Learn / Frameworks / LangChain / Structured Output and Tool Calling

LangChain · Lesson 11 of 15

Structured Output and Tool Calling

Force JSON that matches a Pydantic model and bind tools the model can call.

  • Intermediate
  • 16 min read
  • 3 objectives

Before this lessonLesson 10: Streaming and Callbacks

What you will learn

  • with_structured_output
  • Bind a tool
  • Parse a tool call

Your Progress

0 of 15 lessons 0%

  • Lessons0 / 15
  • Completed0
  • Est. time left~ 4 hours

Create a free account to keep your progress on every device.

Free-form text is a bad API. Ask the model to fill a schema, or to call a tool whose arguments are that schema.

Pydantic first

from pydantic import BaseModel, Field

class Ticket(BaseModel):
    title: str = Field(description="Short summary")
    priority: str = Field(description="low, medium, or high")
    steps: list[str]

extractor = model.with_structured_output(Ticket)
ticket = extractor.invoke("The checkout 500s on Safari when the cart has a coupon.")
print(ticket.priority, ticket.steps)

Tools

from langchain_core.tools import tool

@tool
def get_weather(city: str) -> str:
    """Return a one-line forecast for a city."""
    return f"Sunny, 24C in {city}"

llm = model.bind_tools([get_weather])
msg = llm.invoke("Weather in Lisbon?")
print(msg.tool_calls)

If tool_calls is set, run the function, append a tool result message, and call the model again. That loop is an agent; bound it with a max-steps counter.

Up next · Lesson 12LangGraph BasicsState graphs, cycles, conditional edges and checkpointing a long-running agent.