| 69 | # 重写agent endpoints创建逻辑 |
| 70 | @app.on_event("startup") |
| 71 | def create_agent_endpoints(): |
| 72 | for agent_name, agent_func in registry.agents.items(): |
| 73 | async def create_agent_endpoint( |
| 74 | request: AgentRequest, |
| 75 | func=agent_func |
| 76 | ) -> AgentResponse: |
| 77 | try: |
| 78 | # 创建agent实例 |
| 79 | agent = func(model=request.model) |
| 80 | |
| 81 | # 创建MetaChain实例 |
| 82 | mc = MetaChain() |
| 83 | |
| 84 | # 构建messages |
| 85 | messages = [ |
| 86 | {"role": "user", "content": request.query} |
| 87 | ] |
| 88 | |
| 89 | # 运行agent |
| 90 | response = mc.run( |
| 91 | agent=agent, |
| 92 | messages=messages, |
| 93 | context_storage=request.context_variables, |
| 94 | debug=True |
| 95 | ) |
| 96 | |
| 97 | return AgentResponse( |
| 98 | result=response.messages[-1]['content'], |
| 99 | messages=response.messages, |
| 100 | agent_name=agent.name |
| 101 | ) |
| 102 | |
| 103 | except Exception as e: |
| 104 | raise HTTPException( |
| 105 | status_code=400, |
| 106 | detail=f"Agent execution failed: {str(e)}" |
| 107 | ) |
| 108 | |
| 109 | endpoint = create_agent_endpoint |
| 110 | endpoint.__name__ = f"agent_{agent_name}" |
| 111 | app.post(f"/agents/{agent_name}/run")(endpoint) |
| 112 | |
| 113 | # 获取所有可用的agents信息 |
| 114 | @app.get("/agents") |