Skip to content

Handle the case where OpenAI ChatCompletion created is None #1764

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions pydantic_ai_slim/pydantic_ai/models/openai.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from pydantic_ai.providers import Provider, infer_provider

from .. import ModelHTTPError, UnexpectedModelBehavior, _utils, usage
from .._utils import guard_tool_call_id as _guard_tool_call_id
from .._utils import guard_tool_call_id as _guard_tool_call_id, now_utc as _now_utc
from ..messages import (
AudioUrl,
BinaryContent,
Expand Down Expand Up @@ -298,7 +298,11 @@ async def _completions_create(

def _process_response(self, response: chat.ChatCompletion) -> ModelResponse:
"""Process a non-streamed response, and prepare a message to return."""
timestamp = datetime.fromtimestamp(response.created, tz=timezone.utc)
if response.created:
timestamp = datetime.fromtimestamp(response.created, tz=timezone.utc)
else:
timestamp = _now_utc()

choice = response.choices[0]
items: list[ModelResponsePart] = []
if choice.message.content is not None:
Expand Down Expand Up @@ -554,7 +558,11 @@ def customize_request_parameters(self, model_request_parameters: ModelRequestPar

def _process_response(self, response: responses.Response) -> ModelResponse:
"""Process a non-streamed response, and prepare a message to return."""
timestamp = datetime.fromtimestamp(response.created_at, tz=timezone.utc)
if response.created_at:
timestamp = datetime.fromtimestamp(response.created_at, tz=timezone.utc)
else:
timestamp = _now_utc()

items: list[ModelResponsePart] = []
items.append(TextPart(response.output_text))
for item in response.output:
Expand Down
36 changes: 36 additions & 0 deletions tests/models/test_openai.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,19 @@ def completion_message(message: ChatCompletionMessage, *, usage: CompletionUsage
)


def completion_message_created_none(
message: ChatCompletionMessage, *, usage: CompletionUsage | None = None
) -> chat.ChatCompletion:
return chat.ChatCompletion.model_construct(
created=None,
id='123',
choices=[Choice(finish_reason='stop', index=0, message=message)],
model='gpt-4o-123',
object='chat.completion',
usage=usage,
)


async def test_request_simple_success(allow_model_requests: None):
c = completion_message(ChatCompletionMessage(content='world', role='assistant'))
mock_client = MockOpenAI.create_mock(c)
Expand Down Expand Up @@ -389,6 +402,29 @@ async def get_location(loc_name: str) -> str:
)


async def test_request_created_at_none(allow_model_requests: None):
c = completion_message_created_none(
ChatCompletionMessage(content='world', role='assistant'),
)
mock_client = MockOpenAI.create_mock(c)
m = OpenAIModel('gpt-4o', provider=OpenAIProvider(openai_client=mock_client))
agent = Agent(m)

result = await agent.run('Hello')
assert result.output == 'world'
assert result.all_messages() == snapshot(
[
ModelRequest(parts=[UserPromptPart(content='Hello', timestamp=IsNow(tz=timezone.utc))]),
ModelResponse(
parts=[TextPart(content='world')],
usage=Usage(requests=1),
model_name='gpt-4o-123',
timestamp=IsNow(tz=timezone.utc),
),
]
)


FinishReason = Literal['stop', 'length', 'tool_calls', 'content_filter', 'function_call']


Expand Down
Loading