mirror of
https://github.com/hwchase17/langchain
synced 2024-10-29 17:07:25 +00:00
0d92a7f357
Probably the most boring PR to review ;) Individual commits might be easier to digest --------- Co-authored-by: Bagatur <baskaryan@gmail.com> Co-authored-by: Bagatur <22008038+baskaryan@users.noreply.github.com>
77 lines
1.8 KiB
Plaintext
77 lines
1.8 KiB
Plaintext
---
|
|
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
|
|
# And a query intended to prompt a language model to populate the data structure.
|
|
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>
|