Back to template gallery

PydanticAI agent

A PydanticAI agent designed to generate jokes, showcasing a minimal example using the Pydantic AI framework.

Language

python

Tools

pydanticai

Use cases

Ai

my_actor/main.py

my_actor/agents.py

my_actor/__main__.py

1"""Module defines the main entry point for the Apify Actor.
2
3Feel free to modify this file to suit your specific needs.
4
5To build Apify Actors, utilize the Apify SDK toolkit, read more at the official documentation:
6https://docs.apify.com/sdk/python
7"""
8
9from __future__ import annotations
10
11from apify import Actor
12
13from .agents import Deps, get_joker_agent
14
15
16async def main() -> None:
17 """Define a main entry point for the Apify Actor."""
18 async with Actor:
19 # Charge for Actor start
20 await Actor.charge('actor-start')
21 Actor.log.info('Starting joke generation agent.')
22
23 # Process inputs
24 actor_input = await Actor.get_input()
25
26 if not (joke_topic := actor_input.get('jokeTopic')):
27 await Actor.fail(status_message='Missing "jokeTopic" attribute in input!')
28
29 model_name = actor_input.get('modelName', 'deepseek/deepseek-v4-flash')
30
31 # Generate joke
32 agent = get_joker_agent(model_name)
33 joke = (
34 await agent.run(user_prompt='Tell me a joke.', deps=Deps(joke_topic=joke_topic, model_name=model_name))
35 ).output
36 Actor.log.info(f'The AI generated joke about {joke_topic}:\n{joke}')
37
38 # Store the joke
39 dataset = await Actor.open_dataset()
40 await dataset.push_data({'Topic': joke_topic, 'Joke': joke})
41
42 # Charge for task completion
43 await Actor.charge('task-completed')

PydanticAI template

Start a new AI agent  based project in Python with our PydanticAI project template. It provides a basic structure for the Actor  using the Apify SDK  and PydanticAI , and allows you to add your own functionality with minimal setup.

How it works

Insert your own code to async with Actor: block. You can use the Apify SDK  with any other Python library. Add or modify the agent and tools in my_actor/agents.py.

LLM provider

The agent talks to its LLM through the Apify OpenRouter proxy  — an OpenAI-compatible endpoint at https://openrouter.apify.actor/api/v1 that fronts the full OpenRouter  model catalog. Token usage is billed against the user's Apify account (pay-per-event), so no OPENAI_API_KEY or any other provider API key is required. The Actor authenticates with the proxy using the APIFY_TOKEN that the platform injects into every run automatically.

If you'd rather call OpenAI / Anthropic / etc. directly with your own key, swap the OpenAIProvider configuration in my_actor/agents.py — see the PydanticAI OpenAI docs .

Getting started

For complete information see this article . To run the Actor use the following command:

$apify run

Deploy to Apify

Connect Git repository to Apify

If you've created a Git repository for the project, you can connect to Apify:

  1. Go to Actor creation page 
  2. Click on Link Git Repository button

Push project on your local machine to Apify

You can also deploy the project from your local machine to the Apify platform without the need for the Git repository.

  1. Log in to Apify. You will need to provide your Apify API Token  to complete this action.

    $apify login
  2. Deploy your Actor. This command will deploy and build the Actor on the Apify Platform. You can find your newly created Actor under Actors -> My Actors .

    $apify push

Pay Per Event

This template uses the Pay Per Event (PPE)  monetization model, which provides flexible pricing based on defined events.

To charge users, define events in JSON format and save them on the Apify platform. Here is an example schema with the task-completed event:

[
{
"task-completed": {
"eventTitle": "Task completed",
"eventDescription": "Flat fee for completing the task.",
"eventPriceUsd": 0.01
}
}
]

In the Actor, trigger the event with:

await Actor.charge(event_name='task-completed')

This approach allows you to programmatically charge users directly from your Actor, covering the costs of execution and related services, such as LLM input/output tokens.

To set up the PPE model for this Actor:

  • Configure Pay Per Event: establish the Pay Per Event pricing schema in the Actor's Monetization settings. First, set the Pricing model to Pay per event and add the schema. An example schema can be found in pay_per_event.json.

No provider API key (e.g. OPENAI_API_KEY) needs to be configured — LLM costs are billed through the Apify OpenRouter proxy to the user running the Actor.

Resources

To learn more about Apify, Actors and PydanticAI take a look at the following resources:

Already have a solution in mind?

Sign up for a free Apify account and deploy your code to the platform in just a few minutes! If you want a head start without coding it yourself, browse our Store of existing solutions.