JsonOutputParser в LangChain вызывает исключение OutputParserException, когда модель включает диалоговый текстPython

Программы на Python
Ответить
Anonymous
 JsonOutputParser в LangChain вызывает исключение OutputParserException, когда модель включает диалоговый текст

Сообщение Anonymous »

Я использую LangChain для извлечения структурированных данных из пользовательского запроса с помощью gpt-3.5-turbo. Я определил объект Pydantic и передаю инструкции по форматированию в командную строку.
Однако иногда модель возвращает текст типа "Вот JSON, который вы запрашивали:" перед фактическим объектом JSON, что приводит к сбою JsonOutputParser.
from langchain_core.prompts import PromptTemplate
from langchain_core.output_parsers import JsonOutputParser
from langchain_openai import ChatOpenAI
from pydantic import BaseModel, Field

# 1. Define the desired data structure
class CountryInfo(BaseModel):
name: str = Field(description="Name of the country")
capital: str = Field(description="Capital city")
population: int = Field(description="Approximate population")

# 2. Setup model and parser
model = ChatOpenAI(model="gpt-3.5-turbo", temperature=0.7)
parser = JsonOutputParser(pydantic_object=CountryInfo)

# 3. Setup prompt
prompt = PromptTemplate(
template="Answer the user query.\n{format_instructions}\nQuery: {query}\n",
input_variables=["query"],
partial_variables={"format_instructions": parser.get_format_instructions()},
)

chain = prompt | model | parser

# 4. Execution
try:
# This sometimes fails if the model adds text before the JSON
response = chain.invoke({"query": "Tell me about France"})
print(response)
except Exception as e:
print(f"Error parsing: {e}")

Ошибка:
langchain_core.exceptions.OutputParserException: Invalid json output: Here is the data for France:
{
"name": "France",
"capital": "Paris",
...
}


Подробнее здесь: https://stackoverflow.com/questions/798 ... includes-c
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»