J'Blog

3 课 · 核心

语义检索

基于 Chroma 向量库,与 Workspace 知识库分离。用自然语言描述你想查的内容。 非管理员每人每天可检索 5 次(消耗站点 AI 配额)。

模型集成

原文:模型集成

一句话

模型是 Agent 的推理引擎,驱动决策过程,确定调用哪些工具、如何解释结果以及何时提供最终答案。

什么时候翻这页

当你需要初始化模型、配置模型参数、选择模型提供商、处理模型输出或实现动态模型选择时。

核心概念

模型类型

  • LLMs:大型语言模型,能够解释和生成文本,无需针对每个任务进行专门训练
  • Chat Models:聊天模型,专为对话场景优化,支持多轮对话

模型能力

  • Tool calling:调用外部工具(如数据库查询或API调用)并在响应中使用结果
  • Structured output:模型响应遵循预定义格式
  • Multimodality:处理和返回非文本数据,如图像、音频和视频
  • Reasoning:执行多步推理得出结论

模型接口

  • Invoke:模型接收消息作为输入,生成完整响应后输出消息
  • Stream:实时流式输出,边生成边返回
  • Batch:批量处理多个请求,提高效率

怎么做

初始化模型

使用 init_chat_model 初始化模型:

from langchain.chat_models import init_chat_model

model = init_chat_model("gpt-5.4")

配置模型参数

model = init_chat_model(
    "claude-sonnet-4-6",
    temperature=0.7,
    timeout=30,
    max_tokens=1000,
    max_retries=6
)

调用模型

基本调用

response = model.invoke("Why do parrots talk?")

流式调用

for chunk in model.stream("Why do parrots have colorful feathers?"):
    print(chunk.text, end="", flush=True)

批量调用

responses = model.batch([
    "Why do parrots have colorful feathers?",
    "How do airplanes fly?",
    "What is quantum computing?"
])

动态模型选择

使用 @wrap_model_call 装饰器创建中间件,根据状态动态选择模型:

from langchain.agents.middleware import wrap_model_call, ModelRequest, ModelResponse

@wrap_model_call
def dynamic_model_selection(request: ModelRequest, handler) -> ModelResponse:
    """根据对话复杂度选择模型"""
    message_count = len(request.state["messages"])
    
    if message_count > 10:
        model = advanced_model
    else:
        model = basic_model
    
    return handler(request.override(model=model))

命令 / API 速查

初始化模型

# OpenAI
model = init_chat_model("gpt-5.4", model_provider="openai")

# Anthropic
model = init_chat_model("claude-sonnet-4-6", model_provider="anthropic")

# Azure
model = init_chat_model(
    "azure_openai:gpt-5.4",
    model_provider="azure_openai",
    azure_deployment="deployment_name"
)

# Google Gemini
model = init_chat_model("google_genai:gemini-2.5-flash-lite", model_provider="google_genai")

# AWS Bedrock
model = init_chat_model(
    "anthropic.claude-3-5-sonnet-20240620-v1:0",
    model_provider="bedrock_converse"
)

关键方法

# 调用模型
response = model.invoke("Your question here")

# 流式调用
for chunk in model.stream("Your question here"):
    print(chunk.content)

# 批量调用
responses = model.batch(["Question 1", "Question 2", "Question 3"])

配置选项

# 速率限制
from langchain_core.rate_limiters import InMemoryRateLimiter

rate_limiter = InMemoryRateLimiter(
    requests_per_second=0.1,
    check_every_n_seconds=0.1,
    max_bucket_size=10
)

model = init_chat_model(
    model="gpt-5.4",
    rate_limiter=rate_limiter
)

# 自定义基础URL
model = init_chat_model(
    model="MODEL_NAME",
    model_provider="openai",
    base_url="BASE_URL",
    api_key="YOUR_API_KEY"
)

与 LangGraph / RAG 手册的联系

  • LangGraph:LangGraph 提供了 Agent 的编排运行时,而 LangChain 提供了高层的 Agent 框架。模型是 LangGraph Agent 的核心组件。
  • RAG:模型可以与检索器(retriever)结合使用,实现检索增强生成。在 Agent 中,模型可以利用检索工具获取外部知识。

初学者易错点

  1. 混淆 LLM 和 Chat Model:LLM 返回字符串,Chat Model 返回消息对象。确保使用正确的模型类型。
  2. 忽略流式处理限制:流式处理需要程序中的所有步骤都能处理分块数据,否则会导致错误。
  3. 过度依赖默认参数:不同模型对参数的敏感度不同,应根据任务调整 temperature、max_tokens 等参数。
  4. 忽略速率限制:频繁调用 API 可能触发速率限制,应实现适当的速率控制。
  5. 预绑定模型与结构化输出:使用 bind_tools 预绑定的模型不支持动态模型选择,如需结构化输出,确保中间件中的模型未预绑定。

相关词条

官方原文:https://docs.langchain.com/oss/python/langchain/models