Skip to content
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

Validate chatcompletion to avoid unexpected bugs #551

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
2 changes: 2 additions & 0 deletions pydantic_ai_slim/pydantic_ai/models/openai.py
Copy link

@rluijk rluijk Dec 28, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just my two cents. The second use of response in _map_usage(response) is not explicitly validated. The validation check (response.created) occurs only inside _process_response. This means that _map_usage(response) operates on an unvalidated response, which could lead to unexpected issues if the response is invalid. (in the async def request).

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

O, heck, I overlooked that the exception raised in _process_response ensures _map_usage cannot receive the response if it’s invalid. This guarantees the response is always validated before being passed further.

Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,8 @@ async def _completions_create(
@staticmethod
def _process_response(response: chat.ChatCompletion) -> ModelResponse:
"""Process a non-streamed response, and prepare a message to return."""
if not response.created:
raise UnexpectedModelBehavior('Response has no timestamp', body=response.to_json())
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

better to just use now_utc like we do for other models.

timestamp = datetime.fromtimestamp(response.created, tz=timezone.utc)
choice = response.choices[0]
items: list[ModelResponsePart] = []
Expand Down
11 changes: 11 additions & 0 deletions tests/models/test_openai.py
Original file line number Diff line number Diff line change
Expand Up @@ -473,6 +473,17 @@ async def test_no_content(allow_model_requests: None):
pass


async def test_no_sync_content(allow_model_requests: None):
mock_client = MockOpenAI.create_mock(
chat.ChatCompletion(id='', choices=[], created=0, model='', object='chat.completion')
)
m = OpenAIModel('gpt-4', openai_client=mock_client)
agent = Agent(m, result_type=MyTypedDict)

with pytest.raises(UnexpectedModelBehavior, match='Response has no timestamp'):
await agent.run('')


async def test_no_delta(allow_model_requests: None):
stream = (
chunk([]),
Expand Down
Loading