Hosted with nbsanity. See source notebook on GitHub.

Building Effective Agents (with Pydantic AI)

Examples for the agentic workflows discussed in Building Effective Agents by Erik Schluntz and Barry Zhang of Anthropic, inspired, ported and adapted from the code samples by the authors using Pydantic AI.

Orchestrator - Workers

%pip install -r requirements.txt
from IPython.display import clear_output ; clear_output()
from util import initialize, show
AI_MODEL = initialize()

import asyncio
import json
from typing import List, Dict

from pydantic import BaseModel, Field
from pydantic_ai import Agent
Available AI models:
['openai:gpt-4o',
 'openai:gpt-4o-mini',
 'gemini-1.5-pro',
 'gemini-2.0-flash-exp',
 'claude-3-5-haiku-latest',
 'claude-3-5-sonnet-latest']
Using AI model: openai:gpt-4o

Workflow: Orchestrator - Workers

An orchestrator is an agent that determines what work needs to be done and divides it so that it can be delegated to multiple workers. Once the work plan is ready, we run each task by a separate worker in parallel and eventually collect the results from all workers.

The schemas defined by Pydantic are translated into JSON schema, which is passed on to the model API for defining how the result should be structured. Each API handles this a bit differentls, but the details are abstracted by the library. In general, some complexity and nesting of types is usually OK. In this case, we define a Task type, and return a list of tasks as part of OrchestratorResponse.

Agents in Pydantic AI have some fixed definitions, like their system_prompt, and can be used to execute multiple runs, each with its own prompt. Here we define a worker agent instance, which can execute each task definition.

class Task(BaseModel):
    type: str = Field(..., description=(
        'The type of task. '
        'For example: "formal", "conversational", "hybrid", ...'))
    description: str = Field(
        ...,
        description='Clear description for executing this task.'
    )


class OrchestratorResponse(BaseModel):
    analysis: str = Field(..., description=(
        'Explain your understanding of the task and which variations '
        'would be valuable. Focus on how each approach serves '
        'different aspects of the task.'
    ))
    tasks: List[Task] = Field(..., description="List of tasks")


async def orchestrate(task: str) -> Dict:
    """Process task by breaking it down and running subtasks in parallel."""

    orchestrator_agent = Agent(
        AI_MODEL,
        system_prompt=(
            'Analyze this task and break it down into ',
            '2-3 distinct approaches.',
        ),
        result_type=OrchestratorResponse,
    )
    orchestrator_response = await orchestrator_agent.run(task)
    
    analysis = orchestrator_response.data.analysis
    tasks = orchestrator_response.data.tasks
    
    show('', title='Orchestrator Output')
    show(analysis, title='Analysis')
    show([task.model_dump() for task in tasks], title='Tasks')
    
    # Process all the tasks in parallel and collect results
    worker_agent = Agent(
        AI_MODEL,
        system_prompt='Generate content based on the task specification.',
    )
    worker_responses = await asyncio.gather(*[
        worker_agent.run(json.dumps(
            {'original_task': task} | task_info.model_dump()
        ))
        for task_info in tasks
    ])

    for task, response in zip(tasks, worker_responses):
        show(response.data, title=f"Worker Result ({task.type})")
await orchestrate(
    'Write a product description for a new eco-friendly water bottle.'
)

Orchestrator Output
-------------------


Analysis
--------

Creating a product description for a new eco-friendly water bottle involves focusing on its unique selling points, benefits to the consumer, and environmental impact. Different tones and styles can appeal to different market segments or purposes. A formal approach may be suitable for corporate presentations or websites targeting environmentally-conscious professionals. Conversational tones can engage a broader audience through storytelling and relatable language. Meanwhile, a hybrid approach can blend the professionalism of formal writing with the accessibility of a conversational style.


Tasks
-----

[{'description': 'Create a detailed and polished product description '
                 'emphasizing the eco-friendly aspects, material quality, and '
                 'health benefits of the new water bottle. This should cater '
                 'to an audience looking for sustainable and high-quality '
                 'products.',
  'type': 'formal'},
 {'description': 'Write an engaging and relatable product description that '
                 'highlights the eco-friendly features and benefits of the '
                 'water bottle. Use storytelling or relatable scenarios to '
                 'connect with the audience.',
  'type': 'conversational'},
 {'description': 'Craft a product description that combines formal and '
                 'conversational tones. Detail the eco-friendly nature and '
                 'benefits while keeping the language accessible and engaging '
                 'for a broader audience.',
  'type': 'hybrid'}]


Worker Result (formal)
----------------------

