agent.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. from llm import create_model
  2. from config import load_config
  3. from langchain_mcp_adapters.client import MultiServerMCPClient
  4. from langchain.agents import create_agent
  5. import asyncio
  6. mcp_client=MultiServerMCPClient(
  7. {
  8. "amap": {
  9. "transport": "streamable_http",
  10. "url": "https://mcp.api-inference.modelscope.net/847991bb62714b/mcp"
  11. }
  12. }
  13. )
  14. config=load_config()
  15. llm = create_model(config)
  16. async def ask_agent(question:str)->str:
  17. tools= await mcp_client.get_tools()
  18. agent = create_agent(
  19. model=llm,
  20. tools=tools,
  21. system_prompt="你是⼀个出⾏助⼿,可以使⽤地图⼯具帮⽤户查天⽓、规划路线。回答要简洁,不要编造数据。",
  22. )
  23. # 第三步:执⾏对话,让 LLM ⾃行判断是否需要调⽤⼯具
  24. result =await agent.ainvoke({
  25. "messages": [{"role": "user", "content": question}]
  26. })
  27. # 第四步:返回最后⼀条消息(即 LLM 的最终回复)
  28. return result["messages"][-1].content
  29. async def main():
  30. # 查天⽓——LLM 会⾃动调⽤ amap 的天⽓⼯具
  31. weather = await ask_agent("成都今天天⽓怎么样?")
  32. print(f"天⽓查询结果:{weather}\n")
  33. # 规划路线——不同的问题,LLM 会选择不同的⼯具
  34. route =await ask_agent("帮我规划⼀条从春熙路到双流机场的地铁换乘路线")
  35. print(f"路线规划结果:{route}")
  36. if __name__ == "__main__":
  37. asyncio.run(main())