Framework guide · rapid-mlx 1.1.1 · ← Back to README

PydanticAI

PydanticAI is the Pydantic-native agent framework. Connect it to Rapid-MLX for a local tool conversation with retained history using the version-pinned example below.

Choose a model for your Mac

Rapid-MLX provides a local OpenAI-compatible Chat Completions endpoint on Apple Silicon. Choose a model by unified memory and the memory left after other applications have loaded:

Mac unified memoryModel choicesDownload and memory guidance
18–36 GBqwen3.5-9b-4bit default; start with qwen3.5-4b-4bit on 18–24 GB.About 6 GB for 9B or 3 GB for 4B. Only 32 GB was verified in this tier; 18–24 GB remains unverified.
48+ GBqwen3.5-9b-4bit responsive default; qwen3.8-27b-4bit higher-capability option.About 6 GB for 9B or 16 GB for 27B. The 27B option was verified on 48 GB and needs roughly 20–26 GB free unified memory; long-context cold prefill is slow.

Download size is not runtime memory use. Leave room for the Python client, context and other applications.

The listed aliases were verified with PydanticAI tool-call loops, Rapid-MLX 1.1.0, PydanticAI 2.71.0. These small fixtures do not establish success on every tool workflow. The PydanticAI example below preserves the tested 2.71.0 provider, tools, prompts and history handling.

Install, serve and check readiness

Leave the server running in one terminal:

$ curl -fsSL https://rapidmlx.com/install.sh | bash
$ rapid-mlx serve qwen3.5-9b-4bit --port 8000

The installer must run under bash. Restart the terminal if the installed command is not on your PATH. The first launch downloads the selected model if it is not cached.

In another terminal:

$ curl http://127.0.0.1:8000/v1/models

Alternatively, use rapid-mlx ps. Check that the returned model ID matches the Python model name.

Three turns with tools and conversation history

In your Python environment, install the client versions used for this example:

$ python3 -m pip install 'pydantic-ai==2.71.0' 'openai==3.57.0'

Save this as rapid_mlx_agent.py. The weather tool returns fixed demonstration data, not a live weather observation. The first two turns request tools; the third summarizes their results from the retained conversation:

import asyncio
from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIChatModel
from pydantic_ai.providers.openai_compatible import OpenAICompatibleProvider
from pydantic_ai.usage import UsageLimits

model = OpenAIChatModel(
    'qwen3.5-9b-4bit',
    provider=OpenAICompatibleProvider(
        'rapid-mlx',
        base_url='http://127.0.0.1:8000/v1',
        api_key='local',
    ),
)


async def main():
    calls = []
    agent = Agent(
        model,
        system_prompt='Use the tools for weather and arithmetic. Preserve their results across turns. Answer concisely.',
        model_settings={'temperature': 0, 'max_tokens': 1024, 'timeout': 300},
    )

    @agent.tool_plain
    def get_weather(city: str) -> str:
        """Get the current weather for a city."""
        calls.append({'tool': 'get_weather', 'args': {'city': city}})
        return 'Oslo: 7 C, rainy' if city == 'Oslo' else 'Unknown city'

    @agent.tool_plain
    def add(a: int, b: int) -> int:
        """Add two integers exactly."""
        calls.append({'tool': 'add', 'args': {'a': a, 'b': b}})
        return a + b

    history = []
    for prompt in [
        'Use get_weather to get the current weather in Oslo. Remember it.',
        'Use add to calculate 17 + 25. Remember the result.',
        'Summarize the weather from the first turn and the arithmetic result from the second turn in one sentence.',
    ]:
        result = await agent.run(
            prompt,
            message_history=history,
            usage_limits=UsageLimits(request_limit=8),
        )
        history = result.all_messages()
        print(result.output)


asyncio.run(main())

Run it with python3 rapid_mlx_agent.py. Inspect result.all_messages() to confirm actual tool calls and tool results; a plausible final answer alone does not prove that a tool ran. The API key is a placeholder for an unauthenticated local server; use the actual key if authentication is enabled. To change models, change both the serve command and the Python model name. Start a fresh history when switching models or endpoints.

OpenAIProvider (imported from pydantic_ai.providers.openai) is an equally verified alternative: both providers passed this three-turn loop 3/3 with PydanticAI 2.71.0, openai 3.57.0, Rapid-MLX 1.1.0 and qwen3.5-9b-4bit, with no warnings.

Setup shortcut

With the server running, print matching environment exports:

$ rapid-mlx agents pydanticai --setup --model qwen3.5-9b-4bit --base-url http://127.0.0.1:8000/v1

The PydanticAI profile and setup adapter print export OPENAI_BASE_URL=http://127.0.0.1:8000/v1 and export OPENAI_API_KEY=not-needed; apply them in your shell yourself. They do not create an agent or select its model. In PydanticAI 2.71.0, OpenAIProvider() uses these exports through the OpenAI client: each variable supplies only its omitted connection argument, and an explicit base_url or api_key overrides that variable. With openai_client, the supplied client's configuration is used instead. OpenAICompatibleProvider does not read either export: it requires an explicit base_url or openai_client, and uses api-key-not-set when its own api_key is omitted. The explicit URL and key in the example above therefore work independently of these exports. rapid-mlx agents pydanticai also displays integration instructions.

Long prompts and timeouts

Cold prefill at 24k–48k tokens can take minutes on dense models, especially 27B. Keep sessions compact and reuse cached prefixes where possible. Set a client timeout of at least 300 seconds, as in model_settings above; increase it further for long-context 27B requests.

Troubleshooting

Versioned references: 2.71.0 OpenAIProvider API and OpenAICompatibleProvider API and model settings.

Optional: structured output

This separate example reuses the version-pinned model above. Structured-output behavior depends on the served model and endpoint support; the three-turn tool fixture does not verify this example. Reasoning can consume the output budget before JSON is produced, so allow enough max_tokens and inspect validation failures.

from pydantic import BaseModel

class Person(BaseModel):
    name: str
    age: int

agent = Agent(model, output_type=Person)
r = agent.run_sync("Extract: 'Alice is 30 years old'")
# Inspect r.output and confirm the extracted fields.

Optional: streaming

This separate text-streaming example reuses the model above. The three-turn tool fixture does not verify streaming or streamed tool calls. Check the actual chunks and final text; a text stream alone does not demonstrate tool use.

import asyncio

async def stream_test():
    agent = Agent(model)
    chunks = []
    async with agent.run_stream("Count from 1 to 5, separated by commas.") as result:
        async for delta in result.stream_text(delta=True):
            chunks.append(delta)
    return "".join(chunks)

print(asyncio.run(stream_test()))

See also