Skip to Content

Creating your first agent

Introduction

Once you’ve installed the uAgents Framework library it’s simple to get a minimal use case running.

The uAgents Framework simplifies Agents creation, and enables Agents communication, discovery, and publication on the ASI network. The Framework supports building Agents using anything from advanced Large Language Models (LLMs) to basic APIs.

Let’s start with a simple Agent that initializes and prints its name and address.

Simple Basic Agent

The agent

  1. Let’s create a Python script for this task, and name it by running:

    windows
    echo. > first_agent.py
  2. We then need to import the Agent and Context classes from the uagents library, and then create an agent using the class Agent:

    first_agent.py
    from uagents import Agent, Context agent = Agent(name="alice", seed="secret_seed_phrase", port=8000, endpoint=["http://localhost:8000/submit"])

    It is optional but useful to include a seed parameter when creating an agent to set fixed addresses. Otherwise, random addresses will be generated every time you run the agent. Your address is kind of important, as this is how other agents will identify you.

  3. Let’s define a say_hello() function for our agent to print a message periodically saying hello, my name is ...:

    first_agent.py
    @agent.on_event("startup") async def introduce_agent(ctx: Context): ctx.logger.info(f"Hello, I'm agent {agent.name} and my address is {agent.address}.") if __name__ == "__main__": agent.run()

    The .on_event("startup") decorator defines a behavior for this agent when it is run. In this case, the agent will execute the say_hello() function when the agent starts. The Context object is a collection of data and functions related to the agent. In this case, we just use the agent’s name, alice. The agent executes the function and uses the ctx.logger.info() method to print the message.

  4. Save the script.

    The overall script should look as follows:

    first_agent.py
    from uagents import Agent, Context agent = Agent(name="alice", seed="secret_seed_phrase", port=8000, endpoint=["http://localhost:8000/submit"]) @agent.on_event("startup") async def introduce_agent(ctx: Context): ctx.logger.info(f"Hello, I'm agent {agent.name} and my address is {agent.address}.") if __name__ == "__main__": agent.run()

Output

Agent logs

Make sure to have activated your virtual environment correctly.

Run the script: python first_agent.py

The output would be:

INFO: [alice]: Registration on Almanac API successful INFO: [alice]: Registering on almanac contract... INFO: [alice]: Registering on almanac contract...complete INFO: [alice]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8000&address=agent1qtu6wt5jphhmdjau0hdhc002ashzjnueqe89gvvuln8mawm3m0xrwmn9a76 INFO: [alice]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit) INFO: [alice]: Hello, I'm agent alice and my address is agent1qtu6wt5jphhmdjau0hdhc002ashzjnueqe89gvvuln8mawm3m0xrwmn9a76.

Next Steps: Extending the example using an AI Model

Let’s now expand this simple uAgent example to make something more meaningful. Let’s integrate the uAgent with different AI Models to check the different setups. We first consider ASI:One then OpenAI and how these uAgents can be defined.

ASI:One

Let’s create a simple agent that can respond to a question by using ASI:One model. Go ahead and get your own ASI:One API key as we will need this to make a call to ASI:One.

The Agent

windows
echo. > agent.py

Once you create the file, copy and paste the below code example into the agent.py file you created:

agent.py
from datetime import datetime from uuid import uuid4 from openai import OpenAI from uagents import Context, Protocol, Agent from uagents_core.contrib.protocols.chat import ( ChatAcknowledgement, ChatMessage, EndSessionContent, TextContent, chat_protocol_spec, ) ### Example Expert Assistant ## This chat example is a barebones example of how you can create a simple chat agent ## and connect to agentverse. In this example we will be prompting the ASI:One model to ## answer questions on a specific subject only. This acts as a simple placeholder for ## a more complete agentic system. # the subject that this assistant is an expert in subject_matter = "Nature" client = OpenAI( # By default, we are using the ASI:One LLM endpoint and model base_url='https://api.asi1.ai/v1', # You can get an ASI:One api key by creating an account at https://asi1.ai/dashboard/api-keys api_key='<YOUR-API-KEY>', ) agent = Agent( name="ASI-agent", seed="<your-agent-seedphrase>", port=8001, mailbox=True, publish_agent_details=True, ) # We create a new protocol which is compatible with the chat protocol spec. This ensures # compatibility between agents protocol = Protocol(spec=chat_protocol_spec) # We define the handler for the chat messages that are sent to your agent @protocol.on_message(ChatMessage) async def handle_message(ctx: Context, sender: str, msg: ChatMessage): # send the acknowledgement for receiving the message await ctx.send( sender, ChatAcknowledgement(timestamp=datetime.now(), acknowledged_msg_id=msg.msg_id), ) # collect up all the text chunks text = '' for item in msg.content: if isinstance(item, TextContent): text += item.text # query the model based on the user question response = 'I am afraid something went wrong and I am unable to answer your question at the moment' try: r = client.chat.completions.create( model="asi1", messages=[ {"role": "system", "content": f""" You are a helpful assistant who only answers questions about {subject_matter}. If the user asks about any other topics, you should politely say that you do not know about them. """}, {"role": "user", "content": text}, ], max_tokens=2048, ) response = str(r.choices[0].message.content) except: ctx.logger.exception('Error querying model') # send the response back to the user await ctx.send(sender, ChatMessage( timestamp=datetime.utcnow(), msg_id=uuid4(), content=[ # we send the contents back in the chat message TextContent(type="text", text=response), # we also signal that the session is over, this also informs the user that we are not recording any of the # previous history of messages. EndSessionContent(type="end-session"), ] )) @protocol.on_message(ChatAcknowledgement) async def handle_ack(ctx: Context, sender: str, msg: ChatAcknowledgement): # we are not interested in the acknowledgements for this example, but they can be useful to # implement read receipts, for example. pass # attach the protocol to the agent agent.include(protocol, publish_manifest=True) if __name__ == "__main__": agent.run()

