"""
LangChain 1.0 基础教程 - 第一个 LLM 调用
==========================================
本文件演示如何使用 LangChain 1.0 进行基本的 LLM 调用
涵盖以下核心概念:
1. init_chat_model - 初始化聊天模型
2. invoke - 同步调用模型
3. Messages - 消息类型(System, Human, AI)
4. 基本配置和参数
作者:zhangsan
日期:2026年3月5日
"""
import os
from dotenv import load_dotenv
from langchain.chat_models import init_chat_model
from langchain_core.messages import HumanMessage, SystemMessage, AIMessage
from langchain.agents import create_agent
from fastapi import FastAPI, Query
# ============================================================================
# 环境配置
# ============================================================================
# 加载环境变量
load_dotenv()
# 获取千问API密钥
qwen_config = {
"api_key": os.getenv("QWEN_API_KEY"),
"base_url": "https://dashscope.aliyuncs.com/compatible-mode/v1", # 请求地址
"model_name": "qwen3.5-flash",
}
model_config = qwen_config
chat_model = init_chat_model(
model=f"{model_config['model_name']}",
model_provider="openai", # 使用 openai 提供者来兼容 DashScope 接口
api_key=model_config["api_key"],
base_url=model_config["base_url"],
temperature=0.3,
)
# ============================================================================
# 示例 LLM 调用
# ============================================================================
def example1():
response = chat_model.invoke("什么是机器学习?用一句话解释")
print(response.content)
# 机器学习是一种让计算机通过分析数据自动学习规律,从而在没有显式编程的情况下实现预测或决策的技 术。
# ============================================================================
# 示例 2:使用消息列表进行对话
# ============================================================================
def example2():
"""
示例2:使用消息列表
核心概念:
- SystemMessage: 系统消息,用于设定 AI 的行为和角色
- HumanMessage: 用户消息
- AIMessage: AI 的回复消息
消息列表允许你构建多轮对话历史
"""
messages = [
SystemMessage(content="你是一个专业的 Python 编程导师。回答要简洁、准确。"),
HumanMessage(content="什么是 Python 列表推导式?请简单说明"),
]
response = chat_model.invoke(messages)
# 继续对话:将 AI 的回复添加到对话历史
messages.append(AIMessage(content=response.content))
messages.append(HumanMessage(content="HumanMessage"))
print(response.content)
# ============================================================================
# 示例 3:使用字典格式的消息
# ============================================================================
def example3():
"""
示例3:使用字典格式的消息
LangChain 1.0 支持更简洁的字典格式:
{"role": "system"/"user"/"assistant", "content": "消息内容"}
这种格式与 OpenAI API 的格式一致,更易于使用
"""
messages = [
{"role": "system", "content": "你是一个专业的数学老师。"},
{"role": "user", "content": "什么是斐波那契数列?请简单说明"},
]
print("消息列表:")
for msg in messages:
print(f" {msg['role']}: {msg['content']}")
response = chat_model.invoke(messages)
print(f"AI 回复: {response.content}")
# ============================================================================
# 示例 4:理解 invoke 方法的返回值
# ============================================================================
def example4():
"""
示例5:深入理解 invoke 返回值
invoke 方法返回一个 AIMessage 对象,包含:
- content: 模型的文本回复
- response_metadata: 响应元数据(如 token 使用量、模型信息等)
- additional_kwargs: 额外的关键字参数
- id: 消息 ID
"""
response = chat_model.invoke("解释一下什么是大模型?用一句话。")
print(f"AI 回复: {response.content}")
print(f"响应元数据: {response.response_metadata}")
print(f"额外参数: {response.additional_kwargs}")
print(f"消息 ID: {response.id}")
# 检查 token 使用情况(如果可用)
print(
f"Token 使用量: {response.response_metadata.get('token_usage', {}).get('total_tokens', '未提供')}"
)
# ============================================================================
# 实战 - 构建一个简单的聊天机器人
# ============================================================================
def chatbot():
"""
简单的聊天机器人
功能:
- 接收用户输入
- 调用模型生成回复
- 显示回复
"""
# 初始化对话
conversation = [
{"role": "system", "content": "你是一个友好、幽默的助手,喜欢帮助用户"}
]
# 模拟几轮对话(非交互式)
demo_questions = ["你好!", "你能做什么?", "我想学做饭", "鱼香肉丝怎么做"]
# 模拟对话
for question in demo_questions:
# 构建消息列表
messages = conversation + [{"role": "user", "content": question}]
response = chat_model.invoke(messages)
conversation.append({"role": "user", "content": question})
conversation.append({"role": "assistant", "content": response.content})
# 调用模型
# 显示回复
print(f"你: {question}")
print(f"机器人: {response.content}")
# ============================================================================
# 主程序
# ============================================================================
def main():
# example1()
# example2()
# example3()
# example4()
chatbot()
if __name__ == "__main__":
main()