from langchain_core.pydantic_v1 import BaseModel, Field from langchain_openai import ChatOpenAI from langchain_core.prompts import ChatPromptTemplate # Define our WeatherForecast model class WeatherForecast(BaseModel): temperature: float = Field(description="The temperature in Celsius") condition: str = Field(description="The weather condition (e.g., sunny, rainy, cloudy)") humidity: int = Field(description="The humidity percentage") wind_speed: float = Field(description="The wind speed in km/h") # Set up the LLM model = ChatOpenAI(model="gpt-4", temperature=0) # Create the prompt template prompt = ChatPromptTemplate.from_template( "Given the context below, provide a weather forecast for {city} tomorrow, respond in JSON with `temperature`, `condition`, `humidity`, and `wind_speed` keys\n\n{context}" ) # Apply structured output to the LLM structured_llm = model.with_structured_output(WeatherForecast, method="json_mode") # Chain the prompt and structured LLM weather_chain = prompt | structured_llm # Generate a weather forecast result = weather_chain.invoke({"city": "New York", "context": "The weather in New York will be sunny with a chance of rain."}) print(result) # Output: WeatherForecast(temperature=22.5, condition='Partly cloudy', humidity=65, wind_speed=10.2) __ __