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