Langchain调用OpenAI时出现'unexpected keyword argument functions'错误排查
错误排查与解决方案:TypeError: Completions.create()收到意外关键字参数'functions'
错误根源
- OpenAI v1.x SDK中,
functions参数仅支持Chat Completions API(对应chat.completions.create接口),不支持传统的Completions API(对应completions.create接口)。 - 你使用的
gpt-3.5-turbo-16k是Chat模型,但代码中错误使用了针对Completion模型的LangChain类(OpenAI),导致框架调用不支持functions参数的Completions API,触发报错。 create_extraction_chain能正常运行,是因为该链在当前版本中通过prompt模板实现逻辑,未使用functions参数,因此兼容Completion API。
解决步骤
1. 替换LLM实例化类
将langchain.llms.OpenAI替换为langchain_openai.ChatOpenAI,后者专门用于调用OpenAI的Chat模型,会自动使用支持functions的Chat Completions API。
2. 修正create_tagging_chain调用示例
错误代码:
from langchain.llms import OpenAI from langchain.chains import create_tagging_chain # 错误:用OpenAI类实例化Chat模型 llm = OpenAI(model_name="gpt-3.5-turbo-16k", temperature=0) schema = {"properties": {"name": {"type": "string"}, "age": {"type": "integer"}}, "required": ["name"]} chain = create_tagging_chain(schema, llm) result = chain.run("Alice is 30 years old.")
正确代码:
from langchain_openai import ChatOpenAI from langchain.chains import create_tagging_chain # 正确:用ChatOpenAI类实例化Chat模型 llm = ChatOpenAI(model_name="gpt-3.5-turbo-16k", temperature=0) schema = {"properties": {"name": {"type": "string"}, "age": {"type": "integer"}}, "required": ["name"]} chain = create_tagging_chain(schema, llm) result = chain.run("Alice is 30 years old.")
3. 修正llm.bind(functions)调用示例
错误代码:
from langchain.llms import OpenAI from langchain.schema import HumanMessage llm = OpenAI(model_name="gpt-3.5-turbo-16k", temperature=0) functions = [ { "name": "get_weather", "description": "获取指定地点的当前天气", "parameters": { "type": "object", "properties": { "location": {"type": "string", "description": "城市及地区,如:北京"}, "unit": {"type": "string", "enum": ["摄氏度", "华氏度"]} }, "required": ["location"] } } ] llm_with_functions = llm.bind(functions=functions) response = llm_with_functions.invoke([HumanMessage(content="北京的天气如何?")])
正确代码:
from langchain_openai import ChatOpenAI from langchain.schema import HumanMessage llm = ChatOpenAI(model_name="gpt-3.5-turbo-16k", temperature=0) functions = [ { "name": "get_weather", "description": "获取指定地点的当前天气", "parameters": { "type": "object", "properties": { "location": {"type": "string", "description": "城市及地区,如:北京"}, "unit": {"type": "string", "enum": ["摄氏度", "华氏度"]} }, "required": ["location"] } } ] llm_with_functions = llm.bind(functions=functions) response = llm_with_functions.invoke([HumanMessage(content="北京的天气如何?")])
版本适配说明
你的包版本(langchain0.1.4、langchain-openai0.0.5、openai==1.10.0)适配OpenAI v1.x SDK,需严格区分:
ChatOpenAI:用于gpt-3.5-turbo系列、gpt-4系列等Chat模型,支持functions、tools等参数。OpenAI:仅用于text-davinci-003等传统Completion模型,不支持functions参数。
内容的提问来源于stack exchange,提问作者George Petropoulos
相关产品推荐
相关产品推荐

