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.
AssistantAgentandUserProxyAgent: 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_listdefines the LLM configurations, including the model and API key.UserProxyAgentsimulates user inputs without requiring actual human interaction (set toNEVER).AssistantAgentrepresents the AI agent, configured with the LLM settings.
Tool Integration
To integrate a PydanticAI tool into AG2:- First, define a
Playermodel using BaseModel to structure the input data. - Use RunContext to inject dependencies (like the
Playerinstance) securely into the tool. - The
get_playerfunction defines the tool’s functionality, retrieving injected data throughctx.deps. - Then, convert the tool into an AG2-compatible format with
Interoperability. - Register the tool for execution and interaction with both the
user_proxyandchatbot.
Initiating the chat
Now that everything is set up, you can initiate a chat between theUserProxyAgent and the AssistantAgent:
- The
user_proxysends a message to thechatbot. - The user requests player information, and includes “goal keeper” as additional context.
- The
Playerdata is securely injected into the tool, and the chatbot can access and use it during the chat.