Skip to content

Lesson 2 - Update langchain parser function with a real function #22

Closed
@aprilgittens

Description

@aprilgittens

In 02-explore-agentic-frameworks, the Use Modular Components section provides a code snippet which insists that Parser is a function within langchain. However, there is no Parser function within the langchain package.

I'd recommend using one of the other real functions available (ex: PydanticOutputParser). However, this would also require modifying the code snippet - it becomes quite lengthy but can be run if someone is using Azure OpenAI.

import os
from langchain.output_parsers import PydanticOutputParser
from langchain.prompts import PromptTemplate
from langchain_openai import AzureChatOpenAI
from pydantic import BaseModel, Field
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# Define a Pydantic model for structured data
class FlightBooking(BaseModel):
    origin: str = Field(description="Departure city")
    destination: str = Field(description="Arrival city")
    date: str = Field(description="Flight date")

# Initialize parser
parser = PydanticOutputParser(pydantic_object=FlightBooking)

# Define the prompt template
prompt = PromptTemplate(
    template="Extract structured flight details from the following text:\n{text}\n{format_instructions}",
    input_variables=["text"],
    partial_variables={"format_instructions": parser.get_format_instructions()},
)

# Initialize Azure OpenAI LLM
llm = AzureChatOpenAI(
    azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
    openai_api_version=os.getenv("AZURE_OPENAI_API_VERSION"),
    deployment_name=os.getenv("AZURE_OPENAI_DEPLOYMENT_NAME"),
    openai_api_key=os.getenv("AZURE_OPENAI_API_KEY"),
    temperature=0
)

# Chain together the prompt, model, and parser
chain = prompt | llm | parser

# Example input
user_input = "Book a flight from New York to London on July 15th"

# Invoke the chain
parsed_data = chain.invoke({"text": user_input})

print(parsed_data)
# Output: origin='New York' destination='London' date='July 15th'

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions