Skip to content

Commit e6edd09

Browse files
committed
feat: add tests for openai-agents streaming
1 parent 8357aa2 commit e6edd09

3 files changed

Lines changed: 148 additions & 0 deletions

File tree

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
import asyncio
2+
import os
3+
4+
from agents import Agent, Runner, function_tool
5+
from pydantic import BaseModel
6+
from simpleeval import simple_eval
7+
8+
import sentry_sdk
9+
from sentry_sdk.integrations.openai_agents import OpenAIAgentsIntegration
10+
from sentry_sdk.integrations.stdlib import StdlibIntegration
11+
12+
13+
@function_tool
14+
def calculate(expression: str):
15+
"""
16+
A tool for evaluating mathematical expressions.
17+
Example expressions:
18+
'1.2 * (2 + 4.5)', '12.7 cm to inch'
19+
'sin(45 deg) ^ 2'
20+
"""
21+
# Remove any whitespace
22+
expression = expression.strip()
23+
24+
# Evaluate the expression
25+
result = simple_eval(expression)
26+
27+
# If the result is a float, round it to 6 decimal places
28+
if isinstance(result, float):
29+
result = round(result, 6)
30+
31+
return result
32+
33+
34+
class FinalResult(BaseModel):
35+
number: float
36+
37+
38+
INSTRUCTIONS = (
39+
"You are solving math problems. "
40+
"Reason step by step. "
41+
"Use the calculator when necessary. "
42+
"When you give the final answer, "
43+
"provide an explanation for how you arrived at it. "
44+
)
45+
46+
47+
math_agent = Agent(
48+
name="MathAgent",
49+
instructions=INSTRUCTIONS,
50+
tools=[calculate],
51+
model="gpt-4o",
52+
output_type=FinalResult,
53+
)
54+
55+
56+
PROMPT = (
57+
"A taxi driver earns $9461 per 1-hour of work. "
58+
"If he works 12 hours a day and in 1 hour "
59+
"he uses 12 liters of petrol with a price of $134 for 1 liter. "
60+
"How much money does he earn in one day?"
61+
)
62+
63+
64+
def before_send_transaction(event, hint):
65+
"""Print gen_ai attributes from all spans before sending transaction."""
66+
print("\n" + "=" * 80)
67+
print("TRANSACTION EVENT - Printing all spans with gen_ai attributes")
68+
print("=" * 80)
69+
70+
spans = event.get("spans", [])
71+
for span in spans:
72+
op = span.get("op", "unknown")
73+
description = span.get("description", "no description")
74+
span_id = span.get("span_id", "unknown")
75+
data = span.get("data", {})
76+
77+
# Filter gen_ai prefixed attributes
78+
gen_ai_attrs = {k: v for k, v in data.items() if k.startswith("gen_ai")}
79+
80+
if gen_ai_attrs:
81+
print(f"\nSPAN: {op} - {description}")
82+
print(f"Span ID: {span_id}")
83+
print("gen_ai attributes:")
84+
for key, value in sorted(gen_ai_attrs.items()):
85+
print(f" {key}: {value}")
86+
87+
print("=" * 80 + "\n")
88+
return event
89+
90+
91+
async def main() -> None:
92+
sentry_sdk.init(
93+
dsn=os.environ.get("SENTRY_DSN"),
94+
environment=os.environ.get("ENV", "test"),
95+
traces_sample_rate=1.0,
96+
send_default_pii=True,
97+
# before_send_transaction=before_send_transaction,
98+
integrations=[OpenAIAgentsIntegration()],
99+
disabled_integrations=[
100+
StdlibIntegration(),
101+
],
102+
debug=True,
103+
)
104+
105+
print("Starting streamed run...")
106+
print(f"Input: {PROMPT}")
107+
108+
result = Runner.run_streamed(math_agent, input=PROMPT)
109+
110+
async for event in result.stream_events():
111+
# Ignore raw response event deltas for cleaner output
112+
if event.type == "raw_response_event":
113+
continue
114+
# When the agent updates, print that
115+
elif event.type == "agent_updated_stream_event":
116+
print(f"Agent updated: {event.new_agent.name}")
117+
# When items are generated, print them
118+
elif event.type == "run_item_stream_event":
119+
if event.item.type == "tool_call_item":
120+
# Access tool name from raw_item if available
121+
tool_name = getattr(event.item.raw_item, "name", "unknown")
122+
print(f"-- Tool called: {tool_name}")
123+
elif event.item.type == "tool_call_output_item":
124+
print(f"-- Tool output: {event.item.output}")
125+
elif event.item.type == "message_output_item":
126+
print(f"-- Message output: {event.item}")
127+
128+
print("Done!")
129+
130+
131+
if __name__ == "__main__":
132+
asyncio.run(main())

test-openai-agent-simple/run.sh

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
# exit on first error
44
set -euo pipefail
55

6+
set -a && source .env && set +a
7+
68
# Install uv if it's not installed
79
if ! command -v uv &> /dev/null; then
810
curl -LsSf https://astral.sh/uv/install.sh | sh
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
#!/usr/bin/env bash
2+
3+
# exit on first error
4+
set -euo pipefail
5+
6+
set -a && source .env && set +a
7+
8+
# Install uv if it's not installed
9+
if ! command -v uv &> /dev/null; then
10+
curl -LsSf https://astral.sh/uv/install.sh | sh
11+
fi
12+
13+
# Run the script
14+
uv run python main_streamed.py

0 commit comments

Comments
 (0)