Я использую 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
JsonOutputParser в LangChain вызывает исключение OutputParserException, когда модель включает диалоговый текст ⇐ Python
Программы на Python
1766235884
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}")
[b]Ошибка:[/b]
langchain_core.exceptions.OutputParserException: Invalid json output: Here is the data for France:
{
"name": "France",
"capital": "Paris",
...
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79851244/jsonoutputparser-in-langchain-raises-outputparserexception-when-model-includes-c[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия