Skip to content

Building AI agents, atomically

add "what is atomic agents" notebook

KennyVaneetvelde7bde801c015c
diff --git a/examples/notebooks/what_is_atomic_agents.ipynb b/examples/notebooks/what_is_atomic_agents.ipynb
new file mode 100644
index 0000000..443e92d
--- /dev/null
+++ b/examples/notebooks/what_is_atomic_agents.ipynb
@@ -0,0 +1,700 @@
+{
+ "cells": [
+ {
+ "attachments": {
+ "image.png": {
+ "image/png": "iVBORw0KGgoAAAANSUhEUgAAA1kAAAC/CAYAAAAM9BYxAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAC1DSURBVHhe7d0HlJTV3cfxq4iF2Ess5EXFAnY0Ruw9VkRjjxoVUWNXghpRFLsee+y9966g2LvE3o29YUDsBRVFI6/f69xldphdZnefLTPP93POnp2dbcPyzJ37u+V/p5jwqyBJkiRJysSUhfeSJEmSpAwYsiRJkiQpQ4YsSZIkScqQIUuSJEmSMmTIkiRJkqQMGbIkSZIkKUOGLEmSJEnKkCFLkiRJkjJkyJIkSZKkDBmyJEmSJClDhixJkiRJypAhS5IkSZIyZMiSJEmSpAwZsiRJkiQpQ4YsSZIkScqQIUuSJEmSMmTIkiRJkqQMGbIkSZIkKUOGLEmSJEnKkCFLkiRJkjJkyJIkSZKkDBmyJEmSJClDhixJkiRJypAhS5IkSZIyZMiSJEmSpAwZsiRJkiQpQ4YsSZIkScqQIUuSJEmSMmTIkiRJkqQMGbIkSZIkKUOGLEmSJEnKkCFLkiRJkjJkyJIkSZKkDBmyJEmSJClDhixJkiRJypAhS5IkSZIyZMiSJEmSpAwZsiRJkiQpQ4YsSZIkScqQIUuSJEmSMmTIkiRJkqQMGbIkSZIkKUNTTPhV4bYkKSP//e9/w4cffhiefPLJ+PG///3v+F5qLf/3f/9XuDVR7969wx/+8IewwgorFO6RJLUFQ5YkZYRgdeONN4Ybbrgh3k7o5PImtbYnnniicKu+dP1tscUWYfPNN/d6lKRWZsiSpBZK4erUU0+NH9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f0aIX9fHycfvtt4dBgwaFJZZYIkwxxRThyy+/DGeffXZYYIEFCl/VsRAKKXBx5plnFu4p73e/+13o1atXWGaZZeIbQWv66acvfDYfaEcYsLGce9tIM4dpwIKPmVGVWlsaVEk4xoi+sv2HlslFyNp///3r9lPYSVIecL1z3XvNZ4NBGv6OzoLX995778VlZVTnO/744+Nsz7PPPttqIYtlfD/++GMMQM2dLXv++efDtttuG7777rvCPRP9/ve/j/+eNddcM8w+++yhc+fOhc/kE7NYLLP3yILWQYjiKA6CVdovnqTBYAeF1Za4JnkrxjXIa5/L5ZsuFyGLUWguGmexlBdc74xCw1HolkmB1fajPmaEjj322HDFFVeEAw88MPztb3+LQauxkMW+po8++iiMHDkyzDnnnGG++eab7KHFfA/LNS+44IK6JXuELF7wt9tuu9ClS5d4H/i5hC+qGzKrxtldJ554Yrj00kvD3//+9/g9PO7DDjssvPDCC2H99dcPq6++ephmmmnCMcccE0NcR56Fa2t0/lky6Yx4tgivtCupM5s6scwewL+12hvXJs9/2t60Jzldp5tvvrmvhRXKxZ6s4oZMygOudV6oU0MpZYm9TJdddlkMWOuss07YbLPNwtRTT134bHnvvvtuDKsrrrhi7LivscYaMewQehpC6GFpX//+/evtiWIWilB09NFHx6/B119/HYYMGRL23XffMGbMmPgYzznnnBiwwAHJFOdghur0008PjzzySDj00EPDKqusEhZaaKEw00wzxa/TRGkJUdqTqJYhXDErnopwccYhs4QM4DAAQJttwFJHkAIVKzi4PrlWwbXrmZyVq/mQlRK4y3yUN2lQwQ5SNhykmYjzpM4444zQtWvXsMcee4S55pqr8JkQZpxxxnqzS8xE3XbbbeEvf/lL3VljydNPPx1ntlhQwaxTcQU/QtIll1xSt9z1kEMOCS+99FI8i4sXeH73o48+GsMbmI1iBuubb76JIeyOO+6I31/szjvvjJ9ntqt4ueF0000X/3+pLMjj0G+85rORVhYUh6sUrKSOjnaAa5VjYrh2uZ7pWxu0Ji831QXTNLyUF17z2SiumqcQK/ClowIOOOCAsNRSS8XbhKJx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Pkq9n3nmmfEg4mWWWcb9VJKkmmPIUtXi/Jo+ffqEd999t3CPpI6IkuvnnntuLMVO1cCEioAcdKyOzYEaSZVKA7wyZNU8Du187bXXwpgxY+LHP/zwQ7jgggtiVa5zzjknHHvssfHQTw7y/P777+PXVIsvv/wyvPzyy3HpkaSObeqpp46H/aaS7Nzed99945lYkiTVGkNWDeNgzqFDh8YODecXcIhnjx494iZ0TqU//vjjw3nnnRceeeSRcPLJJ4dbbrml8J3VhfN2JFUHNkZTkp1ZrTnmmKNwr1Q7nPlTnlnVeyJDVg37+eef47ky3333XeGe+pZeeumw6qqrxiU7BK811lgjBrNq88EHH8R/KzNbL774YjynhHN0mLWTJDWf1cIkqXkMWTWsc+fOYffddw/XXntteOyxx8KIESNC37594+cGDx4cZ67Y13T++efHJYOcV1MNG9AJjW+88UasTAY20C+wwAKhV69e8d+39dZbh/XXXz8MGDAglo/OK0dTW86/oSRJlfE1s75chKw8/6dTHnmFFVaI07ezzTZbrPQFPq6mil7PPfdcWG+99eKSx0UXXTSss8464eabby58dqLu3buHLbbYIhx11FGxVLSHlkqS2pIdTUlwJitHWArI/iXKJs8111yFezu+H3/8MQYqCniUs8EGG4TbbrstvPLKK/EcnpNOOilsv/32YcEFFwxTTuklLklqWwYtSfZAc4Q9Sh999FGc0ZpxxhkL906KMPb222+Hzz//vHBPiNUJ99hjjziTdMkll8Q9UKVGjx4dDjjggDjTtNRSS4Ujjjgi/pxy+7yoZPjMM8/E75ncPjCqki233HKx9PNKK60Ui3TcfvvtsUIiFl544fj7mKXzvB2Ba4Nr5bTTTrOzI0mS2pwhK0cINt9++22cySo+q6YUhST222+/cPjhh8ev5+2EE06IpZdx9tlnh2effTbeTig4sdNOO4Xrr78+7pn66quvwsUXXxwPIP3Xv/41SRGKq6++OlY9JJR98cUXhXvr4/EyK3XPPfeEjTbaKDz11FPhqquuCptvvnkMVVawUUO4tnDqqafGsJUClyS1Bc8KkmTIypFvvvkmBpq55547TDfddIV7JzXTTDOFWWed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JEmSJGXIkCVJkiRJGTJkSZIkSVKGDFmSJEmSlCFDliRJkiRlyJAlSZIkSRkyZEmSJElShgxZkiRJkpQhQ5YkSZIkZciQJUmSJEkZMmRJkiRJUoYMWZIkSZKUIUOWJEmSJGXIkCVJkiRJGTJkSZIkSVKGDFmSJEmSlCFDliRJkiRlyJAlSZIkSRkyZEmSJElShgxZkiRJkpQhQ5YkSZIkZciQJUmSJEkZMmRJkiRJUoYMWZIkSZKUIUOWJEmSJGXIkCVJkiRJGTJkSZIkSVKGDFmSJEmSlCFDliRJkiRlyJAlSZIkSRkyZEmSJElSZkL4f+cyzpxOWESZAAAAAElFTkSuQmCC"
+ }
+ },
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Introducing Atomic Agents: Building AI with Modular Design\n",
+ "\n",
+ "Imagine building AI applications as easily as snapping together LEGO blocks. That's the idea behind [Atomic Agents](https://github.com/KennyVaneetvelde/atomic_agents), a new multi-agent framework inspired by **Atomic Design** principles.\n",
+ "\n",
+ "## Before we start, a brief background on Atomic Design\n",
+ "\n",
+ "First, let's talk about **Atomic Design**. Created by **Brad Frost**, it's a methodology for crafting design systems by breaking down interfaces into smaller, self-contained, reusable components. Think of it like atoms, molecules, and organisms in chemistry, but for UI design. This approach helps in creating scalable and consistent user interfaces while also allowing to modify/switch out any single part with minimal impact. Another analogy, as previously mentioned, is LEGO blocks where you can combine all the different, simple pieces to create something completely new and complex.\n",
+ "\n",
+ "## Why Atomic Agents?\n",
+ "\n",
+ "A lot of existing frameworks and methodologies for **Agentic AI** are focused on building autonomous multi-agent systems that you basically wind up and let go. While these can be fun to demo, they're not always practical for real-world applications. Real-life companies aren't looking for a bot that writes articles in a different style each time, with a different structure and a different tone. They want a bot that can write articles in a consistent style, with a consistent structure and a consistent tone that aligns with their brand. Beside fine-tuning a model, which requires a lot of data and money, and isn't even possible if you really want to use the latest GPT model, there's no practical way to gain full control of the output of these frameworks.\n",
+ "\n",
+ "In business, management rarely allocates budget just to create something that's cool but has no value. They want to see a return on investment. They want to see real business issues being solved and automated and cut costs. To achieve this, you need **modularity**, you need to be able to control the output, make sure it's not a black box, make the output reproducible, and make it reliable. This is where **Atomic Agents** come in.\n",
+ "\n",
+ "So how are these business problems solved traditionally, pre-AI? Well, before we even start writing code, we usually start with flows, user stories, customer journeys, ... and then we start breaking these down into smaller parts. We then start writing the necessary code. We'll have a function that takes in some input, processes it, and returns some output. We'll have another function that takes in that output, processes it, and stores it in a database. We'll have another function that queries the database, processes the data, and returns it to the user. The aim of **Atomic Agents** is to bring this same level of modularity and predictability to AI agent development.\n",
+ "\n",
+ "In other words, we are not looking to build \"An AI system that writes a blogpost\". We are looking for something highly structured and verbose. Specifically, we want to build an AI system that:\n",
+ "\n",
+ "1. Generates queries related to a subject\n",
+ "2. Identifies the top X most relevant articles\n",
+ "3. Visits each identified article's page\n",
+ "4. Extracts the text from each article\n",
+ "5. Generates a summary of each article\n",
+ "6. Stores the summaries in a vector database\n",
+ "7. Generates X questions around the subject\n",
+ "8. Uses the vector database to answer those questions\n",
+ "9. Re-synthesizes the answers into a coherent blogpost\n",
+ "\n",
+ "This approach; while being a lot more verbose, is also a lot more predictable, reliable, and, more importantly, usable in a real-world business.\n",
+ "\n",
+ "On top of that, we want to be able to fine-tune each individual step of that system if necessary, we want to be able to modify the system prompt for each task individually, be able to modify which tools are used, and how they are used, be able to choose where memory or context is shared, ... This is where **Atomic Agents** come in.\n",
+ "\n",
+ "## Anatomy of an Agent\n",
+ "\n",
+ "AI agents, not just in the **Atomic Agents** framework, take input from several sources, such as the **system prompt**, the **user input**, the (optionally) **available tools**, and **memory**. Within **Atomic Agents**, I wanted the developer to have full control over how each of these affects the output. This is why each of these are separate components within the framework. In developer terms, we speak of \"separation of concerns\" and \"single responsibility principle\" here.\n",
+ "\n",
+ "![Anatomy of an Atomic Agent](../../.assets/what_is_sent_in_prompt.png)\n",
+ "\n",
+ "In the diagram above, you can see the different components that make up an **Atomic Agent**. Each agent has a \"run\" method, an input schema and an output schema, each with their own schema descriptions, property descriptions, ... all defined by the developer using **Pydantic models**. This enables us to dynamically generate the input to the agent, and to validate its output. This is important because it allows us to chain agents together effortlessly, all the while ensuring that the output of one agent is the correct input for the next agent. Thus, in the schema all the green boxes are things that are always sent to the agent, the blue boxes are sent to the agent in the case where Agent1 is chained to Agent2, and Agent1 must generate output using the input schema of Agent2.\n",
+ "\n",
+ "Tools have almost the exact same setup, each tool has an input schema, an output schema, and a \"run\" method. This allows us to largely treat tools and agents the same way, and to chain them together in the same way. This is in line with a personal philosophy of mine that, at least until we reach AGI, we should treat AI agents as very advanced text-processing tools that are part of a bigger pipeline, rather than as a completely new paradigm (See [my article on Defensive & Robust design in AI automation](https://medium.com/@kenny_v/defensive-and-robust-design-in-ai-automation-8e951c8e7fd7)).\n",
+ "\n",
+ "![image.png](attachment:image.png)\n",
+ "\n",
+ "The real fun begins when you start chaining the input and output of different tools and agents together. By simply assigning the output schema of an agent to be the input schema to a tool, or to another agent, you can create complex AI applications that are still modular and easy to understand. If at any later point you change the tool, and change the schema, the entire system will still work without needing to change anything else."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Example: Building a simple AI agent\n",
+ "Now that we've covered the basics, let's build a simple AI agent using **Atomic Agents** and examine how it works under the hood.\n",
+ "\n",
+ "First, we need to install the Atomic Agents package. You can do this by running the following command:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Install necessary packages\n",
+ "%pip install atomic-agents openai instructor"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Or better yet, you can clone the repository from [here](https://github.com/KennyVaneetvelde/atomic_agents) and help me improve it!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Next, we will import the necessary components for creating the chatbot. Each component serves a specific purpose:\n",
+ "- `ChatMemory`: Manages the chat history.\n",
+ "- `BaseChatAgent`: The base class to create a custom chatbot. Can be extended for additional functionality if needed.\n",
+ "- `SystemPromptGenerator` and `SystemPromptInfo`: To define and generate system prompts."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator, SystemPromptInfo"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now let's define the system prompt information including background, steps, and output instructions. In this example, we will define a system prompt that asks the chatbot to respond to user inputs in rhyming verse.\n",
+ "\n",
+ "The structuring of the system prompts in this library is loosely inspired by the concept of **Patterns** in the [Fabric library](https://github.com/danielmiessler/fabric/tree/main/patterns)."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from rich.console import Console\n",
+ "\n",
+ "system_prompt = SystemPromptInfo(\n",
+ " background=[\n",
+ " 'This assistant is a general-purpose AI designed to be helpful and friendly.',\n",
+ " ],\n",
+ " steps=[\n",
+ " 'Understand the user\\'s input and provide a relevant response.',\n",
+ " 'Respond to the user.'\n",
+ " ],\n",
+ " output_instructions=[\n",
+ " 'Provide helpful and relevant information to assist the user.',\n",
+ " 'Be friendly and respectful in all interactions.',\n",
+ " 'Always answer in rhyming verse.'\n",
+ " ]\n",
+ ")\n",
+ "system_prompt_generator = SystemPromptGenerator(system_prompt)\n",
+ "\n",
+ "Console().print(system_prompt_generator.generate_prompt())"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This should have generated the following system prompt:\n",
+ "\n",
+ "``` markdown\n",
+ "# IDENTITY and PURPOSE\n",
+ "- This assistant is a general-purpose AI designed to be helpful and friendly.\n",
+ "\n",
+ "# INTERNAL ASSISTANT STEPS\n",
+ "- Understand the user's input and provide a relevant response.\n",
+ "- Respond to the user.\n",
+ "\n",
+ "# OUTPUT INSTRUCTIONS\n",
+ "- Provide helpful and relevant information to assist the user.\n",
+ "- Be friendly and respectful in all interactions.\n",
+ "- Always answer in rhyming verse.\n",
+ "- Always respond using the proper JSON schema.\n",
+ "- Always use the available additional information and context to enhance the response.\n",
+ "```\n",
+ "\n",
+ "Note how the last two output instructions are not part of the developer's specification, but are automatically added by the framework to increase reliability in the system prompt."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now that we have defined the system prompt, and thus essentially the behavior and purpose of the chatbot, it makes sense to define an initial memory with a message from the assistant to the user. This step is completely optional however as the `BaseChatAgent` that we will be using later has a check for this and will automatically create an empty memory if none is provided."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from atomic_agents.lib.components.chat_memory import ChatMemory\n",
+ "\n",
+ "memory = ChatMemory()\n",
+ "initial_memory = [\n",
+ " {'role': 'assistant', 'content': 'How do you do? What can I do for you? Tell me, pray, what is your need today?'}\n",
+ "]\n",
+ "memory.load(initial_memory)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now we are ready to create a custom chatbot. Either by using the `BaseChatAgent` class, or by extending it. Since this is a simple usecase, let's look at what it will look like if we simply use the class. In the code below, you can either specify your API key directly in the code or use an environment variable to store it.\n",
+ "\n",
+ "In this instance, I will use the OpenAI client with gpt-3.5-turbo. However, you can choose other clients such as **Anthropic**, **Mistral**, **Groq**, etc... For a full list, check out the [Instructor library docs](https://github.com/jxnl/instructor). Changing the client is as simple as changing the import statement, defining the client, and changing the `model` parameter to a model that is supported by that client (so, for example `llama3-70b-8192` on **Groq**)\n",
+ "\n",
+ "First, we'll set up the API key"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "API_KEY = ''\n",
+ "if not API_KEY:\n",
+ " # Get the environment variable\n",
+ " API_KEY = os.getenv('OPENAI_API_KEY')\n",
+ "\n",
+ "if not API_KEY:\n",
+ " raise ValueError('API key is not set. Please set the API key as a static variable or in the environment variable OPENAI_API_KEY.')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now we'll set up the patched `Instructor` client. This is what takes the `Pydantic` models and uses them for input validation and output generation."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import instructor\n",
+ "import openai\n",
+ "from atomic_agents.agents.base_chat_agent import BaseChatAgent, BaseChatAgentConfig\n",
+ "\n",
+ "client = instructor.from_openai(openai.OpenAI(api_key=API_KEY))\n",
+ "\n",
+ "agent = BaseChatAgent(\n",
+ " config=BaseChatAgentConfig(\n",
+ " client=client,\n",
+ " system_prompt_generator=system_prompt_generator,\n",
+ " model='gpt-3.5-turbo',\n",
+ " memory=memory,\n",
+ " )\n",
+ ")\n",
+ "\n",
+ "# Groq, for example would look like this:\n",
+ "# import groq\n",
+ "# client = instructor.from_groq(groq.Client(api_key=[YOUR API KEY]))\n",
+ "# agent = BaseChatAgent(\n",
+ "# config=BaseChatAgentConfig(\n",
+ "# model='llama3-70b-8192',\n",
+ "# ...\n",
+ "# )\n",
+ "# )"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now we are ready to run the chatbot. Let's start by printing the initial message, followed by a simple chat-loop. Personally, I like to have /exit and /quit as commands to exit the chatbot, but you can change this to whatever you like."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "print(f'Agent: {initial_memory[0][\"content\"]}')\n",
+ "\n",
+ "while True:\n",
+ " user_input = input('You: ')\n",
+ " if user_input.lower() in ['/exit', '/quit']:\n",
+ " print('Exiting chat...')\n",
+ " break\n",
+ " \n",
+ " response = agent.run(agent.input_schema(chat_message=user_input))\n",
+ " print(f'Agent: {response.chat_message}')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Behind the scenes\n",
+ "\n",
+ "So, what is happening behind the scenes when we run the chatbot? Let's dissect the `BaseChatAgent` and understand how it works.\n",
+ "\n",
+ "First off, as mentioned before, each tool and each agent has an **input schema** and an **output schema**.\n",
+ "\n",
+ "These schemas all extend from what is called the `BaseAgentIO` class. This class itself is a Pydantic model with some predefined methods to facilitate storing a structured response in memory and to facilitate printing the response to the console using the `rich` library."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from pydantic import BaseModel, Field\n",
+ "from rich.json import JSON\n",
+ "\n",
+ "class BaseAgentIO(BaseModel):\n",
+ " \"\"\"\n",
+ " Base class for input and output schemas for chat agents.\n",
+ " \"\"\"\n",
+ " def __str__(self):\n",
+ " return self.model_dump_json()\n",
+ " \n",
+ " def __rich__(self):\n",
+ " json_str = self.model_dump_json()\n",
+ " return JSON(json_str)\n",
+ " \n",
+ "class BaseChatAgentInputSchema(BaseAgentIO):\n",
+ " chat_message: str = Field(\n",
+ " ...,\n",
+ " description='The chat message exchanged between the user and the chat agent. '\n",
+ " 'This represents the message sent by the user.'\n",
+ " )\n",
+ "\n",
+ " class Config:\n",
+ " title = 'BaseChatAgentInputSchema'\n",
+ " description = 'This schema represents the user input message exchanged between the user and the chat agent.'\n",
+ " json_schema_extra = {\n",
+ " \"title\": title,\n",
+ " \"description\": description,\n",
+ " }\n",
+ "\n",
+ "class BaseChatAgentResponseSchema(BaseAgentIO):\n",
+ " chat_message: str = Field(\n",
+ " ...,\n",
+ " description='The chat message exchanged between the user and the chat agent. '\n",
+ " 'This contains the markdown-enabled response generated by the chat agent.'\n",
+ " )\n",
+ "\n",
+ " class Config:\n",
+ " title = 'BaseChatAgentResponseSchema'\n",
+ " description = 'This schema represents the response message exchanged between the user and the chat agent.'\n",
+ " json_schema_extra = {\n",
+ " \"title\": title,\n",
+ " \"description\": description,\n",
+ " }"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In the code above, you can see that the `BaseChatAgentInputSchema` and `BaseChatAgentOutputSchema` both:\n",
+ "- Extend from `BaseAgentIO`\n",
+ "- Have a `chat_message` field with a `description` property \n",
+ "- Have a Config class with a `title`, `description`, and `json_schema_extra` property.\n",
+ "\n",
+ "Let's analyze why these title and description properties are important, by looking at what will be presented to the LLM model when we run the chatbot. We can do this by simply dumping one of the schemas to JSON"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import json\n",
+ "\n",
+ "print(json.dumps(BaseChatAgentResponseSchema.model_json_schema(), indent=2))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This will output something like this:\n",
+ "\n",
+ "```json\n",
+ "{\n",
+ " \"description\": \"This schema represents the response message exchanged between the user and the chat agent.\",\n",
+ " \"properties\": {\n",
+ " \"chat_message\": {\n",
+ " \"description\": \"The chat message exchanged between the user and the chat agent. This contains the markdown-enabled response generated by the chat agent.\",\n",
+ " \"title\": \"Chat Message\",\n",
+ " \"type\": \"string\"\n",
+ " }\n",
+ " },\n",
+ " \"required\": [\n",
+ " \"chat_message\"\n",
+ " ],\n",
+ " \"title\": \"BaseChatAgentResponseSchema\",\n",
+ " \"type\": \"object\"\n",
+ "}\n",
+ "```\n",
+ "\n",
+ "This is what the LLM model will see and be constricted by when generating a response. Additionally, this allows for easy generation of documentation as well since these properties are generally accepted by most documentation generators. For example by using [sphinx-pydantic](https://sphinx-pydantic.readthedocs.io/en/latest/).\n",
+ "\n",
+ "Thus, changing the title and description to be more clear, descriptive and precise is encouraged both to improve & fine-tune the agent's performance, but also to improve the documentation of the agent.\n",
+ "\n",
+ "Note that even though in the base chat agent both the input and output schemas have a `chat_message` field, this is not a requirement. We can easily specify any schema we like as the input or the output schema.\n",
+ "\n",
+ "For example, we can even have a nested schema with enums, lists, and more complex structures as demonstrated below:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from enum import Enum\n",
+ "from typing import List, Optional\n",
+ "\n",
+ "\n",
+ "class YelpCategory(Enum):\n",
+ " ITALIAN = \"italian\"\n",
+ " MEXICAN = \"mexican\"\n",
+ " PIZZA = \"pizza\"\n",
+ " SUSHI = \"sushi\"\n",
+ " CHINESE = \"chinese\"\n",
+ " INDIAN = \"indian\"\n",
+ " THAI = \"thai\"\n",
+ " FRENCH = \"french\"\n",
+ " GREEK = \"greek\"\n",
+ " JAPANESE = \"japanese\"\n",
+ " KOREAN = \"korean\"\n",
+ " VIETNAMESE = \"vietnamese\"\n",
+ " AMERICAN = \"american\"\n",
+ " BBQ = \"bbq\"\n",
+ " BURGERS = \"burgers\"\n",
+ " SEAFOOD = \"seafood\"\n",
+ " STEAKHOUSES = \"steakhouses\"\n",
+ " VEGAN = \"vegan\"\n",
+ " VEGETARIAN = \"vegetarian\"\n",
+ "\n",
+ "class PriceRange(Enum):\n",
+ " ONE = \"1\"\n",
+ " TWO = \"2\"\n",
+ " THREE = \"3\"\n",
+ " FOUR = \"4\"\n",
+ "\n",
+ "class YelpSearchToolSchema(BaseAgentIO):\n",
+ " location: str = Field(..., description=\"Location to search for food.\")\n",
+ " term: Optional[str] = Field(None, description=\"Search term (e.g., 'pizza', 'sushi').\")\n",
+ " categories: Optional[List[YelpCategory]] = Field(None, description=\"Categories to filter by (e.g., 'italian, mexican').\")\n",
+ " price: Optional[List[PriceRange]] = Field(None, description=\"Price range to filter by (e.g., '1', '2', '3', '4'). Can be multiple. 1 is cheap. 2 and 3 are mid-range. 4 is the most high-end.\")\n",
+ " open_now: Optional[bool] = Field(False, description=\"Filter for businesses that are open now.\")\n",
+ " limit: Optional[int] = Field(10, description=\"Number of results to return.\")\n",
+ "\n",
+ " class Config:\n",
+ " title = \"YelpSearchTool\"\n",
+ " description = \"Tool for searching for food using the Yelp API. Returns a list of businesses with details such as name, rating, and address.\"\n",
+ " json_schema_extra = {\n",
+ " \"title\": title,\n",
+ " \"description\": description\n",
+ " }"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Some interesting things to note here:\n",
+ "- The price ranges and categories are defined as an enum, which means that the only valid values are the ones specified in the enum.\n",
+ "- The description of the `price_range` field lists what the values mean, which is important for the model to understand the context of the input. This essentially replaces the need for a prompt or few-show examples in the traditional sense.\n",
+ "- If this is not sufficient, [Pydantic examples](https://docs.pydantic.dev/latest/concepts/fields/#customizing-json-schema) can still be added as well per property."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Extending the BaseChatAgent"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import json\n",
+ "from pydantic import Field, create_model\n",
+ "from atomic_agents.agents.base_chat_agent import BaseAgentIO, BaseChatAgent, BaseChatAgentConfig\n",
+ "from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator, SystemPromptInfo\n",
+ "from atomic_agents.lib.tools.base import BaseTool\n",
+ "from atomic_agents.lib.utils.format_tool_message import format_tool_message\n",
+ "\n",
+ "class ToolInterfaceAgentConfig(BaseChatAgentConfig):\n",
+ " tool_instance: BaseTool\n",
+ " return_raw_output: bool = False\n",
+ "\n",
+ "class ToolInputModel(BaseAgentIO):\n",
+ " tool_input: str = Field(..., description=\"Tool input. Presented as a single question or instruction\")\n",
+ "\n",
+ " class Config:\n",
+ " title = \"Default Tool\"\n",
+ " description = \"Default tool description\"\n",
+ " json_schema_extra = {\n",
+ " \"title\": \"Default Tool\",\n",
+ " \"description\": \"Default tool description\"\n",
+ " }\n",
+ "\n",
+ "class ToolInterfaceAgent(BaseChatAgent):\n",
+ " \"\"\"\n",
+ " A specialized chat agent designed to interact with a specific tool.\n",
+ "\n",
+ " This agent extends the BaseChatAgent to include functionality for interacting with a tool instance.\n",
+ " It generates system prompts, handles tool input and output, and can optionally return raw tool output.\n",
+ "\n",
+ " Attributes:\n",
+ " tool_instance: The instance of the tool this agent will interact with.\n",
+ " return_raw_output (bool): Whether to return the raw output from the tool.\n",
+ " \"\"\"\n",
+ "\n",
+ " def __init__(self, config: ToolInterfaceAgentConfig):\n",
+ " \"\"\"\n",
+ " Initializes the ToolInterfaceAgent.\n",
+ "\n",
+ " Args:\n",
+ " config (ToolInterfaceAgentConfig): Configuration for the tool interface agent.\n",
+ " \"\"\"\n",
+ " super().__init__(config=config)\n",
+ " \n",
+ " self.tool_instance = config.tool_instance\n",
+ " self.return_raw_output = config.return_raw_output\n",
+ " \n",
+ " # Create a new model with the updated schema\n",
+ " self.input_schema = create_model(\n",
+ " self.tool_instance.tool_name,\n",
+ " tool_input=(str, Field(..., description=f\"{self.tool_instance.tool_name} tool input. Presented as a single question or instruction\", alias=f'tool_input_{self.tool_instance.tool_name}')),\n",
+ " __base__=ToolInputModel\n",
+ " )\n",
+ " \n",
+ " # Manually set the configuration attributes\n",
+ " self.input_schema.model_config['title'] = self.tool_instance.tool_name\n",
+ " self.input_schema.model_config['description'] = self.tool_instance.tool_description\n",
+ " self.input_schema.model_config['json_schema_extra'] = {\n",
+ " 'title': self.tool_instance.tool_name,\n",
+ " 'description': self.tool_instance.tool_description\n",
+ " }\n",
+ " \n",
+ " if self.return_raw_output:\n",
+ " self.output_schema = self.tool_instance.output_schema\n",
+ " \n",
+ " self.system_prompt_generator = SystemPromptGenerator(\n",
+ " system_prompt_info=SystemPromptInfo(\n",
+ " background=[\n",
+ " f\"This AI agent is designed to interact with the {self.tool_instance.tool_name} tool.\",\n",
+ " f\"Tool description: {self.tool_instance.tool_description}\"\n",
+ " ],\n",
+ " steps=[\n",
+ " \"Get the user input.\",\n",
+ " \"Convert the input to the proper parameters to call the tool.\",\n",
+ " \"Call the tool with the parameters.\",\n",
+ " \"Respond to the user\"\n",
+ " ],\n",
+ " output_instructions=[\n",
+ " \"Make sure the tool call will maximize the utility of the tool in the context of the user input.\",\n",
+ " \"Process the output of the tool into a human readable format and/or use it to respond to the user input.\" if self.return_raw_output else \"Return the raw output of the tool.\"\n",
+ " ]\n",
+ " )\n",
+ " )\n",
+ " \n",
+ " def _get_and_handle_response(self):\n",
+ " \"\"\"\n",
+ " Handles obtaining and processing the response from the tool.\n",
+ "\n",
+ " This method gets the response from the tool, formats the tool input, adds it to memory,\n",
+ " runs the tool, and processes the tool output. If `return_raw_output` is True, it returns\n",
+ " the raw tool output; otherwise, it processes the output and returns the response.\n",
+ " \n",
+ " Returns:\n",
+ " BaseModel: The processed response or raw tool output.\n",
+ " \"\"\"\n",
+ " tool_input = self.get_response(response_model=self.tool_instance.input_schema)\n",
+ " formatted_tool_input = format_tool_message(tool_input)\n",
+ " \n",
+ " self.memory.add_message('assistant', 'TOOL CALL: ' + json.dumps(formatted_tool_input))\n",
+ " tool_output = self.tool_instance.run(tool_input)\n",
+ " self.memory.add_message('assistant', 'TOOL RESPONSE: ' + tool_output.model_dump_json())\n",
+ " \n",
+ " if self.return_raw_output:\n",
+ " return tool_output\n",
+ " \n",
+ " self.memory.add_message('assistant', 'I will now formulate a response for the user based on the tool output.')\n",
+ " response = self.get_response(response_model=self.output_schema) \n",
+ " return response\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As mentioned before, another way to create a new agent is by extending the `BaseChatAgent` class. This allows for more flexibility and customization. Let's look at an example where we extend the `BaseChatAgent` class to create an agent of which the output will always match the required input for a tool. To achieve this and get both the tool call and tool response in the memory, we will want to override the method `_get_and_handle_response`. Additionally, we will want to generate the input schema **dynamically** in order to be able to use any tool we want with this new agent.\n",
+ "\n",
+ "A simple example of how to use this ToolInterfaceAgent could be as follows:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "import instructor\n",
+ "import openai\n",
+ "from rich.console import Console\n",
+ "\n",
+ "from atomic_agents.agents.tool_interface_agent import ToolInterfaceAgent, ToolInterfaceAgentConfig\n",
+ "from atomic_agents.lib.tools.search.searx_tool import SearxNGSearchTool, SearxNGSearchToolConfig\n",
+ "\n",
+ "def initialize_searx_tool():\n",
+ " \"\"\"\n",
+ " Initialize the SearxNGSearchTool with configuration.\n",
+ " \"\"\"\n",
+ " base_url = os.getenv('SEARXNG_BASE_URL')\n",
+ " config = SearxNGSearchToolConfig(base_url=base_url, max_results=10)\n",
+ " return SearxNGSearchTool(config)\n",
+ "\n",
+ "def initialize_agent(client, searx_tool):\n",
+ " \"\"\"\n",
+ " Initialize the ToolInterfaceAgent with the given client and SearxNGSearchTool.\n",
+ " \"\"\"\n",
+ " agent_config = ToolInterfaceAgentConfig(\n",
+ " client=client,\n",
+ " model='gpt-3.5-turbo',\n",
+ " tool_instance=searx_tool,\n",
+ " return_raw_output=False\n",
+ " )\n",
+ " return ToolInterfaceAgent(config=agent_config)\n",
+ "\n",
+ "def main():\n",
+ " console = Console()\n",
+ " client = instructor.from_openai(\n",
+ " openai.OpenAI(\n",
+ " base_url='http://localhost:1234/v1'\n",
+ " )\n",
+ " )\n",
+ " searx_tool = initialize_searx_tool()\n",
+ " agent = initialize_agent(client, searx_tool)\n",
+ "\n",
+ " console.print(\"ToolInterfaceAgent with SearxNGSearchTool is ready.\")\n",
+ "\n",
+ " while True:\n",
+ " user_input = input('You: ')\n",
+ " if user_input.lower() in ['exit', 'quit']:\n",
+ " print('Exiting chat...')\n",
+ " break\n",
+ " \n",
+ " # Fix this\n",
+ " response = agent.run(agent.input_schema(tool_input=user_input))\n",
+ " console.print(f'Agent: {response.chat_message}')\n",
+ "\n",
+ "if __name__ == \"__main__\":\n",
+ " main()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Conclusion\n",
+ "\n",
+ "For now, that's it! While this guide is by no means complete, it should serve as a decent starting point for anyone looking to get started with **Atomic Agents**. If you have any questions, feel free to reach out to me! I'm always happy to help out and answer any questions you might have. If you want to contribute to the project, feel free to open a pull request on the [GitHub repository](https://github.com/KennyVaneetvelde/atomic_agents). Any help is greatly appreciated!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "---"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "If this article sparks your interest and you have any business inquiries, feel free to get in touch with me on [LinkedIn](https://www.linkedin.com/in/kennyvaneetvelde/). As an experienced life-long full-stack developer and course author with a grand fascination for what makes things ‘tick’ and a love for AI that started in my early teens, I am absolutely certain I can assist with anything from coaching to product development to bespoke consultancy services."
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "venv",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.12.3"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}