Last active
January 14, 2025 12:57
-
-
Save silgon/036b61e18fdf8f956661a13812fbf8c8 to your computer and use it in GitHub Desktop.
Example with JSONOutputParser, PydanticOutputParser, Pydantic and Optional Values
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 langchain_openai import ChatOpenAI | |
from langchain_core.output_parsers import JsonOutputParser | |
from langchain_core.output_parsers import PydanticOutputParser | |
from langchain_core.prompts import PromptTemplate | |
from pydantic import BaseModel, ValidationError | |
from typing import List, Optional | |
# Initialize the language model. Replace 'openai' with your specified model. | |
llm = ChatOpenAI(model="gpt-4o-mini",temperature=0) | |
class OutputItem(BaseModel): | |
title: str | |
description: str | |
tags: List[str] | |
author: Optional[str] = None # Optional field | |
published_date: Optional[str] = None # Optional fiel | |
class OutputArray(BaseModel): | |
elements: List[OutputItem] | |
json_output_parser = JsonOutputParser(pydantic_object=OutputArray) | |
pydantic_output_parser = PydanticOutputParser(pydantic_object=OutputArray) | |
# Define the prompt template | |
prompt_template = PromptTemplate( | |
input_variables=["keywords"], | |
template="Given the keywords: {keywords}, return a JSON array of 10 objects. The elements 'author' and 'published_date' are optional.\n{format_instructions}" | |
) | |
# Define the keywords you want to provide to the model | |
keywords = "AI, machine learning, LangChain" | |
# Generate the prompt | |
prompt = prompt_template.format(keywords=keywords,format_instructions=json_output_parser.get_format_instructions()) | |
# Get the response from the LLM | |
response = llm.invoke(prompt) | |
# Parse the response using JsonOutputParser | |
parsed_json = json_output_parser.parse(response.content) # Will throw an error if response is not valid JSON | |
output = pydantic_output_parser.parse(response.content) | |
# Output the parsed JSON | |
print(parsed_json) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment