Skip to main content

Introduction

PydanticAI is a newer framework that brings powerful features for working with LLMs. Although it doesn’t yet have a collection of pre-built tools like other frameworks, it offers useful capabilities such as dependency injection. This feature allows you to inject a “Context” into tools, which can help pass parameters or manage state without relying on LLMs. Though it’s still evolving, you can easily integrate PydanticAI tools into AG2 to boost agent capabilities, particularly for tasks that involve structured data and context-driven logic.

Installation

To get PydanticAI tools working with AG2, install the necessary dependencies:

Imports

Import necessary modules and tools.
  • BaseModel: Used to define data structures for tool inputs and outputs.
  • RunContext: Provides context during the execution of tools.
  • PydanticAITool: Represents a tool in the PydanticAI framework.
  • AssistantAgent and UserProxyAgent: Agents that facilitate communication in the AG2 framework.
  • Interoperability: This module acts as a bridge, making it easier to integrate PydanticAI tools with AG2’s architecture.

Agent Configuration

Configure the agents for the interaction.
  • config_list defines the LLM configurations, including the model and API key.
  • UserProxyAgent simulates user inputs without requiring actual human interaction (set to NEVER).
  • AssistantAgent represents the AI agent, configured with the LLM settings.

Tool Integration

To integrate a PydanticAI tool into AG2:
  • First, define a Player model using BaseModel to structure the input data.
  • Use RunContext to inject dependencies (like the Player instance) securely into the tool.
  • The get_player function defines the tool’s functionality, retrieving injected data through ctx.deps.
  • Then, convert the tool into an AG2-compatible format with Interoperability.
  • Register the tool for execution and interaction with both the user_proxy and chatbot.

Initiating the chat

Now that everything is set up, you can initiate a chat between the UserProxyAgent and the AssistantAgent:
  • The user_proxy sends a message to the chatbot.
  • The user requests player information, and includes “goal keeper” as additional context.
  • The Player data is securely injected into the tool, and the chatbot can access and use it during the chat.

Output