|
| 1 | +# pylint: skip-file |
| 2 | +"""Manual OpenAI Agents instrumentation example.""" |
| 3 | + |
| 4 | +from __future__ import annotations |
| 5 | + |
| 6 | +from agents import Agent, Runner, function_tool |
| 7 | +from dotenv import load_dotenv |
| 8 | + |
| 9 | +from opentelemetry import trace |
| 10 | +from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import ( |
| 11 | + OTLPSpanExporter, |
| 12 | +) |
| 13 | +from opentelemetry.instrumentation.openai_agents import ( |
| 14 | + OpenAIAgentsInstrumentor, |
| 15 | +) |
| 16 | +from opentelemetry.sdk.trace import TracerProvider |
| 17 | +from opentelemetry.sdk.trace.export import BatchSpanProcessor |
| 18 | + |
| 19 | + |
| 20 | +def configure_otel() -> None: |
| 21 | + """Configure the OpenTelemetry SDK for exporting spans.""" |
| 22 | + |
| 23 | + provider = TracerProvider() |
| 24 | + provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter())) |
| 25 | + trace.set_tracer_provider(provider) |
| 26 | + |
| 27 | + OpenAIAgentsInstrumentor().instrument(tracer_provider=provider) |
| 28 | + |
| 29 | + |
| 30 | +@function_tool |
| 31 | +def get_weather(city: str) -> str: |
| 32 | + """Return a canned weather response for the requested city.""" |
| 33 | + |
| 34 | + return f"The forecast for {city} is sunny with pleasant temperatures." |
| 35 | + |
| 36 | + |
| 37 | +def run_agent() -> None: |
| 38 | + """Create a simple agent and execute a single run.""" |
| 39 | + |
| 40 | + assistant = Agent( |
| 41 | + name="Travel Concierge", |
| 42 | + instructions=( |
| 43 | + "You are a concise travel concierge. Use the weather tool when the" |
| 44 | + " traveler asks about local conditions." |
| 45 | + ), |
| 46 | + tools=[get_weather], |
| 47 | + ) |
| 48 | + |
| 49 | + result = Runner.run_sync( |
| 50 | + assistant, |
| 51 | + "I'm visiting Barcelona this weekend. How should I pack?", |
| 52 | + ) |
| 53 | + |
| 54 | + print("Agent response:") |
| 55 | + print(result.final_output) |
| 56 | + |
| 57 | + |
| 58 | +def main() -> None: |
| 59 | + load_dotenv() |
| 60 | + configure_otel() |
| 61 | + run_agent() |
| 62 | + |
| 63 | + |
| 64 | +if __name__ == "__main__": |
| 65 | + main() |
0 commit comments