Structured Output

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Structured Output

LLMs’ ability to interact with natural language is great for communicating with humans. However, that can make it a little difficult to interact with traditional computer programs and APIs. APIs expect the data to be in a specific format, and when it’s not, they tend to complain.

from langchain_core.pydantic_v1 import BaseModel, Field

class Person(BaseModel):
  """Profile of a human."""

  name: str = Field(description="The person's name")
  age: int = Field(description="The person's age, between 1 and 100")
structured_llm = llm.with_structured_output(Person)
structured_llm.invoke("Create a random character for a story")
Person(name='Gandalf', age=100)
See forum comments
Download course materials from Github
Previous: Memory Demo Next: Structured Output Demo