自定义追踪 演示了高级追踪模式,包括自定义追踪、跨度和复杂多智能体系统的流程组织。 本演示所展示的内容 自定义追踪:在单一流程中对多个智能体运行进行分组 自定义跨度:添加业务逻辑监控点 层次化追踪:用于复杂操作的嵌套跨度 追踪元数据:通过分组和元数据组织追踪 快速入门 安装 OpenAI Agents SDK: 设置环境: 运行智能体: 关键概念 trace() 上下文管理器:创建自定义流程分组 customspan():添加业务逻辑监控 追踪元数据:流程命名与组织 层次结构:用于复杂操作的嵌套跨度 自定义追踪模式 多步骤流程追踪 自定义业务逻辑跨度 层次化跨度 高级功能 追踪元数据与分组 事件追踪 自定义追踪的优势 流程组织 分组相关操作:多个智能体运行集中于单一追踪
演示了高级追踪模式,包括自定义追踪、跨度和复杂多智能体系统的流程组织。
安装 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 翻译服务进行翻译。尽管我们力求准确,但请注意,自动翻译可能存在错误或不准确之处。应以原文语言版本的文档作为权威依据。如需获取关键信息,建议使用专业的人工翻译。对于因使用本翻译而产生的任何误解或误读,我们概不负责。