如何解决Python中LangChain+AzureOpenAI的AttributeError与BadRequestError
问题解决:LangChain集成Azure OpenAI的版本适配错误
错误原因分析与解决
1. AttributeError: 'AzureOpenAI' object has no attribute 'chat'
langchain_openai.AzureOpenAI是对应OpenAI文本补全接口的类,仅支持补全类模型(如gpt-3.5-turbo-instruct、text-davinci-003),这类对象没有chat方法。如果要调用gpt-4这类聊天模型,必须使用专门的聊天模型类AzureChatOpenAI。
2. BadRequestError: OperationNotSupported
gpt-4属于聊天模型,只能通过聊天补全接口调用,无法使用文本补全接口。你之前用AzureOpenAI调用invoke,本质是触发了文本补全接口,因此Azure返回不支持的错误。
修正后的完整代码
from langchain_openai import AzureChatOpenAI # 创建聊天模型客户端 client = AzureChatOpenAI( openai_api_version=api_version, azure_deployment=deployment_name, azure_endpoint=azure_endpoint, api_key=api_key, # 直接传入密钥,无需放入model_kwargs temperature=TEMPERATURE, max_tokens=MAX_TOKENS, model=model ) # 场景1:简单单轮对话,用predict直接传字符串 response = client.predict("Hi") print(response) # 场景2:复杂多轮对话,用invoke传入标准聊天消息结构 from langchain_core.messages import HumanMessage, SystemMessage response = client.invoke([ SystemMessage(content="你是一个友好的助手"), HumanMessage(content="Hi") ]) print(response.content)
关键注意事项
- 确保Azure OpenAI部署中,
deployment_name对应的是gpt-4(或其他聊天模型)的部署实例,而非补全模型 - 新版本LangChain的
AzureChatOpenAI支持直接传入api_key参数,无需通过model_kwargs传递 - 聊天模型的
invoke方法返回AIMessage对象,需通过.content属性提取文本响应内容
内容的提问来源于stack exchange,提问作者DataJanitor
相关产品推荐
相关产品推荐

