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

Fix OpenAI streaming empty chunk error #69

Merged
merged 2 commits into from
May 1, 2024
Merged
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
4 changes: 2 additions & 2 deletions logfire/_internal/integrations/openai.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,14 +180,14 @@ def get_endpoint_config(options: FinalRequestOptions | None) -> EndpointConfig:
message_template='Chat Completion with {request_data[model]!r}',
span_data={'request_data': json_data},
on_response=on_chat_response,
content_from_stream=lambda chunk: chunk.choices[0].delta.content,
content_from_stream=lambda chunk: chunk.choices[0].delta.content if chunk and chunk.choices else None,
)
elif url == '/completions':
return EndpointConfig(
message_template='Completion with {request_data[model]!r}',
span_data={'request_data': json_data},
on_response=on_completion_response,
content_from_stream=lambda chunk: chunk.choices[0].text,
content_from_stream=lambda chunk: chunk.choices[0].text if chunk and chunk.choices else None,
)
elif url == '/embeddings':
return EndpointConfig(
Expand Down
163 changes: 139 additions & 24 deletions tests/otel_integrations/test_openai.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,34 +40,46 @@ def request_handler(request: httpx.Request) -> httpx.Response:
if request.url == 'https://api.openai.com/v1/chat/completions':
json_body = json.loads(request.content)
if json_body.get('stream'):
chunks = [
cc_chunk.ChatCompletionChunk(
if json_body['messages'][0]['content'] == 'empty response chunk':
return httpx.Response(200, text='data: []\n\n')
elif json_body['messages'][0]['content'] == 'empty choices in response chunk':
chunk = cc_chunk.ChatCompletionChunk(
id='1',
choices=[
cc_chunk.Choice(index=0, delta=cc_chunk.ChoiceDelta(content='The answer', role='assistant'))
],
created=1,
model='gpt-4',
object='chat.completion.chunk',
),
cc_chunk.ChatCompletionChunk(
id='2',
choices=[
cc_chunk.Choice(index=1, delta=cc_chunk.ChoiceDelta(content=' is Nine', role='assistant'))
],
created=1,
model='gpt-4',
object='chat.completion.chunk',
),
cc_chunk.ChatCompletionChunk(
id='3',
choices=[cc_chunk.Choice(index=2, delta=cc_chunk.ChoiceDelta(content=None, role='assistant'))],
choices=[],
created=1,
model='gpt-4',
object='chat.completion.chunk',
),
]
return httpx.Response(200, text=''.join(f'data: {chunk.model_dump_json()}\n\n' for chunk in chunks))
)
return httpx.Response(200, text=f'data: {chunk.model_dump_json()}\n\n')
else:
chunks = [
cc_chunk.ChatCompletionChunk(
id='1',
choices=[
cc_chunk.Choice(index=0, delta=cc_chunk.ChoiceDelta(content='The answer', role='assistant'))
],
created=1,
model='gpt-4',
object='chat.completion.chunk',
),
cc_chunk.ChatCompletionChunk(
id='2',
choices=[
cc_chunk.Choice(index=1, delta=cc_chunk.ChoiceDelta(content=' is Nine', role='assistant'))
],
created=1,
model='gpt-4',
object='chat.completion.chunk',
),
cc_chunk.ChatCompletionChunk(
id='3',
choices=[cc_chunk.Choice(index=2, delta=cc_chunk.ChoiceDelta(content=None, role='assistant'))],
created=1,
model='gpt-4',
object='chat.completion.chunk',
),
]
return httpx.Response(200, text=''.join(f'data: {chunk.model_dump_json()}\n\n' for chunk in chunks))
else:
return httpx.Response(
200,
Expand Down Expand Up @@ -351,6 +363,109 @@ async def test_async_chat_completions(instrumented_async_client: openai.AsyncCli
)


def test_sync_chat_empty_response_chunk(instrumented_client: openai.Client, exporter: TestExporter) -> None:
response = instrumented_client.chat.completions.create(
model='gpt-4',
messages=[{'role': 'system', 'content': 'empty response chunk'}],
stream=True,
)
combined = [chunk for chunk in response]
assert combined == [[]]
assert exporter.exported_spans_as_dict() == snapshot(
[
{
'name': 'Chat Completion with {request_data[model]!r}',
'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False},
'parent': None,
'start_time': 1000000000,
'end_time': 2000000000,
'attributes': {
'code.filepath': 'openai.py',
'code.function': 'instrumented_openai_request',
'code.lineno': 123,
'request_data': '{"messages":[{"role":"system","content":"empty response chunk"}],"model":"gpt-4","stream":true}',
'async': False,
'logfire.msg_template': 'Chat Completion with {request_data[model]!r}',
'logfire.msg': "Chat Completion with 'gpt-4'",
'logfire.json_schema': '{"type":"object","properties":{"request_data":{"type":"object"},"async":{}}}',
'logfire.span_type': 'span',
},
},
{
'name': 'streaming response from {request_data[model]!r}',
'context': {'trace_id': 2, 'span_id': 3, 'is_remote': False},
'parent': None,
'start_time': 3000000000,
'end_time': 4000000000,
'attributes': {
'code.filepath': 'openai.py',
'code.function': '__stream__',
'code.lineno': 123,
'request_data': '{"messages":[{"role":"system","content":"empty response chunk"}],"model":"gpt-4","stream":true}',
'async': False,
'logfire.msg_template': 'streaming response from {request_data[model]!r}',
'logfire.msg': "streaming response from 'gpt-4'",
'logfire.span_type': 'span',
'response_data': '{"combined_chunk_content":"","chunk_count":0}',
'logfire.json_schema': '{"type":"object","properties":{"request_data":{"type":"object"},"async":{},"response_data":{"type":"object"}}}',
},
},
]
)


def test_sync_chat_empty_response_choices(instrumented_client: openai.Client, exporter: TestExporter) -> None:
response = instrumented_client.chat.completions.create(
model='gpt-4',
messages=[{'role': 'system', 'content': 'empty choices in response chunk'}],
stream=True,
)
combined = [chunk for chunk in response]
assert len(combined) == 1
assert combined[0].choices == []
assert exporter.exported_spans_as_dict() == snapshot(
[
{
'name': 'Chat Completion with {request_data[model]!r}',
'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False},
'parent': None,
'start_time': 1000000000,
'end_time': 2000000000,
'attributes': {
'code.filepath': 'openai.py',
'code.function': 'instrumented_openai_request',
'code.lineno': 123,
'request_data': '{"messages":[{"role":"system","content":"empty choices in response chunk"}],"model":"gpt-4","stream":true}',
'async': False,
'logfire.msg_template': 'Chat Completion with {request_data[model]!r}',
'logfire.msg': "Chat Completion with 'gpt-4'",
'logfire.json_schema': '{"type":"object","properties":{"request_data":{"type":"object"},"async":{}}}',
'logfire.span_type': 'span',
},
},
{
'name': 'streaming response from {request_data[model]!r}',
'context': {'trace_id': 2, 'span_id': 3, 'is_remote': False},
'parent': None,
'start_time': 3000000000,
'end_time': 4000000000,
'attributes': {
'code.filepath': 'openai.py',
'code.function': '__stream__',
'code.lineno': 123,
'request_data': '{"messages":[{"role":"system","content":"empty choices in response chunk"}],"model":"gpt-4","stream":true}',
'async': False,
'logfire.msg_template': 'streaming response from {request_data[model]!r}',
'logfire.msg': "streaming response from 'gpt-4'",
'logfire.span_type': 'span',
'response_data': '{"combined_chunk_content":"","chunk_count":0}',
'logfire.json_schema': '{"type":"object","properties":{"request_data":{"type":"object"},"async":{},"response_data":{"type":"object"}}}',
},
},
]
)


def test_sync_chat_completions_stream(instrumented_client: openai.Client, exporter: TestExporter) -> None:
response = instrumented_client.chat.completions.create(
model='gpt-4',
Expand Down