1. LangChain结构化输出与多轮对话实战指南
最近在开发一个天气查询机器人时,我深入体验了LangChain的结构化输出和多轮对话功能。作为一个长期从事AI应用开发的工程师,我发现这套工具链能显著提升智能体开发的规范性和可控性。下面我将通过一个完整的天气查询案例,分享如何利用dataclass定义数据结构、用@tool装饰器创建工具函数,以及实现连贯的多轮对话。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 核心组件与环境搭建
2.1 基础库导入与说明
首先需要导入LangChain的核心组件,这里我使用的是Qwen大模型作为基础LLM:
python复制from langchain_openai import ChatOpenAI
from langchain.agents import create_agent
from dataclasses import dataclass
from langchain.tools import tool, ToolRuntime
from langgraph.checkpoint.memory import InMemorySaver
from langchain.agents.structured_output import ToolStrategy
关键组件说明:
ChatOpenAI: LangChain的LLM封装类,支持多种大模型接入create_agent: 智能体工厂函数dataclass: Python内置数据结构定义工具@tool: 将普通函数转换为智能体可调用工具InMemorySaver: 轻量级对话记忆存储ToolStrategy: 结构化输出策略控制器
2.2 大模型配置技巧
我选择Qwen-plus模型作为基础LLM,配置时有几个关键参数需要注意:
python复制llm = ChatOpenAI(
model="qwen-plus",
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
api_key="your_api_key", # 建议从环境变量读取
temperature=0.7 # 控制生成
