PydanticAI agent
PydanticAI agent to generate a joke
src/main.py
src/agents.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
11import os
12
13from apify import Actor
14
15from src.agents import Deps, get_joker_agent
16
17
18async def main() -> None:
19 """Define a main entry point for the Apify Actor."""
20 async with Actor:
21 # Charge for Actor start
22 await Actor.charge('actor-start')
23 Actor.log.info('Starting joke generation agent.')
24
25 # Process inputs
26 actor_input = await Actor.get_input()
27 if openai_api_key := (actor_input.get('openAIApiKey') or os.environ.get('OPENAI_API_KEY')):
28 os.environ['OPENAI_API_KEY'] = openai_api_key
29 else:
30 await Actor.fail(
31 status_message='OpenAI API key is missing. Create issues at the Apify platform to inform the developer'
32 )
33
34 if not (joke_topic := actor_input.get('jokeTopic')):
35 await Actor.fail(status_message='Missing "jokeTopic" attribute in input!')
36
37 # Generate joke
38 joke = (await get_joker_agent().run(user_prompt='Tell me a joke.', deps=Deps(joke_topic=joke_topic))).data
39 Actor.log.info(f'The AI generated joke about {joke_topic}:\n{joke}')
40
41 # Store the joke
42 dataset = await Actor.open_dataset()
43 await dataset.push_data({'Topic': joke_topic, 'Joke': joke})
44
45 # Charge for task completion
46 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 the src/agents.py file.
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:
- Go to Actor creation page
- 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.
-
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
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:
1[ 2 { 3 "task-completed": { 4 "eventTitle": "Task completed", 5 "eventDescription": "Flat fee for completing the task.", 6 "eventPriceUsd": 0.01 7 } 8 } 9]
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 the OpenAI API key environment variable: provide your OpenAI API key to the
OPENAI_API_KEY
in the Actor's Environment variables. - 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 .actor/pay_per_event.json.
Resources
To learn more about Apify, Actors and PydanticAI take a look at the following resources:
Scrape single page with provided URL with HTTPX and extract data from page's HTML with Beautiful Soup.
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.
Crawler example that uses headless Chrome driven by Playwright to scrape a website. Headless browsers render JavaScript and can help when getting blocked.
Scraper example built with Selenium and headless Chrome browser to scrape a website and save the results to storage. A popular alternative to Playwright.
Empty template with basic structure for the Actor with Apify SDK that allows you to easily add your own functionality.
Template with basic structure for an Actor using Standby mode that allows you to easily add your own functionality.