ChatOpenAI
常用方法详解
ChatOpenAI
是 LangChain 中用于与 OpenAI 聊天模型交互的核心类,提供了多种方法来调用和管理对话。以下是其主要方法的详细介绍:
核心方法
1. invoke()
- 同步调用模型
最常用的方法,用于同步调用模型并获取完整响应。
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage
chat = ChatOpenAI(model="qwen-max", temperature=0.7)
# 方式一:单条消息调用
response = chat.invoke("你好!")
print(response.content) # 输出: 你好!有什么可以帮您的吗?
# 方式二:多条消息列表调用
messages = [
HumanMessage(content="你好!"),
HumanMessage(content="请介绍下你自己")
]
response = chat.invoke(messages)
print(response.content)
2. stream()
- 流式响应
用于获取流式响应,适合需要逐步显示结果的场景。
# 流式处理响应
for chunk in chat.stream("请写一首关于春天的诗"):
print(chunk.content, end="", flush=True)
3. generate()
- 批量生成
同时处理多个用户输入(question),返回包含元数据的完整响应对象。
# 批量处理多个用户输入
messages_list = [
[HumanMessage(content="2+2等于多少?")],
[HumanMessage(content="中国的首都是哪里?")]
]
result = chat.generate(messages_list)
for gen in result.generations:
print(gen[0].text)
# 输出:
# 2+2等于4。
# 中国的首都是北京。
4. bind_tools()
- 绑定工具调用
将函数调用能力绑定到当前模型。
from langchain_core.tools import tool
@tool
def get_current_weather(location: str):
"""获取指定位置的当前天气"""
return f"{location}的天气是晴朗的,25℃"
# 绑定工具,生成新的聊天模型
chat_with_tools = chat.bind_tools([get_current_weather])
# 使用工具调用
response = chat_with_tools.invoke("旧金山现在的天气如何?")
# 返回:旧金山的天气是晴朗的,25℃
print(response.additional_kwargs) # 打印包含工具调用信息
高级方法
5. with_structured_output()
- 结构化输出
强制模型返回结构化数据。
from langchain_core.pydantic_v1 import BaseModel, Field
class Person(BaseModel):
name: str = Field(description="姓名")
age: int = Field(description="年龄")
hobbies: list[str] = Field(description="爱好列表")
# 给当前模型设置为结构化输出
structured_chat = chat.with_structured_output(Person)
response = structured_chat.invoke("小明23岁,喜欢读书和游泳")
print(response)
# 输出: name='小明' age=23 hobbies=['读书', '游泳']
6. with_fallbacks()
- 失败回退
设置模型调用失败时的备用模型。
from langchain_openai import ChatOpenAI
# 主模型 + 备用模型
reliable_chat = ChatOpenAI(model="gpt-4").with_fallbacks([
ChatOpenAI(model="gpt-3.5-turbo"),
ChatOpenAI(model="gpt-3.5-turbo-16k")
])
# 当gpt-4不可用时自动回退
response = reliable_chat.invoke("请解释量子力学的基本原理")
7. predict_messages()
- 预测消息
与invoke
类似,但返回完整的消息对象。
response = chat.predict_messages([HumanMessage(content="Python的优点是什么?")])
print(response)
# 输出: AIMessage(content='Python具有简单易学...', additional_kwargs={...})
配置相关方法
8. 模型参数设置
在初始化时配置模型参数:
chat = ChatOpenAI(
model="gpt-4-turbo",
temperature=0.5, # 控制随机性 (0-2)
max_tokens=500, # 最大输出token数
frequency_penalty=0.2, # 减少重复内容 (-2.0到2.0)
presence_penalty=0.1, # 增加新话题可能性 (-2.0到2.0)
timeout=30, # 超时时间(秒)
streaming=True # 是否使用流式响应
)
9. 异步方法
所有ChatOpenAI
的核心方法都有对应的异步版本:
# 异步调用
async def main():
response = await chat.ainvoke("异步调用的优势是什么?")
print(response.content)
# 异步流式处理
async def stream_response():
async for chunk in chat.astream("请逐步解释机器学习"):
print(chunk.content, end="", flush=True)
实用技巧
消息历史管理
from langchain.memory import ConversationBufferMemory
memory = ConversationBufferMemory()
memory.save_context({"input": "你好"}, {"output": "你好!有什么可以帮您?"})
# 添加新消息
memory.chat_memory.add_user_message("我想了解AI")
memory.chat_memory.add_ai_message("人工智能是...")
# 获取完整历史
history = memory.load_memory_variables({})
messages = history["history"].messages
# 使用历史进行对话
response = chat.invoke(messages)
自定义停止词
chat = ChatOpenAI(
model="gpt-3.5-turbo",
stop=["\n", "。"] # 当遇到换行或句号时停止生成
)
完整工作流示例
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage, SystemMessage
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
# 创建聊天模型
chat = ChatOpenAI(model="gpt-4", temperature=0.7)
# 创建提示模板
prompt = ChatPromptTemplate.from_messages([
SystemMessage(content="你是一个专业的IT顾问"),
("human", "{input}")
])
# 创建处理链
chain = prompt | chat | StrOutputParser()
# 执行链式调用
response = chain.invoke({"input": "如何保护公司数据安全?"})
print(response)
最佳实践
温度设置:
- 创意任务:0.7-1.0
- 事实性回答:0.1-0.3
- 平衡:0.5
错误处理:
from openai import APIError try: response = chat.invoke("问题内容") except APIError as e: print(f"API错误: {e}")
内容过滤:
chat = ChatOpenAI( model="gpt-3.5-turbo", model_kwargs={"response_format": {"type": "text"}} # 仅返回文本 )
性能优化:
# 批量处理提高效率 responses = chat.batch([ "问题1", "问题2", "问题3" ])
ChatOpenAI
提供了丰富的功能和灵活的配置选项,可以满足从简单问答到复杂对话系统的各种需求。根据具体场景选择合适的方法和参数配置,可以显著提升应用性能和用户体验。