使用gpt-35-turbo运行AgentExecutor触发InvalidRequestError错误求助
问题:使用gpt-35-turbo运行LangChain OpenAIFunctionsAgent时出现InvalidRequestError
运行从LangChain官方文档复制的OpenAIFunctionsAgent代码时,执行agent_executor.run()触发以下错误:
InvalidRequestError: Unrecognized request argument supplied: functions
相关代码
from langchain.agents import tool from langchain.agents import OpenAIFunctionsAgent from langchain.agents import AgentExecutor from langchain.chat_models import ChatOpenAI from langchain.schema import SystemMessage # Create LLM llm = ChatOpenAI( model_kwargs={"engine": deployment_name}, temperature=0.2) @tool def get_word_length(word: str) -> int: """Returns the length of a word.""" return len(word) tools = [get_word_length] # Prompt system_message = SystemMessage(content="You are very powerful assistant, but bad at calculating lengths of words.") prompt = OpenAIFunctionsAgent.create_prompt(system_message=system_message) # Create Agent agent = OpenAIFunctionsAgent(llm=llm, tools=tools, prompt=prompt) # Create Agent Executor agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True) # Run it agent_executor.run("how many letters in the word educa?")
错误栈信息
> Entering new AgentExecutor chain... ------ InvalidRequestError: Unrecognized request argument supplied: functions Traceback (most recent call last) Cell In[29], line 51 48 agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True) 50 # Run it ---> 51 agent_executor.run("how many letters in the word educa?")
错误原因
OpenAIFunctionsAgent依赖OpenAI的functions参数实现工具调用,但旧版本的gpt-35-turbo(如0301版本)不支持该参数,只有gpt-35-turbo-0613及以后的版本才支持工具调用功能。
修复方案
方案1:升级到支持工具调用的模型版本
修改ChatOpenAI的初始化代码,指定支持工具调用的模型版本:
llm = ChatOpenAI( model="gpt-35-turbo-0613", # 指定兼容工具调用的模型版本 model_kwargs={"engine": deployment_name}, temperature=0.2)
方案2:改用兼容旧模型的Agent类型
如果无法升级模型,可使用StructuredChatAgent替代OpenAIFunctionsAgent,示例代码如下:
from langchain.agents import tool from langchain.agents import AgentExecutor from langchain.chat_models import ChatOpenAI from langchain.schema import SystemMessage from langchain.agents import StructuredChatAgent from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder # Create LLM llm = ChatOpenAI( model_kwargs={"engine": deployment_name}, temperature=0.2) @tool def get_word_length(word: str) -> int: """Returns the length of a word.""" return len(word) tools = [get_word_length] # 构建适配StructuredChatAgent的Prompt system_message = SystemMessage(content="You are very powerful assistant, but bad at calculating lengths of words.") prompt = ChatPromptTemplate.from_messages([ system_message, MessagesPlaceholder(variable_name="chat_history"), ("user", "{input}"), MessagesPlaceholder(variable_name="agent_scratchpad") ]) # 创建Agent和Executor agent = StructuredChatAgent(llm=llm, tools=tools, prompt=prompt) agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True) # 运行 agent_executor.run("how many letters in the word educa?")
内容的提问来源于stack exchange,提问作者Andrii
相关产品推荐
相关产品推荐

