跳到主要内容

LLM 调用

本章将详细介绍如何在 LangChain 中调用各种大语言模型(LLM),包括 OpenAI、Anthropic、Google 等主流模型。

初始化模型

LangChain 提供了标准化的接口来初始化各种模型。

使用 init_chat_model(新 API)

LangChain v1 推荐使用 init_chat_model 来初始化聊天模型:

from langchain.chat_models import init_chat_model

# 使用 OpenAI
model = init_chat_model(
model="gpt-4o-mini", # 模型名称
model_provider="openai" # 模型提供商
)

# 使用 Anthropic
model = init_chat_model(
model="claude-3-5-sonnet-20240620",
model_provider="anthropic"
)

# 使用 Google
model = init_chat_model(
model="gemini-1.5-pro",
model_provider="google_genai"
)

参数说明

  • model:模型名称
  • model_provider:模型提供商标识
  • temperature:生成随机性(0-2),默认 0.7
  • max_tokens:最大生成 token 数
  • streaming:是否启用流式输出

旧版 API(仍可用)

在旧版 LangChain 中使用不同的初始化方式:

# OpenAI
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model="gpt-4o-mini")

# Anthropic
from langchain_anthropic import ChatAnthropic
llm = ChatAnthropic(model="claude-3-5-sonnet-20240620")

调用模型

基本调用

from langchain.chat_models import init_chat_model
from langchain.schema import HumanMessage

# 初始化模型
model = init_chat_model(
model="gpt-4o-mini",
model_provider="openai"
)

# 调用模型
response = model.invoke("你好,请介绍一下你自己")
print(response.content)

使用消息对象

from langchain.chat_models import init_chat_model
from langchain.schema import HumanMessage, SystemMessage

model = init_chat_model(
model="gpt-4o-mini",
model_provider="openai"
)

# 构建消息列表
messages = [
SystemMessage(content="你是一个专业的Python编程助手"),
HumanMessage(content="请解释什么是装饰器")
]

response = model.invoke(messages)
print(response.content)

使用消息元组(新 API)

LangChain v1 支持更简洁的消息格式:

# 格式: ("角色", "内容")
messages = [
("system", "你是一个友好的AI助手"),
("user", "你好"),
]

response = model.invoke(messages)

流式输出

启用流式输出

from langchain.chat_models import init_chat_model

model = init_chat_model(
model="gpt-4o-mini",
model_provider="openai",
streaming=True # 启用流式输出
)

# 流式输出
for chunk in model.stream("请给我讲一个笑话"):
print(chunk.content, end="", flush=True)

流式输出的优势

流式输出让你能够:

  • 更快看到响应:无需等待完整响应生成
  • 更好的用户体验:类似打字机的效果
  • 节省时间:对于长文本尤为重要

模型参数

常用参数

model = init_chat_model(
model="gpt-4o-mini",
model_provider="openai",

# 生成控制
temperature=0.7, # 控制随机性 (0-2)
max_tokens=1000, # 最大生成 token 数
top_p=0.9, # 核采样参数
frequency_penalty=0.0, # 频率惩罚
presence_penalty=0.0, # 存在惩罚

# 流式输出
streaming=True,

# 其他
timeout=60, # 超时时间(秒)
)

参数解释

参数说明建议值
temperature控制输出的随机性0.7(通用)、0.2(精确)、1.0(创意)
max_tokens限制输出长度根据任务需要设置
top_p核采样,累积概率阈值0.9(默认)
frequency_penalty减少重复词汇0-2
presence_penalty鼓励引入新话题0-2

多模态模型

处理图片输入

from langchain.chat_models import init_chat_model
from langchain.schema import HumanMessage
from langchain.core.messages import HumanMessage

# 初始化支持视觉的模型
model = init_chat_model(
model="gpt-4o",
model_provider="openai"
)

# 创建带图片的消息
messages = [
HumanMessage(
content=[
{"type": "text", "text": "描述这张图片"},
{"type": "image_url", "image_url": {"url": "https://example.com/image.jpg"}}
]
)
]

