Skip to content

Commit 43f39cf

Browse files
committed
fix: check chunk has choises before printing
1 parent 4c41388 commit 43f39cf

File tree

3 files changed

+19
-8
lines changed

3 files changed

+19
-8
lines changed

llm_observability_examples.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,8 @@ def main_sync():
2929

3030
try:
3131
basic_openai_call(distinct_id, trace_id, properties)
32-
# streaming_openai_call(distinct_id, trace_id, properties)
33-
# non_instrumented_openai_call()
32+
streaming_openai_call(distinct_id, trace_id, properties)
33+
non_instrumented_openai_call()
3434
except Exception as e:
3535
print("Error during OpenAI call:", str(e))
3636

@@ -106,7 +106,8 @@ def streaming_openai_call(distinct_id, trace_id, properties):
106106
)
107107

108108
for chunk in response:
109-
print(chunk.choices[0].delta.content or "", end="")
109+
if hasattr(chunk, "choices") and chunk.choices and len(chunk.choices) > 0:
110+
print(chunk.choices[0].delta.content or "", end="")
110111

111112
return response
112113

@@ -127,7 +128,8 @@ async def streaming_async_openai_call(distinct_id, trace_id, properties):
127128
)
128129

129130
async for chunk in response:
130-
print(chunk.choices[0].delta.content or "", end="")
131+
if hasattr(chunk, "choices") and chunk.choices and len(chunk.choices) > 0:
132+
print(chunk.choices[0].delta.content or "", end="")
131133

132134
return response
133135

posthog/ai/providers/openai/openai.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -100,9 +100,14 @@ def generator():
100100
"total_tokens",
101101
]
102102
}
103-
if chunk.choices[0].delta.content:
104-
accumulated_content.append(chunk.choices[0].delta.content)
103+
104+
if hasattr(chunk, "choices") and chunk.choices and len(chunk.choices) > 0:
105+
content = chunk.choices[0].delta.content
106+
if content:
107+
accumulated_content.append(content)
108+
105109
yield chunk
110+
106111
finally:
107112
end_time = time.time()
108113
latency = end_time - start_time

posthog/ai/providers/openai/openai_async.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -100,9 +100,13 @@ async def async_generator():
100100
"total_tokens",
101101
]
102102
}
103-
if chunk.choices[0].delta.content:
104-
accumulated_content.append(chunk.choices[0].delta.content)
103+
if hasattr(chunk, "choices") and chunk.choices and len(chunk.choices) > 0:
104+
content = chunk.choices[0].delta.content
105+
if content:
106+
accumulated_content.append(content)
107+
105108
yield chunk
109+
106110
finally:
107111
end_time = time.time()
108112
latency = end_time - start_time

0 commit comments

Comments
 (0)