演示了高级追踪模式,包括自定义追踪、跨度和复杂多智能体系统的流程组织。
安装 OpenAI Agents SDK:
pip install openai-agents
设置环境:
cp ../env.example .env # Edit .env and add your OpenAI API key
运行智能体:
import asyncio from agent import main # Test custom tracing patterns asyncio.run(main())
with trace("Research and Analysis Workflow") as workflow_trace: # Step 1: Research research_result = await Runner.run(research_agent, "Research AI in healthcare") # Step 2: Analysis analysis_result = await Runner.run(analysis_agent, f"Analyze: {research_result.final_output}") # Step 3: Summary summary_result = await Runner.run(analysis_agent, f"Summarize: {analysis_result.final_output}")
with trace("Document Processing Workflow") as doc_trace: with custom_span("Data Preparation") as prep_span: # Your business logic here data = prepare_data() prep_span.add_event("Data loaded", {"records": 100}) prep_span.add_event("Data validated", {"errors": 0}) with custom_span("AI Processing") as ai_span: result = await Runner.run(agent, "Process the data") ai_span.add_event("Processing complete", { "output_length": len(result.final_output) })
with trace("E-commerce Order Processing") as order_trace: with custom_span("Order Validation") as validation_span: # Nested span for inventory check with custom_span("Inventory Check") as inventory_span: inventory_span.add_event("Stock verified", {"available": True}) # Nested span for payment validation with custom_span("Payment Validation") as payment_span: payment_span.add_event("Payment authorized", {"amount": 99.99})
conversation_id = "conv_12345" # First interaction in conversation with trace( "Customer Support - Initial Inquiry", group_id=conversation_id, metadata={"customer_id": "cust_789", "priority": "high"} ) as trace1: result1 = await Runner.run(support_agent, "How do I reset my password?") # Follow-up interaction in same conversation with trace( "Customer Support - Follow-up", group_id=conversation_id, metadata={"customer_id": "cust_789", "interaction": 2} ) as trace2: result2 = await Runner.run(support_agent, f"Based on this context: {result1.final_output}")
with custom_span("Business Process") as span: span.add_event("Process started", {"timestamp": datetime.now()}) # Business logic here span.add_event("Milestone reached", {"progress": "50%"}) # More business logic span.add_event("Process completed", {"status": "success"})
免责声明:
本文档采用基于机器的 AI 翻译服务进行翻译。尽管我们力求准确,但请注意,自动翻译可能存在错误或不准确之处。应以原文语言版本的文档作为权威依据。如需获取关键信息,建议使用专业的人工翻译。对于因使用本翻译而产生的任何误解或误读,我们概不负责。