You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

gpt5_agent_integration.py 20 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. #!/usr/bin/env python3
  2. """
  3. GPT-5 Agent Integration Examples for AutoGen
  4. This script demonstrates how to integrate GPT-5's advanced features
  5. with AutoGen agents and multi-agent systems:
  6. 1. GPT-5 powered AssistantAgent with reasoning control
  7. 2. Multi-agent systems with GPT-5 optimization
  8. 3. Specialized agents for different GPT-5 capabilities
  9. 4. Agent conversation with chain-of-thought preservation
  10. 5. Tool-specialized agents with custom GPT-5 tools
  11. This showcases enterprise-grade patterns for GPT-5 integration.
  12. """
  13. import asyncio
  14. import os
  15. from typing import Any, Dict, Literal, Optional
  16. from autogen_core import CancellationToken
  17. from autogen_core.models import UserMessage
  18. from autogen_core.tools import BaseCustomTool, CustomToolFormat
  19. from autogen_ext.models.openai import OpenAIChatCompletionClient, OpenAIResponsesAPIClient
  20. from pydantic import BaseModel
  21. import json
  22. class TextResult(BaseModel):
  23. text: str
  24. def _coerce_content_to_text(content: object) -> str:
  25. if isinstance(content, str):
  26. return content
  27. try:
  28. return json.dumps(content, ensure_ascii=False, default=str)
  29. except Exception:
  30. return str(content)
  31. class DataAnalysisTool(BaseCustomTool[TextResult]):
  32. """GPT-5 custom tool for data analysis with freeform input."""
  33. def __init__(self):
  34. super().__init__(
  35. return_type=TextResult,
  36. name="data_analysis",
  37. description="Analyze data and generate insights. Input should be data description or analysis request.",
  38. )
  39. async def run(self, input_text: str, cancellation_token: CancellationToken) -> TextResult:
  40. """Simulate data analysis."""
  41. # In production, this would connect to data analysis tools
  42. analysis_types = {
  43. "trend": "📈 Trend analysis shows upward trajectory with seasonal variations",
  44. "correlation": "🔗 Strong positive correlation (r=0.85) detected between variables",
  45. "outlier": "⚠️ 3 outliers detected requiring attention",
  46. "summary": "📊 Dataset summary: 1000 records, normal distribution, complete data"
  47. }
  48. analysis_type = "summary" # Default
  49. for key in analysis_types:
  50. if key in input_text.lower():
  51. analysis_type = key
  52. break
  53. return TextResult(text=f"Data Analysis Results:\n{analysis_types[analysis_type]}\n\nDetailed analysis: {input_text}")
  54. class ResearchTool(BaseCustomTool[TextResult]):
  55. """GPT-5 custom tool for research tasks."""
  56. def __init__(self):
  57. super().__init__(
  58. return_type=TextResult,
  59. name="research",
  60. description="Conduct research and gather information on specified topics.",
  61. )
  62. async def run(self, input_text: str, cancellation_token: CancellationToken) -> TextResult:
  63. """Simulate research functionality."""
  64. return TextResult(
  65. text=(
  66. f"🔍 Research Results for: {input_text}\n"
  67. f"• Found 15 relevant academic papers\n"
  68. f"• Identified 3 key trends\n"
  69. f"• Generated comprehensive summary with citations\n"
  70. f"• Confidence level: High"
  71. )
  72. )
  73. class CodeReviewTool(BaseCustomTool[TextResult]):
  74. """GPT-5 custom tool with grammar constraints for code review."""
  75. def __init__(self):
  76. # Define grammar for code review requests
  77. code_review_grammar = CustomToolFormat(
  78. type="grammar",
  79. syntax="lark",
  80. definition="""
  81. start: review_request
  82. review_request: "REVIEW" language_spec code_block review_type?
  83. language_spec: "LANG:" IDENTIFIER
  84. code_block: "CODE:" code_content
  85. code_content: /[\\s\\S]+/
  86. review_type: "TYPE:" review_focus
  87. review_focus: "security" | "performance" | "style" | "bugs" | "all"
  88. IDENTIFIER: /[a-zA-Z_][a-zA-Z0-9_+#-]*/
  89. %import common.WS
  90. %ignore WS
  91. """
  92. )
  93. super().__init__(
  94. return_type=TextResult,
  95. name="code_review",
  96. description="Review code with structured input. Format: REVIEW LANG:python CODE:your_code TYPE:security",
  97. format=code_review_grammar,
  98. )
  99. async def run(self, input_text: str, cancellation_token: CancellationToken) -> TextResult:
  100. """Perform structured code review."""
  101. return TextResult(
  102. text=(
  103. f"📝 Code Review Complete:\n"
  104. f"Input: {input_text}\n"
  105. f"✅ No security vulnerabilities found\n"
  106. f"⚡ Performance suggestions: Use list comprehension\n"
  107. f"🎨 Style: Follows PEP 8 guidelines\n"
  108. f"🐛 No bugs detected\n"
  109. f"Overall: Production ready"
  110. )
  111. )
  112. ReasoningEffort = Literal["minimal", "low", "medium", "high"]
  113. class GPT5ReasoningAgent:
  114. """Assistant agent optimized for GPT-5 reasoning tasks."""
  115. def __init__(self, name: str, reasoning_effort: ReasoningEffort = "high"):
  116. self.name = name
  117. self.client = OpenAIChatCompletionClient(
  118. model="gpt-5",
  119. api_key=os.getenv("OPENAI_API_KEY", "your-api-key-here")
  120. )
  121. self.reasoning_effort: ReasoningEffort = reasoning_effort
  122. # Configure for reasoning tasks
  123. self.system_message = """
  124. You are a reasoning specialist powered by GPT-5. Your role is to:
  125. 1. Break down complex problems into manageable parts
  126. 2. Apply systematic thinking and analysis
  127. 3. Provide clear explanations of your reasoning process
  128. 4. Verify conclusions and consider alternative perspectives
  129. Use your advanced reasoning capabilities to provide thoughtful, well-structured responses.
  130. """
  131. async def process_request(self, user_input: str) -> str:
  132. """Process user request with optimized reasoning."""
  133. response = await self.client.create(
  134. messages=[
  135. UserMessage(content=self.system_message, source="system"),
  136. UserMessage(content=user_input, source="user")
  137. ],
  138. reasoning_effort=self.reasoning_effort,
  139. verbosity="high", # Detailed explanations
  140. preambles=True
  141. )
  142. return _coerce_content_to_text(response.content)
  143. class GPT5CodeAgent:
  144. """Assistant agent optimized for GPT-5 code generation tasks."""
  145. def __init__(self, name: str):
  146. self.name = name
  147. self.client = OpenAIChatCompletionClient(
  148. model="gpt-5",
  149. api_key=os.getenv("OPENAI_API_KEY", "your-api-key-here")
  150. )
  151. # Initialize code-related tools
  152. self.code_review_tool = CodeReviewTool()
  153. self.system_message = """
  154. You are a code generation specialist powered by GPT-5. Your role is to:
  155. 1. Generate high-quality, production-ready code
  156. 2. Follow best practices and coding standards
  157. 3. Provide clear documentation and comments
  158. 4. Consider security, performance, and maintainability
  159. Use your advanced capabilities to write excellent code.
  160. """
  161. async def process_request(self, user_input: str) -> str:
  162. """Process code-related requests."""
  163. response = await self.client.create(
  164. messages=[
  165. UserMessage(content=self.system_message, source="system"),
  166. UserMessage(content=user_input, source="user")
  167. ],
  168. tools=[self.code_review_tool],
  169. reasoning_effort="low", # Code tasks need less reasoning
  170. verbosity="medium",
  171. preambles=True # Explain code choices
  172. )
  173. return _coerce_content_to_text(response.content)
  174. class GPT5AnalysisAgent:
  175. """Assistant agent optimized for data analysis with GPT-5."""
  176. def __init__(self, name: str):
  177. self.name = name
  178. self.client = OpenAIChatCompletionClient(
  179. model="gpt-5-mini", # Cost-effective for analysis tasks
  180. api_key=os.getenv("OPENAI_API_KEY", "your-api-key-here")
  181. )
  182. # Initialize analysis tools
  183. self.data_tool = DataAnalysisTool()
  184. self.research_tool = ResearchTool()
  185. self.system_message = """
  186. You are a data analysis specialist powered by GPT-5. Your role is to:
  187. 1. Analyze data patterns and trends
  188. 2. Generate actionable insights
  189. 3. Create clear visualizations and reports
  190. 4. Provide evidence-based recommendations
  191. Use your analytical capabilities to uncover valuable insights.
  192. """
  193. async def process_request(self, user_input: str) -> str:
  194. """Process analysis requests."""
  195. response = await self.client.create(
  196. messages=[
  197. UserMessage(content=self.system_message, source="system"),
  198. UserMessage(content=user_input, source="user")
  199. ],
  200. tools=[self.data_tool, self.research_tool],
  201. reasoning_effort="medium",
  202. verbosity="high", # Detailed analysis reports
  203. preambles=True
  204. )
  205. return _coerce_content_to_text(response.content)
  206. class GPT5ConversationManager:
  207. """Manages multi-turn conversations with chain-of-thought preservation."""
  208. def __init__(self):
  209. self.client = OpenAIResponsesAPIClient(
  210. model="gpt-5",
  211. api_key=os.getenv("OPENAI_API_KEY", "your-api-key-here")
  212. )
  213. self.conversation_history: list[dict[str, Any]] = []
  214. self.last_response_id: Optional[str] = None
  215. async def continue_conversation(self, user_input: str, reasoning_effort: ReasoningEffort = "medium") -> Dict[str, Any]:
  216. """Continue conversation with CoT preservation."""
  217. response = await self.client.create(
  218. input=user_input,
  219. previous_response_id=self.last_response_id,
  220. reasoning_effort=reasoning_effort,
  221. verbosity="medium",
  222. preambles=True
  223. )
  224. # Update conversation state
  225. self.conversation_history.append({
  226. "user_input": user_input,
  227. "response": _coerce_content_to_text(response.content),
  228. "reasoning": response.thought,
  229. "response_id": getattr(response, 'response_id', None)
  230. })
  231. self.last_response_id = getattr(response, 'response_id', None)
  232. return {
  233. "content": _coerce_content_to_text(response.content),
  234. "reasoning": response.thought,
  235. "usage": response.usage,
  236. "turn_number": len(self.conversation_history)
  237. }
  238. async def demonstrate_gpt5_reasoning_agent():
  239. """Demonstrate specialized reasoning agent."""
  240. print("🧠 GPT-5 Reasoning Agent Example")
  241. print("=" * 50)
  242. reasoning_agent = GPT5ReasoningAgent("ReasoningSpecialist", reasoning_effort="high")
  243. complex_problem = """
  244. A company has three departments: Engineering (50 people), Sales (30 people), and Marketing (20 people).
  245. They want to form cross-functional teams of 5 people each, with at least one person from each department.
  246. What's the maximum number of teams they can form, and how should they distribute people?
  247. """
  248. print("Complex Problem:")
  249. print(complex_problem)
  250. print("\nReasoning Agent Response:")
  251. response = await reasoning_agent.process_request(complex_problem)
  252. print(response)
  253. await reasoning_agent.client.close()
  254. async def demonstrate_gpt5_code_agent():
  255. """Demonstrate specialized code generation agent."""
  256. print("\n💻 GPT-5 Code Agent Example")
  257. print("=" * 50)
  258. code_agent = GPT5CodeAgent("CodeSpecialist")
  259. code_request = """
  260. Create a Python class for a thread-safe LRU cache with the following requirements:
  261. 1. Maximum capacity that can be set at initialization
  262. 2. get() and put() methods
  263. 3. Thread safety using locks
  264. 4. O(1) average time complexity for both operations
  265. 5. Proper error handling
  266. """
  267. print("Code Request:")
  268. print(code_request)
  269. print("\nCode Agent Response:")
  270. response = await code_agent.process_request(code_request)
  271. print(response)
  272. await code_agent.client.close()
  273. async def demonstrate_gpt5_analysis_agent():
  274. """Demonstrate data analysis agent with custom tools."""
  275. print("\n📊 GPT-5 Analysis Agent Example")
  276. print("=" * 50)
  277. analysis_agent = GPT5AnalysisAgent("AnalysisSpecialist")
  278. analysis_request = """
  279. I have sales data showing monthly revenue for the past 2 years.
  280. The data shows seasonal patterns with peaks in Q4 and dips in Q1.
  281. Can you analyze this trend data and provide insights for business planning?
  282. """
  283. print("Analysis Request:")
  284. print(analysis_request)
  285. print("\nAnalysis Agent Response:")
  286. response = await analysis_agent.process_request(analysis_request)
  287. print(response)
  288. await analysis_agent.client.close()
  289. async def demonstrate_multi_turn_conversation():
  290. """Demonstrate multi-turn conversation with CoT preservation."""
  291. print("\n💬 GPT-5 Multi-Turn Conversation Example")
  292. print("=" * 50)
  293. conversation_manager = GPT5ConversationManager()
  294. # Turn 1: Initial complex question
  295. print("\nTurn 1: Initial Architecture Question")
  296. response1 = await conversation_manager.continue_conversation(
  297. "Design a microservices architecture for an e-commerce platform that needs to handle 1 million daily active users",
  298. reasoning_effort="high"
  299. )
  300. print(f"Response: {response1['content'][:300]}...")
  301. print(f"Turn: {response1['turn_number']}, Tokens: {response1['usage'].total_tokens}")
  302. # Turn 2: Follow-up with context preservation
  303. print("\nTurn 2: Follow-up on Database Strategy")
  304. response2 = await conversation_manager.continue_conversation(
  305. "How would you handle database sharding and data consistency in this architecture?",
  306. reasoning_effort="medium" # Lower effort due to preserved context
  307. )
  308. print(f"Response: {response2['content'][:300]}...")
  309. print(f"Turn: {response2['turn_number']}, Tokens: {response2['usage'].total_tokens}")
  310. # Turn 3: Implementation details
  311. print("\nTurn 3: Implementation Details")
  312. response3 = await conversation_manager.continue_conversation(
  313. "Show me the API design for the user service with authentication",
  314. reasoning_effort="low" # Minimal reasoning needed with established context
  315. )
  316. print(f"Response: {response3['content'][:300]}...")
  317. print(f"Turn: {response3['turn_number']}, Tokens: {response3['usage'].total_tokens}")
  318. print(f"\nTotal conversation turns: {len(conversation_manager.conversation_history)}")
  319. await conversation_manager.client.close()
  320. async def demonstrate_agent_collaboration():
  321. """Demonstrate multiple GPT-5 agents working together."""
  322. print("\n🤝 GPT-5 Multi-Agent Collaboration Example")
  323. print("=" * 50)
  324. # Initialize specialized agents
  325. reasoning_agent = GPT5ReasoningAgent("Strategist", reasoning_effort="high")
  326. code_agent = GPT5CodeAgent("Developer")
  327. analysis_agent = GPT5AnalysisAgent("Analyst")
  328. project_brief = """
  329. Project: Build a real-time analytics dashboard for monitoring website performance
  330. Requirements: Track page load times, user engagement, error rates, and conversion metrics
  331. Constraints: Must handle 10K concurrent users, sub-second query response times
  332. """
  333. print("Project Brief:")
  334. print(project_brief)
  335. # Agent 1: Strategic analysis
  336. print("\n🧠 Strategist (Reasoning Agent):")
  337. strategy_response = await reasoning_agent.process_request(
  338. f"Analyze this project and provide a strategic approach:\n{project_brief}"
  339. )
  340. print(strategy_response[:400] + "...")
  341. # Agent 2: Technical implementation
  342. print("\n💻 Developer (Code Agent):")
  343. code_response = await code_agent.process_request(
  344. f"Based on the strategy, design the technical architecture and provide code examples for the analytics dashboard"
  345. )
  346. print(code_response[:400] + "...")
  347. # Agent 3: Performance analysis
  348. print("\n📊 Analyst (Analysis Agent):")
  349. analysis_response = await analysis_agent.process_request(
  350. f"Analyze the performance requirements and suggest optimization strategies for the dashboard"
  351. )
  352. print(analysis_response[:400] + "...")
  353. print("\n✅ Multi-agent collaboration complete!")
  354. # Cleanup
  355. await reasoning_agent.client.close()
  356. await code_agent.client.close()
  357. await analysis_agent.client.close()
  358. async def demonstrate_tool_specialization():
  359. """Demonstrate agents with different tool specializations."""
  360. print("\n🛠️ GPT-5 Tool Specialization Example")
  361. print("=" * 50)
  362. # Create an agent that restricts tool usage for safety
  363. client = OpenAIChatCompletionClient(
  364. model="gpt-5",
  365. api_key=os.getenv("OPENAI_API_KEY", "your-api-key-here")
  366. )
  367. # All available tools
  368. data_tool = DataAnalysisTool()
  369. research_tool = ResearchTool()
  370. code_review_tool = CodeReviewTool()
  371. all_tools = [data_tool, research_tool, code_review_tool]
  372. safe_tools = [data_tool, research_tool] # Exclude code review for this task
  373. print("Tool Specialization: Data-focused agent (restricted tools)")
  374. response = await client.create(
  375. messages=[UserMessage(
  376. content="I need help analyzing user engagement data and researching industry benchmarks, but I also want code review",
  377. source="user"
  378. )],
  379. tools=all_tools,
  380. allowed_tools=safe_tools, # Restrict to safe tools only
  381. tool_choice="auto",
  382. reasoning_effort="medium",
  383. verbosity="medium",
  384. preambles=True # Explain tool restrictions
  385. )
  386. print(f"Agent Response: {_coerce_content_to_text(response.content)}")
  387. if response.thought:
  388. print(f"Tool Usage Explanation: {response.thought}")
  389. await client.close()
  390. async def main():
  391. """Run all GPT-5 agent integration examples."""
  392. print("🚀 GPT-5 Agent Integration Demo")
  393. print("=" * 60)
  394. print("Showcasing enterprise-grade GPT-5 integration with AutoGen agents")
  395. print("")
  396. try:
  397. # Run all agent examples
  398. await demonstrate_gpt5_reasoning_agent()
  399. await demonstrate_gpt5_code_agent()
  400. await demonstrate_gpt5_analysis_agent()
  401. await demonstrate_multi_turn_conversation()
  402. await demonstrate_agent_collaboration()
  403. await demonstrate_tool_specialization()
  404. print("\n🎉 All GPT-5 agent integration examples completed!")
  405. print("=" * 60)
  406. print("Enterprise Integration Patterns Demonstrated:")
  407. print("• Specialized agents for different GPT-5 capabilities")
  408. print("• Multi-turn conversations with chain-of-thought preservation")
  409. print("• Multi-agent collaboration with GPT-5 optimization")
  410. print("• Tool specialization and access control")
  411. print("• Cost optimization using appropriate model variants")
  412. except Exception as e:
  413. print(f"\n❌ Error running agent examples: {e}")
  414. print("Ensure your OPENAI_API_KEY is set and you have GPT-5 access")
  415. if __name__ == "__main__":
  416. if not os.getenv("OPENAI_API_KEY"):
  417. print("⚠️ Warning: OPENAI_API_KEY environment variable not found.")
  418. print("Please set it with: export OPENAI_API_KEY='your-api-key-here'")
  419. asyncio.run(main())