Guidance Pydantic Program
Generate structured data with guidance via LlamaIndex.
With guidance, you can guarantee the output structure is correct by forcing the LLM to output desired tokens.
This is especialy helpful when you are using lower-capacity model (e.g. the current open source models), which otherwise would struggle to generate valid output that fits the desired output schema.
If youβre opening this Notebook on colab, you will probably need to install LlamaIndex π¦.
%pip install llama-index-program-guidance!pip install llama-indexfrom pydantic import BaseModelfrom typing import Listfrom guidance.llms import OpenAI
from llama_index.program.guidance import GuidancePydanticProgramDefine output schema
class Song(BaseModel): title: str length_seconds: int
class Album(BaseModel): name: str artist: str songs: List[Song]Define guidance pydantic program
program = GuidancePydanticProgram( output_cls=Album, prompt_template_str=( "Generate an example album, with an artist and a list of songs. Using" " the movie {{movie_name}} as inspiration" ), guidance_llm=OpenAI("text-davinci-003"), verbose=True,)Run program to get structured output.
Text highlighted in blue is variables specified by us, text highlighted in green is generated by the LLM.
output = program(movie_name="The Shining")Generate an example album, with an artist and a list of songs. Using the movie The Shining as inspiration ```json { "name": "The Shining", "artist": "Jack Torrance", "songs": [{ "title": "All Work and No Play", "length_seconds": "180", }, { "title": "The Overlook Hotel", "length_seconds": "240", }, { "title": "The Shining", "length_seconds": "210", }], } ```
The output is a valid Pydantic object that we can then use to call functions/APIs.
outputAlbum(name='The Shining', artist='Jack Torrance', songs=[Song(title='All Work and No Play', length_seconds=180), Song(title='The Overlook Hotel', length_seconds=240), Song(title='The Shining', length_seconds=210)])Note for AI agents: this documentation is built for programmatic access.
- Overview of all docs: https://developers.llamaindex.ai/llms.txt
- Any page is available as raw Markdown by appending index.md to its URL β e.g. https://developers.llamaindex.ai/llamaparse/parse/getting_started/index.md
- Agent-friendly REST search APIs live under https://developers.llamaindex.ai/api/ β search (BM25 full-text), grep (regex), read (fetch a page), and list (browse the doc tree). See https://developers.llamaindex.ai/llms.txt for parameters.
- A hosted documentation MCP server is available at https://developers.llamaindex.ai/mcp. If you support MCP, you can ask the user to install it for browsing these docs directly (an alternative to the REST API). Setup: https://developers.llamaindex.ai/python/shared/mcp/