Error code: 400 'param': 'messages.[2].content', 'code': None
Confirm this is an issue with the Python library and not an underlying OpenAI API
- [X] This is an issue with the Python library
Describe the bug
Using the agent capability of Langchain, three tools have been added Sometimes there may be errors, sometimes it may be normal Error message:
File "/Users/gujiachun/anaconda3/envs/langchain-test/lib/python3.11/site-packages/openai/_base_client.py", line 1240, in post return cast(ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/gujiachun/anaconda3/envs/langchain-test/lib/python3.11/site-packages/openai/_base_client.py", line 921, in request return self._request( ^^^^^^^^^^^^^^ File "/Users/gujiachun/anaconda3/envs/langchain-test/lib/python3.11/site-packages/openai/_base_client.py", line 1020, in _request raise self._make_status_error_from_response(err.response) from None openai.BadRequestError: Error code: 400 - {'error': {'message': "Invalid value for 'content': expected a string, got null. (request id: 20240723090211496742562ZksEJFx0) (request id: 2024072301021136579144958040285)", 'type': 'invalid_request_error', 'param': 'messages.[2].content', 'code': None}}
To Reproduce
from datetime import date from operator import eq, itemgetter
import requests from langchain.chains.query_constructor.schema import AttributeInfo from langchain.retrievers import SelfQueryRetriever from langchain_community.agent_toolkits.load_tools import load_tools from langchain_community.utilities import SerpAPIWrapper from langchain_core.documents import Document from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate, PromptTemplate from langchain_core.runnables import RunnableParallel, RunnablePassthrough, RunnableLambda from langchain_core.structured_query import Comparison, Comparator from langchain_core.tools import tool from langchain_huggingface import HuggingFaceEmbeddings from langchain_community.vectorstores import Milvus from langchain_openai import ChatOpenAI from langchain_core.runnables import chain
from langchain import hub from langchain.agents import create_openai_functions_agent
from langchain.agents import AgentExecutor
serpapi_api_key = "54d5973f9487d329ffdf22c773bb2514a94f37242d8d1311a4817e96a7386c14"
api_key = "sk-jFFKnyLzOGW4njGc9b68Fb5e1dB04c198aCfCcC3C894Fa0a" api_url = "https://ai-yyds.com/v1"
llm = ChatOpenAI(base_url=api_url, api_key=api_key, model_name="gpt-4")
一个最简单的模版,带记忆
prompt = hub.pull("hwchase17/openai-functions-agent") print(prompt.messages)
@tool def search(text: str): """This tool is only used when real-time information needs to be searched. The search returns only the first 3 items""" serp = SerpAPIWrapper(serpapi_api_key=serpapi_api_key)
response = serp.run(text)
print(type(response))
content = ""
if type(response) is list:
for item in response:
content += str(item["title"]) + "\n"
else:
content = response
return content
@tool def time() -> str: """Return today's date and use it for any questions related to today's date. The input should always be an empty string, and this function will always return today's date. Any mathematical operation on a date should occur outside of this function""" return str(date.today())
@tool def weather(city: str): """When you need to check the weather, you can use this tool, which returns the weather conditions for the day, tomorrow, and the day after tomorrow""" url = "https://api.seniverse.com/v3/weather/daily.json?key=SrlXSW6OX9PssfOJ1&location=beijing&language=zh-Hans&unit=c&start=0"
response = requests.get(url)
data = response.json()
if not data or len(data['results']) == 0:
return None
daily = data['results'][0]["daily"]
content = ""
res = []
for day in daily:
info = {"city": city, "date": day["date"], "info": day["text_day"], "temperature_high": day["high"],
"temperature_low": day["low"]}
content += f"{city} date:{day['date']} info:{day['text_day']} maximum temperature:{day['high']} minimum temperature:{day['low']}\n"
res.append(info)
return content
tools = [time, weather, search]
agent = create_openai_functions_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
chain1 = agent_executor | StrOutputParser()
for chunk in agent_executor.stream({"input": "What's the weather like in Shanghai today"}): if "output" in chunk: print(f'{chunk["output"]}')
Code snippets
from datetime import date
from operator import eq, itemgetter
import requests
from langchain.chains.query_constructor.schema import AttributeInfo
from langchain.retrievers import SelfQueryRetriever
from langchain_community.agent_toolkits.load_tools import load_tools
from langchain_community.utilities import SerpAPIWrapper
from langchain_core.documents import Document
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate, PromptTemplate
from langchain_core.runnables import RunnableParallel, RunnablePassthrough, RunnableLambda
from langchain_core.structured_query import Comparison, Comparator
from langchain_core.tools import tool
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_community.vectorstores import Milvus
from langchain_openai import ChatOpenAI
from langchain_core.runnables import chain
from langchain import hub
from langchain.agents import create_openai_functions_agent
from langchain.agents import AgentExecutor
serpapi_api_key = "54d5973f9487d329ffdf22c773bb2514a94f37242d8d1311a4817e96a7386c14"
api_key = "sk-jFFKnyLzOGW4njGc9b68Fb5e1dB04c198aCfCcC3C894Fa0a"
api_url = "https://ai-yyds.com/v1"
llm = ChatOpenAI(base_url=api_url, api_key=api_key, model_name="gpt-4")
# 一个最简单的模版,带记忆
prompt = hub.pull("hwchase17/openai-functions-agent")
print(prompt.messages)
@tool
def search(text: str):
"""This tool is only used when real-time information needs to be searched. The search returns only the first 3 items"""
serp = SerpAPIWrapper(serpapi_api_key=serpapi_api_key)
response = serp.run(text)
print(type(response))
content = ""
if type(response) is list:
for item in response:
content += str(item["title"]) + "\n"
else:
content = response
return content
@tool
def time() -> str:
"""Return today's date and use it for any questions related to today's date.
The input should always be an empty string, and this function will always return today's date. Any mathematical operation on a date should occur outside of this function"""
return str(date.today())
@tool
def weather(city: str):
"""When you need to check the weather, you can use this tool, which returns the weather conditions for the day, tomorrow, and the day after tomorrow"""
url = "https://api.seniverse.com/v3/weather/daily.json?key=SrlXSW6OX9PssfOJ1&location=beijing&language=zh-Hans&unit=c&start=0"
response = requests.get(url)
data = response.json()
if not data or len(data['results']) == 0:
return None
daily = data['results'][0]["daily"]
content = ""
res = []
for day in daily:
info = {"city": city, "date": day["date"], "info": day["text_day"], "temperature_high": day["high"],
"temperature_low": day["low"]}
content += f"{city} date:{day['date']} info:{day['text_day']} maximum temperature:{day['high']} minimum temperature:{day['low']}\n"
res.append(info)
return content
tools = [time, weather, search]
agent = create_openai_functions_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
chain1 = agent_executor | StrOutputParser()
for chunk in agent_executor.stream({"input": "What's the weather like in Shanghai today"}):
if "output" in chunk:
print(f'{chunk["output"]}')
OS
macos
Python version
Python 3.8.19
Library version
openai 1.37