You can run this with the following command: python agent.py. However, you will first to retrieve the ASI:One API key to correctly do so and provide a seed phrase for the uAgent.

At a high level, this uAgent shows a simple expert assistant built using the uAgents Framework that connects through a Mailbox to Agentverse and is discoverable also on ASI:One. The agent uses the ASI chat protocol, acknowledges incoming messages, forwards user input to the model, and responds only to questions about a specific topic before ending the session (e.g., Nature in this example). If the model query fails, the error is logged and a fallback response is sent. Handler functions registered with decorators like @protocol.on_message(ChatMessage) define how to react when a chat message is received. This enables structured, protocol-based conversations between agents, while still allowing for more flexible interactions. You can further explore this specific example by heading to chat protocol example for loosely structured communication.

If you run this agent example you should see something like the following:

Output

Agent logs

Once you correctly retrieve all the parameters needed and correctly set up your mailbox, you should be able to run your uAgent. You should see something similar in your terminal output:

INFO: [ASI-agent]: Starting agent with address: agent1qf878gaq0jzznglu22uef96rm6pxwamwj6h0pnhgm5pzgk2de235hm27tf INFO: [ASI-agent]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8001&address=agent1qf878gaq0jzznglu22uef96rm6pxwamwj6h0pnhgm5pzgk2de235hm27tf INFO: [ASI-agent]: Starting server on http://0.0.0.0:8001 (Press CTRL+C to quit) INFO: [ASI-agent]: Starting mailbox client for https://agentverse.ai INFO: [ASI-agent]: Mailbox access token acquired INFO: [uagents.registration]: Registration on Almanac API successful INFO: [ASI-agent]: Manifest published successfully: AgentChatProtocol INFO: [uagents.registration]: Registration on Almanac API successful INFO: [uagents.registration]: Registering on almanac contract... INFO: [ASI-agent]: Mailbox access token acquired

Cool! Now this Agent can easily reply to your queries. Just head over to ASI:One Chat UI and start your journey! Check out this guide for a step-by-step example on uAgents and ASI:One integration.

OpenAI

You can integrate your uAgents with any AI Model you wish. For instance, instead of ASI:One, let’s consider OpenAI now. We still want our uAgent to respond to a question by utilising openai.

First of all, go ahead and get your own openai api key as we will need this to make a call to openai.

Create a new file

windows
echo. > ai_agent.py

Agent

Copy and paste the below example into ai_agent.py file:

ai_agent.py
from pydantic import BaseModel, Field from uagents import Agent, Context, Protocol, Model from openai import OpenAI CHAT_MODEL = "gpt-4o-mini" OPENAI_API_KEY = "<YOUR-API-KEY>" agent = Agent(name="open_ai_agent", seed="<your-agent-seedphrase>", port=8000, endpoint=["http://127.0.0.1:8000/submit"] ) class AIRequest(BaseModel): question: str = Field( description="The question that the user wants to have an answer for." ) class AIResponse(BaseModel): answer: str = Field( description="The answer from AI agent to the user agent" ) PROMPT_TEMPLATE = """ Answer the following question: {question} """ @agent.on_event("startup") async def print_address(ctx: Context): ctx.logger.info(agent.address) def query_openai_chat(prompt: str): client = OpenAI( api_key=OPENAI_API_KEY, # This is the default and can be omitted ) chat_completion = client.chat.completions.create( messages=[ { "role": "system", "content": prompt, } ], model="gpt-4o", ) return (chat_completion.choices[0].message.content) @agent.on_message(model=AIRequest, replies=AIResponse) async def answer_question(ctx: Context, sender: str, msg: AIRequest): ctx.logger.info(f"Received question from {sender}: {msg.question}") prompt = PROMPT_TEMPLATE.format(question=msg.question) response = query_openai_chat(prompt) ctx.logger.info(f"Response: {response}") await ctx.send( sender, AIResponse(answer=response) ) agent.run()

Run this with python ai_agent.py. Remember to provide both the OpenAI API Key and the uAgent’s seed phrase otherwise you will not be able to run the example correctly. Once you do so successfully, you should see logs similar to the following in your terminal:

python uagents-create/ai.py INFO: [open_ai_agent]: Starting agent with address: agent1qdpzrc02a8lnlzaahtdyy3wnaux64pqa22vykp59tx67jx2mmy3dzf249jk INFO: [open_ai_agent]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)

Keep a note of the address output to log, as the client will need this address to contact this agent.

Next, let’s now create a second agent which shares messages to open_ai_agent above:

Client agent

Create a new file for client.py:

windows
echo. > client.py

And paste the following code into it:

client.py
from uagents import Agent, Context, Field, Model, Protocol from pydantic import BaseModel, Field agent = Agent(name="simple test agent", seed="your seed value alt", port=8001, endpoint=["http://127.0.0.1:8001/submit"] ) QUESTION = "Write the Javascript code to give me the sum from 1 to 10" class AIRequest(BaseModel): question: str = Field( description="The question that the user wants to have an answer for." ) class AIResponse(BaseModel): answer: str = Field( description="The answer from AI agent to the user agent" ) @agent.on_event("startup") async def ask_question(ctx: Context): ctx.logger.info( f"Asking AI agent to answer {QUESTION}" ) await ctx.send( 'THE OTHER AGENTS ADDR', AIRequest(question=QUESTION) ) @agent.on_message(model=AIResponse) async def handle_data(ctx: Context, sender: str, data: AIResponse): ctx.logger.info(f"Got response from AI agent: {data.answer}") agent.run()

There’s a lot to unpack here, and we cover the components of these agents here, here and here in more detail. However, at a high level these two agents define the AIRequest(Model) and AIResponse(Model) message objects; by defining these both agents can understand and respond to these messages. Some functions have handlers defined. Handlers @agent.on_message(model=AIRequest, replies=AIResponse) tell the uAgents library to call these functions when a message of AIRequest is received. This allows us to create very structured dialogues between two agents. However it doesn’t need to be so structured, check out the chat protocol for loosely structured communication.

If you run these agents you should see something like the following:

Output

Agent logs

python uagents-create/ai_agent.py INFO: [open_ai_agent]: Starting agent with address: agent1qdpzrc02a8lnlzaahtdyy3wnaux64pqa22vykp59tx67jx2mmy3dzf249jk INFO: [open_ai_agent]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8000&address=agent1qdpzrc02a8lnlzaahtdyy3wnaux64pqa22vykp59tx67jx2mmy3dzf249jk INFO: [open_ai_agent]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit) INFO: [open_ai_agent]: Received question from agent1qwzl46ku3r2en2m8st5y0nd4j68dahqj8n95eq5af6823mfw2h0z2yvqwpc: Write the Javascript code to give me the sum from 1 to 10 INFO:httpx:HTTP Request: POST https://api.openai.com/v1/chat/completions "HTTP/1.1 200 OK" INFO: [open_ai_agent]: Response: Certainly! You can calculate the sum of numbers from 1 to 10 in JavaScript using a loop or a mathematical formula. Here is how you can do it using a loop: ...

Client logs

python uagents-create/client.py INFO: [simple test agent]: Starting agent with address: agent1qwzl46ku3r2en2m8st5y0nd4j68dahqj8n95eq5af6823mfw2h0z2yvqwpc INFO: [simple test agent]: Asking AI agent to answer Write the Javascript code to give me the sum from 1 to 10 INFO: [simple test agent]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8001&address=agent1qwzl46ku3r2en2m8st5y0nd4j68dahqj8n95eq5af6823mfw2h0z2yvqwpc INFO: [simple test agent]: Starting server on http://0.0.0.0:8001 (Press CTRL+C to quit) INFO: [simple test agent]: Got response from AI agent: Certainly! You can calculate the sum of numbers from 1 to 10 in JavaScript using a loop or a mathematical formula. Here's how you can do it using a loop: ...

With this, you’re ready to start building greater, grander Agents. Take a look at the storage and sending tokens guides, persistent data is useful and Agents getting paid is awesome.

Last updated on