Skip to content

Documentation navigation

Getting Started

Install the SDK and run your first agent invocation.

#Quickstart

Build an agent that calls a typed Python tool and returns a Pydantic answer model. You supply the tools and the answer fields; your code reads response.result. The complete application below uses a local weather fixture so you can see where its facts come from.

#Install and configure

The SDK requires Python 3.10 or newer. The runnable examples project and optional maivn-tools integrations require Python 3.12 or newer.

Create a project folder and install in a virtual environment:

The SDK includes encrypted local storage for caller-declared private values. On supported desktops it uses the OS credential store when those values are first needed. Servers need durable storage and a secret-manager key. See Values that outlive one call before using private values in a server or container.
Shell
mkdir weather-app
cd weather-app
python -m venv .venv
source .venv/bin/activate
python -m pip install maivn

On Windows PowerShell, activate with .venv\Scripts\Activate.ps1. In an existing uv project, use uv add maivn, then run Python commands with uv run.

Create a runtime API key in your developer portal, then export it in the shell where you will run the application:

Shell
export MAIVN_API_KEY=your-runtime-key

PowerShell uses:

Powershell
$env:MAIVN_API_KEY = 'your-runtime-key'

Agent accepts an explicit key, a configured client, or MAIVN_API_KEY from the process environment. It loads a dotenv file only when you select one with env_file=.... This application reads the exported key with os.environ['MAIVN_API_KEY']. A missing value fails before invocation. Catalog examples supply their own execution-time .env loading, described in the examples tour.

#Choosing which mAIvn endpoint to call

With no URL configuration, the SDK uses https://api.maivn.io. There is one address knob: MAIVN_BASE_URL (or base_url= on Agent/Client). For a local v2 stack, point it at that stack's single address.

Confirm that your account has access to the selected endpoint.

Shell
export MAIVN_BASE_URL=http://127.0.0.1:8000

For another deployment, set the same variable to its address. An explicit base_url= on Agent or Client wins over the environment variable, which wins over the default.

#Your first application

Save this complete example as weather_app.py in your project folder:

Python
import os

from maivn import Agent
from pydantic import BaseModel, Field

# 1. Write a typed tool with a clear description.
def get_weather(city: str) -> dict[str, str | int]:
    """Return the weather fixture for Austin, in degrees Fahrenheit."""
    if city.casefold() != 'austin':
        return {'error': 'The fixture contains only Austin.'}
    return {'city': 'Austin', 'temperature': 72, 'condition': 'sunny'}

# 2. Define the answer fields your application needs.
class WeatherReport(BaseModel):
    city: str = Field(description='City returned by the weather tool.')
    temperature: int = Field(description='Temperature in degrees Fahrenheit.')
    summary: str = Field(description='A short summary of the tool result.')

# 3. Give the agent a plain tools list.
agent = Agent(
    name='Weather Assistant',
    api_key=os.environ['MAIVN_API_KEY'],
    system_prompt='Call get_weather for the requested city. Answer from its result.',
    tools=[get_weather],
)

# 4. Invoke with the answer model.
response = agent.invoke(
    'What is the weather in Austin?',
    structured_output=WeatherReport,
)

# 5. Read the typed result.
report = response.result
print(report.city, report.temperature, report.summary)

Run it from the folder containing that file, in the configured environment:

Shell
python weather_app.py

The expected result names Austin, reports 72, and describes sunny conditions. The tool is a synthetic fixture; the model invocation uses the selected mAIvn endpoint. Your tool code runs locally. The runtime receives its schema and uses the tool result to produce the answer.

structured_output=WeatherReport requests a typed answer for this call. You can also write agent.structured_output(WeatherReport).invoke(...). Both place the validated model on response.result. Invalid returned fields raise ValueError with the underlying Pydantic validation error as its cause. Connection and model failures still need handling. Validation of the shape does not establish that the facts are correct.

For an ordinary text answer, omit structured_output and read response.response. The Structured Output Guide covers the typed routes and selective bypass of unnecessary orchestration and presentation work.

#Make it yours

  1. Replace get_weather's fixture with your weather source. Keep typed arguments, a clear description, and explicit handling for unavailable cities.
  2. Add a field such as condition to WeatherReport, update the prompt, and check it against the source result. Review any external requests or writes you add.
  3. Use the existing examples catalog for parcel tracking, toolset permissions, approved actions, and specialist-agent handoffs. The runnable demos include factual checks and expected results.

#Add named tools and Studio metadata

Bound decorators and add_tool remain useful when you need explicit registration options. For example, to give the final answer a stable tool name:

Python
agent.add_tool(WeatherReport, name='weather_report', final_tool=True)
response = agent.invoke('Weather report for Austin', force_final_tool=True)

The parcel quickstart in the runnable catalog uses the explicit name status_card. Its Studio prompt selects that name and its invocation forces the final tool. Keep those names together when customizing it. A plain standalone tools-list application does not need Studio metadata.

To install Studio in this application's environment and launch from its configured project folder:

Shell
python -m pip install maivn-studio
python -m maivn_studio.main

With uv, add the companion to the project and launch in that environment:

Shell
uv add maivn-studio
uv run python -m maivn_studio.main

The runnable examples project declares a Studio extra; use uv run --extra studio python -m maivn_studio.main there so synchronization keeps it installed. See the Studio guide for discovery and configuration.

#Show live progress

Enable verbose=True on an invocation to display terminal progress. Plain text works without an extra dependency. Install maivn[rich] for Rich rendering in capable terminals. NO_COLOR, CI, TERM=dumb, non-TTY stdout, or missing Rich select plain text. MAIVN_TERMINAL_TIER=plain forces plain text, and rich requests Rich rendering with safe fallback.

For a UI, use an event callback or consume the stream:

Python
def handle(event: dict) -> None:
    print(event)

response = agent.events(on_event=handle).invoke('What is the weather in Austin?')

for event in agent.stream('What is the weather in Austin?'):
    print(event)

See Frontend Events for browser integration and System Tools for runtime datetime awareness, web search, and hosted code execution.

#Troubleshooting and next steps

If construction reports "Agent requires either a Client instance or an api_key", pass api_key=os.environ['MAIVN_API_KEY'] or supply a client built with the public ClientBuilder.from_environment(). When several agents have identical connection settings, you can pass the same configured client to each while keeping their tools and permissions separate.

If a tool is not called, check its description and the request. If a connection fails, check the selected endpoint and runtime key. See Troubleshooting for more detail.

Continue with Core Concepts, Tools, Structured Output, and Multi-Agent.