Introducing the AquoPure Eco-Friendly Water Bottle, a revolutionary product designed for the conscious consumer. Meticulously crafted from high-grade, sustainably sourced materials, the AquoPure Water Bottle epitomizes the perfect blend of sustainability, durability, and health-centric design.

Constructed from 100% BPA-free Tritan™, a material renowned for its outstanding clarity and superior shatter resistance, this water bottle guarantees a safe and toxin-free hydration experience. Tritan™ not only ensures that your liquids taste exactly as they should, maintaining their pure flavor, but also withstands years of daily usage, making it a highly durable alternative to single-use plastics.

Our bottle is crafted with a double-walled vacuum insulation that keeps beverages cold for up to 24 hours and hot for up to 12 hours, offering exceptional versatility to cater to your lifestyle needs, whether on a rigorous hike or during a day at the office. The innovative design also includes a spill-proof, one-touch open lid that ensures convenience without compromising your commitment to sustainability.

The AquoPure Water Bottle comes in elegantly understated colors derived from natural pigments, reflecting the beauty of the earth while minimizing environmental impact. Each purchase contributes to reforestation projects, reinforcing our pledge to give back to the planet.

Making the switch to AquoPure is not just a purchase; it's a movement towards a healthier body and a healthier planet. Experience hydration reimagined with the AquoPure Eco-Friendly Water Bottle — where eco-conscious living meets unparalleled performance. Invest in a product that supports both your lifestyle and our environment today.


Worker Result (conversational)
------------------------------

Imagine you're heading out for a long day – maybe it's a hike through the lush forest trails, a jam-packed day at the office, or an intense session at the gym. You want to stay hydrated but are also mindful of your impact on the planet. Meet the HydrateGreen, the eco-friendly water bottle that's about to become your favorite companion on all your adventures.

Crafted from 100% recycled stainless steel, the HydrateGreen is not just any water bottle; it's a statement of your commitment to sustainability. Its sleek, modern design fits comfortably in your hand, while the vibrant shades inspired by nature – think ocean blues, forest greens, and sunset oranges – make every sip a reminder of the beauty you’re helping preserve.

Picture this: it's a sweltering afternoon, but your HydrateGreen bottle keeps your water ice-cold for up to 24 hours, thanks to its innovative double-wall vacuum insulation. Or maybe it's a chilly morning, and your steaming hot coffee stays warm and comforting through your entire commute. From the first sip to the last, your drink stays at the perfect temperature.

And it's not just about keeping drinks at the right temperature. The HydrateGreen features a custom bamboo cap complete with a convenient, eco-friendly carrying handle, allowing you to securely attach it to your backpack or gym bag. Plus, every bottle you purchase supports ocean cleanup initiatives, so you’ll rest assured knowing you’re helping reduce plastic waste.

Embrace a lifestyle of sustainability and style. Whether you’re conquering mountain trails, surviving the concrete jungle, or simply relaxing at home, let the HydrateGreen bottle be your go-to choice for hydration that respects our planet. With every sip, you’re not just hydrating your body, but nourishing our world. Choose the HydrateGreen and redefine what it means to drink responsibly.


Worker Result (hybrid)
----------------------

Introducing the EcoFlow Water Bottle: Your Perfect Companion for a Sustainable Lifestyle!

Hey there, eco-warriors and hydration enthusiasts! Meet the EcoFlow Water Bottle, a groundbreaking solution for those who care about staying hydrated and preserving our beautiful planet. This isn't just any water bottle; it’s a testament to mindful living and conscious choices.

Made from 100% recycled stainless steel, the EcoFlow Water Bottle embodies eco-conscious design without compromising on durability or style. Its sleek, modern aesthetic is perfect for both your morning yoga session and your afternoon board meeting. The triple-insulated design keeps your beverages cold for up to 24 hours, or hot for up to 12, so your drink is always at the perfect temperature, just like magic!

But wait, it gets better. With every purchase, a portion of the proceeds goes directly to ocean clean-up initiatives, turning your hydration habit into a force for environmental good. Our commitment to reducing plastic waste means no BPA, no harmful chemicals—just pure, environmentally friendly goodness sip after sip.

Worried about spills or leaks? The EcoFlow features an innovative leak-proof cap and a comfortable grip, making it easy to carry on those morning jogs or hike. Plus, it’s dishwasher safe, letting you spend more time on what matters and less on scrubbing.

Embrace sustainability and style with the EcoFlow Water Bottle. It’s more than just a product; it’s a statement. Refresh yourself and the planet with every glass of water. Ready to join the revolution? Grab your EcoFlow today and take that first sip toward a better tomorrow!