Knowledge Base Sections ▾

Navigation

▸ Start here By roles

Categories

Tools 54
Glossary 12

Tools

PydanticAI + Gonka — typed AI agents for pennies

PydanticAI is a Python framework for creating AI agents from the Pydantic team (the very library for validation that supports half of the Python ecosystem). The main feature of PydanticAI is typed output: you describe the result as a standard Pydantic model, and the framework guarantees the model returns that exact structure, validated and ready to use. Plus, it features intuitive @agent.tool tool calling, dependency injection, and support for any provider.

The problem is the same as with all agent frameworks — token cost. An agent with tools runs context in circles: query → tool call → result → follow-up query. A single task can easily consume millions of tokens. At OpenAI ($2.50–$15 per 1M) and Anthropic ($3–$15 per 1M) rates, even a prototype becomes expensive, and production with thousands of requests per day becomes unaffordable.

PydanticAI works natively with any OpenAI-compatible endpoint via the OpenAIChatModel and OpenAIProvider classes. This means JoinGonka Gateway connects in just a few lines — without separate packages or adapters. The result: typed agents running for $0.0062 per 1M input tokens instead of $2.50–$15 at OpenAI/Anthropic — hundreds and thousands of times cheaper.

Quick Start: Connecting in Code

First, get your key: sign up at gate.joingonka.ai/register — when you register, we give you 3M free tokens — and create a jg-xxx key in Dashboard → API Keys.

Installation:

pip install pydantic-ai
# or the slim variant with only the OpenAI dependencies:
# pip install "pydantic-ai-slim[openai]"

A minimal example — an agent through Gonka. PydanticAI sets a custom endpoint via OpenAIProvider(base_url=..., api_key=...), which is passed to OpenAIChatModel:

from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIChatModel
from pydantic_ai.providers.openai import OpenAIProvider

model = OpenAIChatModel(
    "MiniMaxAI/MiniMax-M2.7",
    provider=OpenAIProvider(
        base_url="https://gate.joingonka.ai/v1",
        api_key="jg-your-key",
    ),
)

agent = Agent(model)

result = agent.run_sync("Explain in two sentences what PoUW is")
print(result.output)

That's it — your PydanticAI agent runs through the Gonka decentralized network for pennies. The run_sync method is handy for scripts; for async code, use await agent.run(...).

Model parameters: MiniMax M2.7 has a 180K token context window (180000), DeepSeek V4 Flash has 380K, GLM-5.3 Flash has 390K; the maximum response length through the Gateway is up to 8192 tokens for MiniMax and GLM-5.3 Flash, up to 32768 for DeepSeek. You can limit the output via model settings (OpenAIChatModelSettings(max_tokens=8192)). Available models: MiniMaxAI/MiniMax-M2.7, deepseek-ai/DeepSeek-V4-Flash-0731, and zai-org/GLM-5.3-Flash — just change the model name in the first argument of OpenAIChatModel.

PydanticAI Feature: Typed Output

The main reason to choose PydanticAI is structured output. Instead of parsing the response text with regexes, you describe the result as a Pydantic model and pass it to the output_type parameter. The framework uses the model's tool calling to force it to return data strictly according to the schema, validates it, and gives you a ready-made object via result.output.

from pydantic import BaseModel
from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIChatModel
from pydantic_ai.providers.openai import OpenAIProvider

model = OpenAIChatModel(
    "MiniMaxAI/MiniMax-M2.7",
    provider=OpenAIProvider(
        base_url="https://gate.joingonka.ai/v1",
        api_key="jg-your-key",
    ),
)


class Profile(BaseModel):
    name: str
    role: str
    skills: list[str]


agent = Agent(model, output_type=Profile)

result = agent.run_sync(
    "Extract the data: Anna is a backend developer who knows Python, Go and Postgres"
)
print(result.output)
# name='Anna' role='backend developer' skills=['Python', 'Go', 'Postgres']
print(result.output.skills)  # ['Python', 'Go', 'Postgres'] — already a list[str], not text

This works because all three Gonka models (MiniMax M2.7, DeepSeek V4 Flash, and GLM-5.3 Flash) support native tool calling — PydanticAI relies on it to return a valid JSON structure. What you get is a typed Python object, not a string you have to parse by hand. Perfect for data extraction, classification, form filling, and RAG pipelines, where the output must flow onward through code in a strict format.

Cost Comparison

PydanticAI is a framework for agents and pipelines that operate continuously: extracting data, calling tools, and processing request streams. Here, token cost decides whether a project remains a prototype or goes into production. Let's compare typical workloads:

ScenarioTokensOpenAI / AnthropicJoinGonka Gonka
Structure extraction from doc~3K$0.008 — $0.045~$0.000028
Agent with tool calling (one cycle)~15K$0.04 — $0.22~$0.00014
RAG pipeline (1000 requests/day)~5M/day$12 — $75/day~$0.048/day
Production agent (100K requests/day)~500M/day$1,250 — $7,500/day~$4.80/day

The difference is hundreds or thousands of times. For a prototype, this means the 3M free tokens are enough for the first agent runs. For production handling hundreds of thousands of requests per day, savings amount to tens of thousands of dollars per month — with the same code on PydanticAI, just with a different base_url.

One jg-xxx key and one balance work for both the OpenAI format (/v1) and the Anthropic format (/v1/messages) — but for PydanticAI, the OpenAI-compatible endpoint shown above is sufficient.

Tool calling and model selection

The second key PydanticAI feature is tools. You can register a function with the @agent.tool_plain decorator (no context) or @agent.tool (with access to RunContext and dependency injection). The model decides on its own when to call the tool, receives the result, and continues reasoning:

import random
from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIChatModel
from pydantic_ai.providers.openai import OpenAIProvider

model = OpenAIChatModel(
    "MiniMaxAI/MiniMax-M2.7",
    provider=OpenAIProvider(
        base_url="https://gate.joingonka.ai/v1",
        api_key="jg-your-key",
    ),
)

agent = Agent(
    model,
    instructions="You are an assistant. Use the tools when needed.",
)


@agent.tool_plain
def roll_dice() -> str:
    """Rolls a six-sided die and returns the result."""
    return str(random.randint(1, 6))


@agent.tool_plain
def calculator(expression: str) -> str:
    """Evaluates a math expression."""
    return str(eval(expression))


result = agent.run_sync("Roll the die and multiply the result by 7")
print(result.output)

Since tool calling on Gonka is native, tools are invoked reliably — no fragile parsing of text responses. The whole cycle (request → tool call → final answer) costs about $0.00007 through Gonka versus $0.04–0.22 at OpenAI/Anthropic.

Which model to choose: MiniMaxAI/MiniMax-M2.7 — for long conversations and balanced tasks, output up to 8192. deepseek-ai/DeepSeek-V4-Flash-0731 — one of the longest contexts on the network (380K) and cheap large prompts, output up to 32768. zai-org/GLM-5.3-Flash — a reasoning model for complex deliberation and the longest context on the network (390K), output up to 8192; reasoning consumes part of max_tokens, so set it with headroom (from 600). All three are available right now with a single key — only the model string changes. Kindred tools: LangChain for chains and RAG, LlamaIndex for data indexing.

PydanticAI + Gonka = typed AI agents in Python for pennies. Structured output with Pydantic models, native tool calling, dependency injection — all via OpenAIChatModel + OpenAIProvider with a single base_url. Cost: starting from $0.0062 per 1M tokens instead of $2.50–$15 at OpenAI and Anthropic.

Want to learn more?

Explore other sections or start earning GNK right now.

Get free tokens →