
需求:开发一个智能体可以帮助用户查询天气信息安装依赖pip install langchain#集成deepseekpip install langchain-deepseek#集成openaipip install langchain-openai步骤1.加载环境变量2.定义工具3.定义Agent4.调用Agent1加载环境变量fromdotenvimportload_dotenv load_dotenv()2定义工具fromlangchain.toolsimporttooltooldefget_weather(location:str)-str:Get the current weather in a given locationreturnfThe current weather in{location}is sunny with a temperature of 25 degrees Celsius.3定义Agentfromlangchain.agentsimportcreate_agent agentcreate_agent(deepseek-chat,tools[get_weather],)4调用Agentprint(正在调用)responseagent.invoke({messages:[{role:user,content:今天吉林天气如何},],})print(调用完成)print(response)执行流程agent是里面的模型是怎么知道我们定义的tools①当你用 tool 装饰一个函数时LangChain 会自动将该函数转换成 Tool 对象并提取以下元信息函数名 → Tool.nameget_weather函数文档字符串docstring → Tool.description“Get the current weather in a given location”参数类型注解如 location: str → 自动生成参数模式args_schema通常是一个 Pydantic 模型描述参数名称、类型、是否必填等。②当创建一个agent需要传入tools列表读取每个 Tool 对象的 name、description、args_schema将这些信息组装成 prompt 的一部分例如 ZERO_SHOT_REACT_DESCRIPTION 类型的 agent 会使用一个固定的 prompt 模板其中包含工具列表的格式化字符串