Issue with PydanticOutputParser handling multiple content returns. #23590
Unanswered
1024689068
asked this question in
Q&A
Replies: 1 comment
-
To handle multi-line list returns with
Here is the code to accomplish this: from langchain_core.output_parsers import PydanticOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.pydantic_v1 import BaseModel, Field, validator
from langchain_openai import OpenAI
from langchain_community.llms import BaichuanLLM
import os
os.environ["BAICHUAN_API_KEY"] = " "
model = BaichuanLLM()
# Define your desired data structure for a single joke.
class Joke(BaseModel):
setup: str = Field(description="question to set up a joke")
punchline: str = Field(description="answer to resolve the joke")
@validator("setup")
def question_ends_with_question_mark(cls, field):
if field[-1] != "?":
raise ValueError("Badly formed question!")
return field
# Define your desired data structure for a list of jokes.
class JokesList(BaseModel):
jokes: list[Joke] = Field(description="list of jokes")
# Set up a parser for the list of jokes.
parser = PydanticOutputParser(pydantic_object=JokesList)
prompt = ChatPromptTemplate.from_messages(
[
("system", "Answer the user query. Wrap the output in `json` tags\n{format_instructions}"),
("human", "{query}"),
]
).partial(format_instructions=parser.get_format_instructions())
# And a query intended to prompt a language model to populate the data structure.
prompt_and_model = prompt | model
output = prompt_and_model.invoke({"query": "Tell me three jokes."})
parsed_output = parser.invoke(output)
print(parsed_output) This code sets up a |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Checked other resources
Commit to Help
Example Code
Description
"I used the code from https://python.langchain.com/v0.2/docs/how_to/output_parser_structured/, but I changed the query to 'tell me three jokes' and used Baichuan's Baichuan3-Turbo model. It returned [{'setup': 'Why don't scientists trust atoms?', 'punchline': 'Because they make up everything!'}, {'setup': 'What did the fish say when it hit the wall?', 'punchline': 'Dam!'}, {'setup': 'How many programmers does it take to change a light bulb?', 'punchline': 'None, they just define light bulb as being on.'}]. This caused PydanticOutputParser to fail to parse the format correctly, resulting in an error. Is there any way to handle this multi-line list return?"
System Info
Beta Was this translation helpful? Give feedback.
All reactions