Magentic
Decorator-based library for seamlessly integrating LLMs as Python functions. Uses @prompt, @chatprompt, and @prompt_chain decorators to turn Python function signatures into LLM calls with typed structured output. Built on pydantic for output validation. Current version: 0.41.1 (Mar 2026). Still pre-1.0 — API may change. Default backend: OpenAI.
Warnings
- gotcha The function body of @prompt decorated functions is NEVER executed. Must use ... (ellipsis) as the body. Any actual code in the body is dead code that will never run.
- gotcha When functions= is passed to @prompt, the LLM may return a FunctionCall object instead of the final result. Must call fn_call() to execute it. Use @prompt_chain to auto-resolve.
- gotcha Default model is gpt-4o-mini (OpenAI). Requires OPENAI_API_KEY. Fails silently if not set — raises AuthenticationError at call time, not at decoration time.
- gotcha Still pre-1.0 (0.41.x). API stability not guaranteed. Minor versions may introduce breaking changes.
- gotcha Anthropic and LiteLLM backends require separate extras. 'pip install magentic' alone only includes OpenAI backend.
Install
-
pip install magentic -
pip install 'magentic[anthropic]' -
pip install 'magentic[litellm]'
Imports
- prompt
from magentic import prompt from pydantic import BaseModel class Superhero(BaseModel): name: str power: str @prompt('Create a superhero named {name}.') def create_superhero(name: str) -> Superhero: ... # body is never executed — must be ellipsis hero = create_superhero('Garden Man') print(hero.name, hero.power) - FunctionCall
from magentic import prompt, FunctionCall def get_weather(city: str) -> str: return f'Sunny in {city}' @prompt( 'What is the weather in {city}?', functions=[get_weather] ) def describe_weather(city: str) -> FunctionCall[str]: ... # Returns a FunctionCall object — must be called to execute fn_call = describe_weather('Boston') result = fn_call() # actually calls get_weather print(result) - chatprompt
from magentic import chatprompt, SystemMessage, UserMessage @chatprompt( SystemMessage('You are a helpful assistant.'), UserMessage('{question}'), ) def answer(question: str) -> str: ... print(answer('What is Python?'))
Quickstart
# pip install magentic
from magentic import prompt
from pydantic import BaseModel
class Superhero(BaseModel):
name: str
power: str
enemies: list[str]
@prompt('Create a superhero named {name}.')
def create_superhero(name: str) -> Superhero:
... # never executed
hero = create_superhero('Garden Man')
print(hero.name) # 'Garden Man'
print(hero.power) # 'Control over plants'
print(hero.enemies) # ['Pollution Man', ...]