PydanticAI agent
A PydanticAI agent designed to generate jokes, showcasing a minimal example using the Pydantic AI framework.
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/python7"""8
9from __future__ import annotations10
11from apify import Actor12
13from .agents import Deps, get_joker_agent14
15
16async def main() -> None:17 """Define a main entry point for the Apify Actor."""18 async with Actor:19 # Charge for Actor start20 await Actor.charge('actor-start')21 Actor.log.info('Starting joke generation agent.')22
23 # Process inputs24 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 joke32 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 ).output36 Actor.log.info(f'The AI generated joke about {joke_topic}:\n{joke}')37
38 # Store the joke39 dataset = await Actor.open_dataset()40 await dataset.push_data({'Topic': joke_topic, 'Joke': joke})41
42 # Charge for task completion43 await Actor.charge('task-completed')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.
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.
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 .
For complete information see this article . To run the Actor use the following command:
$apify run
If you've created a Git repository for the project, you can connect to Apify:
- Go to Actor creation page
- Click on Link Git Repository button
You can also deploy the project from your local machine to the Apify platform without the need for the Git repository.
-
Log in to Apify. You will need to provide your Apify API Token to complete this action.
$apify login -
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
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 eventand 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.
To learn more about Apify, Actors and PydanticAI take a look at the following resources:
Crawlee + BeautifulSoup
Crawl and scrape websites using Crawlee and BeautifulSoup. Start from a URL and store results to your Apify dataset.
Empty Python project
Start with Apify SDK already set up, then build any features you need.
One‑Page HTML Scraper with BeautifulSoup
Scrape single page with provided URL with HTTPX and extract data from page's HTML with Beautiful Soup.
BeautifulSoup
Example of a web scraper that uses Python HTTPX to scrape HTML from URLs provided on input, parses it using BeautifulSoup and saves results to storage.
Playwright + Chrome
Crawler example that uses headless Chrome driven by Playwright to scrape a website. Headless browsers render JavaScript and can help when getting blocked.
Selenium + Chrome
Scraper example built with Selenium and headless Chrome browser to scrape a website and save the results to storage. A popular alternative to Playwright.