Last active
September 28, 2023 14:50
-
-
Save gswithjeff/1cef448d9f72ba23f7ef534b659c8ea6 to your computer and use it in GitHub Desktop.
How to Use LangChain Output Parsers to Structure Large Language Models Responses
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from typing import List | |
| from dotenv import load_dotenv | |
| from langchain.llms import OpenAI | |
| from langchain.output_parsers import PydanticOutputParser | |
| from langchain.prompts import PromptTemplate | |
| from pydantic import BaseModel, Field | |
| load_dotenv() | |
| model_name = "text-davinci-003" | |
| temperature = 0.0 | |
| model = OpenAI(model_name=model_name, temperature=temperature) | |
| class Reservation(BaseModel): | |
| date: str = Field(description="reservation date") | |
| time: str = Field(description="reservation time") | |
| party_size: int = Field(description="number of people") | |
| cuisine: str = Field(description="preferred cuisine") | |
| parser = PydanticOutputParser(pydantic_object=Reservation) | |
| reservation_template = ''' | |
| Book us a nice table for two this Friday at 6:00 PM. | |
| Choose any cuisine, it doesn't matter. Send the confirmation by email. | |
| Our location is: {query} | |
| Format instructions: | |
| {format_instructions} | |
| ''' | |
| prompt = PromptTemplate( | |
| template=reservation_template, | |
| input_variables=["query"], | |
| partial_variables={"format_instructions": parser.get_format_instructions()}, | |
| ) | |
| _input = prompt.format_prompt(query="San Francisco, CA") | |
| output = model(_input.to_string()) | |
| reservation = parser.parse(output) | |
| print(_input.to_string()) | |
| for parameter in reservation.__fields__: | |
| print(f"{parameter}: {reservation.__dict__[parameter]}, {type(reservation.__dict__[parameter])}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment