AI agents - Build AI Agents, Learn Handoffs, Learn to Integrate tools with AI agents | Sagar Kakkala´s World
Prerequisites for AI agent Demo
Before we start, generate Open AI API Key, you can checkout step "Pre-Requisties Before making a Fine-tune Model" in this blog here to know how to generate Open AI API Key - Fine Tune Model Blog
Now for this session, we will be using Jupyter Notebook, so install Anaconda on your local Machine - Anaconda Download
Once Downloaded and Installed, You will be able to see various tools offered by Anaconda
click on Jupyter Notebook - Launch
This would open Jupyter Notebook in your local browser
Now lets us create a new folder for our AI Agents here
Now once you are inside folder, let us create Jupyter Notebooks, we will create env file first to save our OpenAI API key
Now here we will save our generated OpenAIAPI key in this format
and also select python as kernel
click on Run icon or "Shift+Enter" for cell to execute code
here this code generally creates .env file and "w" stands for write, which actually erases any existing data of .env file and writes new data, if you want to append data, you can use "a" instead of w
AI Agent
Now let us create a new notebook for us to create AI agents and call this file there, we will create translator AI agent, you can create any AI agent of your choice
create a new notebook

And now let us call our OpenAI API key first before we start building our Agent
from dotenv import load_dotenv
load_dotenv()
if the result returned is true, this means we were able to successfully import our OpenAI API key and it would be used, Python checks the env file whenever required automatically and will be used by our AI agent
Now install Open-ai agents
pip install openai-agents
once agents are installed, let us check if we are able to successfully import agents and runners
from agents import Agent, Runner
since it executed cell without any errors, we are able to successfully import agents
Now let us build our first AI Agent
Build your own AI Agent
agent= Agent (
name= "Portugal language translator",
instructions= "you are a portugal langugage translator, you need to take user inputs in english and translate it in portugese" )
Here i had build translator agent, but you can built any agent of your choice like Spanish Translator, French Translator or even any other AI agent like detective agent for fun but make sure you give right instructions for agent to know its expected Task
Now let us have chat_history as well included for us to have logs
chat_history = []
Now let us use this AI agent, let us build user input prompt
while True:
userInput = input("Please provide word or sentence you want to translate: ")
if userInput.lower() in ["exit", "bye"]:
print("Sayonara Amigo!")
break
elif userInput.lower() == "history":
print("\n---- Chat History ----")
for i, (u, b) in enumerate(chat_history):
print(f"{i+1}. You: {u}\n ChatBot: {b}")
print("----------------------\n")
continue
result = await Runner.run(agent, userInput)
response = result.final_output
chat_history.append((userInput, response))
print("\nChatBot:", response)
print("To end chat, please type 'bye' or 'exit'. Type 'history' to view past conversations.\n")
since now our AI agent is ready to use, let us check if our AI agent is able to successfully do our job or not, since our AI agent is translator here, it takes inputs in English and gives response to us in Portugese
As seen, it could translate our inputs to english, Now since this Agent runs in loop, and we have specified condition to include history, you can type history to check conversation
Now since this agent runs in a loop, and to exit loop , type "exit" or "bye" to close AI agent
HandOff Agents
Now let us consider you have multiple AI agents, and based on user Input you need that particular Agent to be picked up, that is when handoff plays a major role, you can check for more in OpenAI Python SDK
let us here take a use case where an application has multiple language users, based on language user uses, it must respond in same language of user, this is where Handoff can be used
from agents import Agent, Runner
import asyncio
# Define the agents
spanish_agent = Agent(
name="Spanish agent",
instructions="You only speak Spanish.",
)
english_agent = Agent(
name="English agent",
instructions="You only speak English.",
)
triage_agent = Agent(
name="Triage agent",
instructions="Handoff to the appropriate agent based on the language of the request.",
handoffs=[spanish_agent, english_agent],
)
# Chat history for better context (optional)
chat_history = []
async def chat_with_agent():
print("π Hellowww! Type 'exit' or 'quit' to stop chatting.\n")
while True:
user_input = input("You: ")
if user_input.lower() in ["exit", "quit"]:
print("Sayonara! π")
break
elif user_input.lower() == "history":
print("\n---- Chat History ----")
for i, (u, b) in enumerate(chat_history):
print(f"{i+1}. You: {u}\n Agent: {b}")
print("----------------------\n")
continue
# Send the message to the triage agent
result = await Runner.run(triage_agent, input=user_input)
response = result.final_output
# Save to chat history
chat_history.append((user_input, response))
print(f"Agent: {response}\n")
# For Jupyter or IPython:
await chat_with_agent()
here in the code, we have used 3 AI agents , one agent which speaks only English, other Agent which speaks only Spanish and Triagent which actually checks user input and routes to particular agent. In other words, if user speaks english, it responds in English, if user speaks spanish, it responds in spanish
let us run this Agent now to check if our handoff is working fine or not
As seen from above screenshot, it responded exactly way we wanted , hence proving that handoff was successful
AI agent with Tools
AI Agent without Tools
from agents import Agent, Runner
import asyncio
# Define the agents
weather_agent = Agent(
name="Weather agent",
instructions="You search the internet about current temparature of the city asked by the user and give answer to the user.",
)
# Chat history for better context (optional)
chat_history = []
async def chat_with_agent():
print("π Enter the city you want to find temparature of.\n")
while True:
user_input = input("You: ")
if user_input.lower() in ["exit", "quit"]:
print("Goodbye! π")
break
elif user_input.lower() == "history":
print("\n---- Chat History ----")
for i, (u, b) in enumerate(chat_history):
print(f"{i+1}. You: {u}\n Agent: {b}")
print("----------------------\n")
continue
# Send the message to weather forecast agent
result = await Runner.run(weather_agent, input=user_input)
response = result.final_output
# Save to chat history
chat_history.append((user_input, response))
print(f"Agent: {response}\n")
# For Jupyter or IPython:
await chat_with_agent()
AI Agent with Tools
from agents import Agent, Runner, WebSearchTool
import asyncio
# Define the agents
weather_agent = Agent(
name="Weather agent",
instructions="You search the internet about current temparature of the city asked by the user and give answer to the user.",
tools=[WebSearchTool(user_location={"type": "approximate","country" : "IN","city": "Visakhapatnam"})]
)
# Chat history for better context (optional)
chat_history = []
async def chat_with_agent():
print("π Enter the city you want to find temparature of.\n")
while True:
user_input = input("You: ")
if user_input.lower() in ["exit", "quit"]:
print("Sayonara! π")
break
elif user_input.lower() == "history":
print("\n---- Chat History ----")
for i, (u, b) in enumerate(chat_history):
print(f"{i+1}. You: {u}\n Agent: {b}")
print("----------------------\n")
continue
# Send the message to weather forecast agent
result = await Runner.run(weather_agent, input=user_input)
response = result.final_output
# Save to chat history
chat_history.append((user_input, response))
print(f"Agent: {response}\n")
# For Jupyter or IPython:
await chat_with_agent()
























Comments
Post a Comment