Seamlessly integrate LLMs as Python functions
Seamlessly integrate Large Language Models into Python code. Use the @prompt and @chatprompt decorators to create functions that return structured output from an LLM. Combine LLM queries and tool use with traditional Python code to build complex agentic systems.
pip install magenticor using uv
uv add magenticConfigure your OpenAI API key by setting the OPENAI_API_KEY environment variable. To configure a different LLM provider see Configuration for more.
The @prompt decorator allows you to define a template for a Large Language Model (LLM) prompt as a Python function. When this function is called, the arguments are inserted into the template, then this prompt is sent to an LLM which generates the function output.
from magentic import prompt
@prompt('Add more "dude"ness to: {phrase}')
def dudeify(phrase: str) -> str: ... # No function body as this is never executed
dudeify("Hello, how are you?")
# "Hey, dude! What's up? How's it going, my man?"The @prompt decorator will respect the return type annotation of the decorated function. This can be any type supported by pydantic including a pydantic model.
from magentic import prompt
from pydantic import BaseModel
class Superhero(BaseModel):
name: str
age: int
power: str
enemies: list[str]
@prompt("Create a Superhero named {name}.")
def create_superhero(name: str) -> Superhero: ...
create_superhero("Garden Man")
# Superhero(name='Garden Man', age=30, power='Control over plants', enemies=['Pollution Man', 'Concrete Woman'])See Structured Outputs for more.
The @chatprompt decorator works just like @prompt but allows you to pass chat messages as a template rather than a single text prompt. This can be used to provide a system message or for few-shot prompting where you provide example responses to guide the model's output. Format fields denoted by curly braces {example} will be filled in all messages (except FunctionResultMessage).
…See Chat Prompting for more.
An LLM can also decide to call functions. In this case the @prompt-decorated function returns a FunctionCall object which can be called to execute the function using the arguments provided by the LLM.
…See Function Calling for more.
Sometimes the LLM requires making one or more function calls to generate a final answer. The @prompt_chain decorator will resolve FunctionCall objects automatically and pass the output back to the LLM to continue until the final answer is reached.
In the following example, when describe_weather is called the LLM first calls the get_current_weather function, then uses the result of this to formulate its final answer which gets returned.
from magentic import prompt_chain
def get_current_weather(location, unit="fahrenheit"):
"""Get the current weather in a given location"""
# Pretend to query an API
return {"temperature": "72", "forecast": ["sunny", "windy"]}
@prompt_chain(
"What's the weather like in {city}?",
functions=[get_current_weather],
)
def describe_weather(city: str) -> str: ...
describe_weather("Boston")
# 'The current weather in Boston is 72°F and it is sunny and windy.'LLM-powered functions created using @prompt, @chatprompt and @prompt_chain can be supplied as functions to other @prompt/@prompt_chain decorators, just like regular python functions. This enables increasingly complex LLM-powered functionality, while allowing individual components to be tested and improved in isolation.
The StreamedStr (and AsyncStreamedStr) class can be used to stream the output of the LLM. This allows you to process the text while it is being generated, rather than receiving the whole output at once.
from magentic import prompt, StreamedStr
@prompt("Tell me about {country}")
def describe_country(country: str) -> StreamedStr: ...
# Print the chunks while they are being received
for chunk in describe_country("Brazil"):
print(chunk, end="")
# 'Brazil, officially known as the Federative Republic of Brazil, is ...'Multiple StreamedStr can be created at the same time to stream LLM outputs concurrently. In the below example, generating the description for multiple countries takes approximately the same amount of time as for a single country.
…Structured outputs can also be streamed from the LLM by using the return type annotation Iterable (or AsyncIterable). This allows each item to be processed while the next one is being generated.
…See Streaming for more.
Asynchronous functions / coroutines can be used to concurrently query the LLM. This can greatly increase the overall speed of generation, and also allow other asynchronous code to run while waiting on LLM output. In the below example, the LLM generates a description for each US president while it is waiting on the next one in the list. Measuring the characters generated per second shows that this example achieves a 7x speedup over serial processing.
…See Asyncio for more.
functions argument to @prompt can contain async/coroutine functions. When the corresponding FunctionCall objects are called the result must be awaited.Annotated type annotation can be used to provide descriptions and other metadata for function parameters. See the pydantic documentation on using Field to describe function arguments.@prompt and @prompt_chain decorators also accept a model argument. You can pass an instance of OpenaiChatModel to use GPT4 or configure a different temperature. See below.@prompt functions by following the example notebook for a Pandas DataFrame.Magentic supports multiple LLM providers or "backends". This roughly refers to which Python package is used to interact with the LLM API. The following backends are supported.
The default backend, using the openai Python package and supports all features of magentic.
No additional installation is required. Just import the OpenaiChatModel class from magentic.
from magentic import OpenaiChatModel
model = OpenaiChatModel("gpt-4o")Ollama supports an OpenAI-compatible API, which allows you to use Ollama models via the OpenAI backend.
First, install ollama from ollama.com. Then, pull the model you want to use.
ollama pull llama3.2Then, specify the model name and base_url when creating the OpenaiChatModel instance.
from magentic import OpenaiChatModel
model = OpenaiChatModel("llama3.2", base_url="http://localhost:11434/v1/")When using the openai backend, setting the MAGENTIC_OPENAI_BASE_URL environment variable or using OpenaiChatModel(..., base_url="http://localhost:8080") in code allows you to use magentic with any OpenAI-compatible API e.g. Azure OpenAI Service, LiteLLM OpenAI Proxy Server, LocalAI. Note that if the API does not support tool calls then you will not be able to create prompt-functions that return Python objects, but other features of magentic will still work.
To use Azure with the openai backend you will need to set the MAGENTIC_OPENAI_API_TYPE environment variable to "azure" or use OpenaiChatModel(..., api_type="azure"), and also set the environment variables needed by the openai package to access Azure. See https://github.com/openai/openai-python#microsoft-azure-openai
This uses the anthropic Python package and supports all features of magentic.
Install the magentic package with the anthropic extra, or install the anthropic package directly.
pip install "magentic[anthropic]"Then import the AnthropicChatModel class.
from magentic.chat_model.anthropic_chat_model import AnthropicChatModel
model = AnthropicChatModel("claude-3-5-sonnet-latest")This uses the litellm Python package to enable querying LLMs from many different providers. Note: some models may not support all features of magentic e.g. function calling/structured output and streaming.
Install the magentic package with the litellm extra, or install the litellm package directly.
pip install "magentic[litellm]"Then import the LitellmChatModel class.
from magentic.chat_model.litellm_chat_model import LitellmChatModel
model = LitellmChatModel("gpt-4o")This uses the openai Python package with some small modifications to make the API queries compatible with the Mistral API. It supports all features of magentic. However tool calls (including structured outputs) are not streamed so are received all at once.
Note: a future version of magentic might switch to using the mistral Python package.
No additional installation is required. Just import the MistralChatModel class.
from magentic.chat_model.mistral_chat_model import MistralChatModel
model = MistralChatModel("mistral-large-latest")The default ChatModel used by magentic (in @prompt, @chatprompt, etc.) can be configured in several ways. When a prompt-function or chatprompt-function is called, the ChatModel to use follows this order of preference
ChatModel instance provided as the model argument to the magentic decoratorwith MyChatModel:ChatModel created from environment variables and the default settings in src/magentic/settings.pyThe following code snippet demonstrates this behavior:
from magentic import OpenaiChatModel, prompt
from magentic.chat_model.anthropic_chat_model import AnthropicChatModel
@prompt("SayNo open issues yet, or sync has not completed.