response = model.invoke(messages)
print(response.content)

本地图片

import base64

# 读取本地图片并转为 base64
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode('utf-8')

# 使用本地图片
image_base64 = encode_image("local_image.jpg")
messages = [
HumanMessage(
content=[
{"type": "text", "text": "描述这张图片"},
{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{image_base64}"}}
]
)
]

异步调用

异步 API

import asyncio
from langchain.chat_models import init_chat_model

async def call_model():
model = init_chat_model(
model="gpt-4o-mini",
model_provider="openai"
)

response = await model.ainvoke("异步调用测试")
return response.content

# 运行异步函数
result = asyncio.run(call_model())
print(result)

并发调用

import asyncio
from langchain.chat_models import init_chat_model
from langchain.schema import HumanMessage

async def concurrent_calls():
model = init_chat_model(
model="gpt-4o-mini",
model_provider="openai"
)

questions = [
"什么是Python?",
"什么是Java?",
"什么是Go?"
]

# 并发调用
tasks = [model.ainvoke([HumanMessage(content=q)]) for q in questions]
responses = await asyncio.gather(*tasks)

return [r.content for r in responses]

results = asyncio.run(concurrent_calls())
for r in results:
print(r)

模型比较

切换模型

LangChain 的优势之一是可以轻松切换模型:

from langchain.chat_models import init_chat_model

# 定义一个获取模型的函数
def get_model(provider="openai", model_name="gpt-4o-mini"):
return init_chat_model(
model=model_name,
model_provider=provider
)

# 切换模型只需更改参数
model = get_model(provider="openai", model_name="gpt-4o")
model = get_model(provider="anthropic", model_name="claude-3-5-sonnet")

支持的模型

提供商模型说明
OpenAIgpt-4o, gpt-4o-mini, gpt-4-turbo通用能力强
Anthropicclaude-3-5-sonnet, claude-3-haiku性价比高
Googlegemini-1.5-pro, gemini-1.5-flash上下文长
AWSbedrock models企业级
Ollamallama, mistral本地部署

错误处理

常见错误

from langchain.chat_models import init_chat_model
from langchain_core.messages import HumanMessage

model = init_chat_model(
model="gpt-4o-mini",
model_provider="openai"
)

try:
response = model.invoke([HumanMessage(content="test")])
print(response.content)
except Exception as e:
print(f"错误类型: {type(e).__name__}")
print(f"错误信息: {e}")

重试机制

from langchain.chat_models import init_chat_model
from langchain_core.messages import HumanMessage
from tenacity import retry, stop_after_attempt, wait_exponential

model = init_chat_model(
model="gpt-4o-mini",
model_provider="openai"
)

@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=1, max=10))
def call_with_retry():
return model.invoke([HumanMessage(content="test")])

response = call_with_retry()

完整示例

简单聊天应用

from langchain.chat_models import init_chat_model
from langchain.schema import HumanMessage, AIMessage

# 初始化模型
model = init_chat_model(
model="gpt-4o-mini",
model_provider="openai"
)

# 对话历史
chat_history = [
SystemMessage(content="你是一个有帮助的AI助手")
]

print("开始对话(输入 'quit' 退出)\n")

while True:
user_input = input("你: ")
if user_input.lower() == 'quit':
break

# 添加用户消息
chat_history.append(HumanMessage(content=user_input))

# 获取响应
response = model.invoke(chat_history)

# 添加AI响应
chat_history.append(response)

print(f"AI: {response.content}\n")

流式聊天

from langchain.chat_models import init_chat_model

model = init_chat_model(
model="gpt-4o-mini",
model_provider="openai",
streaming=True
)

print("AI: ", end="")
for chunk in model.stream("给我讲一个关于程序员笑话"):
print(chunk.content, end="", flush=True)
print()

下一步

现在你已经学会了如何调用 LLM,接下来学习: