2023-06-16 18:52:56 +00:00
|
|
|
---
|
|
|
|
sidebar_position: 2
|
|
|
|
---
|
|
|
|
Below we go over the main type of output parser, the `PydanticOutputParser`.
|
|
|
|
|
|
|
|
```python
|
|
|
|
from langchain.prompts import PromptTemplate, ChatPromptTemplate, HumanMessagePromptTemplate
|
|
|
|
from langchain.llms import OpenAI
|
|
|
|
from langchain.chat_models import ChatOpenAI
|
|
|
|
|
|
|
|
from langchain.output_parsers import PydanticOutputParser
|
|
|
|
from pydantic import BaseModel, Field, validator
|
|
|
|
from typing import List
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
```python
|
|
|
|
model_name = 'text-davinci-003'
|
|
|
|
temperature = 0.0
|
|
|
|
model = OpenAI(model_name=model_name, temperature=temperature)
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
```python
|
|
|
|
# Define your desired data structure.
|
|
|
|
class Joke(BaseModel):
|
|
|
|
setup: str = Field(description="question to set up a joke")
|
|
|
|
punchline: str = Field(description="answer to resolve the joke")
|
|
|
|
|
|
|
|
# You can add custom validation logic easily with Pydantic.
|
|
|
|
@validator('setup')
|
|
|
|
def question_ends_with_question_mark(cls, field):
|
|
|
|
if field[-1] != '?':
|
|
|
|
raise ValueError("Badly formed question!")
|
|
|
|
return field
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
```python
|
|
|
|
# Set up a parser + inject instructions into the prompt template.
|
|
|
|
parser = PydanticOutputParser(pydantic_object=Joke)
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
```python
|
|
|
|
prompt = PromptTemplate(
|
|
|
|
template="Answer the user query.\n{format_instructions}\n{query}\n",
|
|
|
|
input_variables=["query"],
|
|
|
|
partial_variables={"format_instructions": parser.get_format_instructions()}
|
|
|
|
)
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
```python
|
2023-07-12 20:20:08 +00:00
|
|
|
# And a query intended to prompt a language model to populate the data structure.
|
2023-06-16 18:52:56 +00:00
|
|
|
joke_query = "Tell me a joke."
|
|
|
|
_input = prompt.format_prompt(query=joke_query)
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
```python
|
|
|
|
output = model(_input.to_string())
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
```python
|
|
|
|
parser.parse(output)
|
|
|
|
```
|
|
|
|
|
|
|
|
<CodeOutputBlock lang="python">
|
|
|
|
|
|
|
|
```
|
|
|
|
Joke(setup='Why did the chicken cross the road?', punchline='To get to the other side!')
|
|
|
|
```
|
|
|
|
|
|
|
|
</CodeOutputBlock>
|