fetch-logo
ConceptsConceptsGuidesGuidesExamplesExamplesReferencesReferencesAPIsAPIs
GitHub (opens in a new tab)
  • Examples
      • Create your first agent
      • Interval task with Agents
      • Multiple agents communication
      • Local Network Interaction
      • Agents communication
      • Agents storage
      • Table booking service with Agents
      • Cleaning service with Agents
      • Send tokens with Agents
      • Verify messages with Agents
      • Communicating with other agents wallet
      • Agents communication using Agentverse Mailbox service
      • Agents Broadcast
      • Agents Name Service
      • Query an agent using a proxy API
      • Register a dice roll agent as a Function
      • Register a coin toss agent as a Function
      • Register a local agent as a Function
      • Using News API to build network of Primary and Secondary functions
      • Locally Hosted Agent with LangChain Integration
      • Hugging face API agent as a Function
      • On Query decorator example
      • Agents and Functions Creation using APIs
      • Adding Secret to agent using Agentverse API
      • React app with agents 'on_query' decorator
      • Open Dialogue Chit-Chat
      • Predefined Dialogue Chit-Chat
      • Chat API example
      • DeltaV Dialogue Chit-Chat
  • Examples
      • Create your first agent
      • Interval task with Agents
      • Multiple agents communication
      • Local Network Interaction
      • Agents communication
      • Agents storage
      • Table booking service with Agents
      • Cleaning service with Agents
      • Send tokens with Agents
      • Verify messages with Agents
      • Communicating with other agents wallet
      • Agents communication using Agentverse Mailbox service
      • Agents Broadcast
      • Agents Name Service
      • Query an agent using a proxy API
        • Introduction
      • Register a dice roll agent as a Function
      • Register a coin toss agent as a Function
      • Register a local agent as a Function
      • Using News API to build network of Primary and Secondary functions
      • Locally Hosted Agent with LangChain Integration
      • Hugging face API agent as a Function
      • On Query decorator example
      • Agents and Functions Creation using APIs
      • Adding Secret to agent using Agentverse API
      • React app with agents 'on_query' decorator
      • Open Dialogue Chit-Chat
      • Predefined Dialogue Chit-Chat
      • Chat API example
      • DeltaV Dialogue Chit-Chat
Examples
Intermediate topics
Query an agent using a proxy API

Query an agent using a proxy API

Introduction

This file can be run on any platform supporting Python, with the necessary install permissions. This example shows how to query an agent using a proxy API.

Supporting documentation

  • Creating an agent ↗️
  • Communicating with other agents ↗️
  • Register in Almanac ↗️
  • Almanac Contract ↗️
  • Protocols ↗️

The agent

agent.py
from uagents import Agent, Context, Model
 
class TestRequest(Model):
    message: str
 
class Response(Model):
    text: str
 
agent = Agent(
    name="your_agent_name_here",
    seed="your_agent_seed_here",
    port=8001,
    endpoint="http://localhost:8001/submit",
)
 
@agent.on_event("startup")
async def startup(ctx: Context):
    ctx.logger.info(f"Starting up {agent.name}")
    ctx.logger.info(f"With address: {agent.address}")
    ctx.logger.info(f"And wallet address: {agent.wallet.address()}")
 
@agent.on_query(model=TestRequest, replies={Response})
async def query_handler(ctx: Context, sender: str, _query: TestRequest):
    ctx.logger.info("Query received")
    try:
        # do something here
        await ctx.send(sender, Response(text="success"))
    except Exception:
        await ctx.send(sender, Response(text="fail"))
 
if __name__ == "__main__":
    agent.run()

The agent is created using the Agent class from uagents library. It is initialized with a name, seed, port, and endpoint. It defines an on_event handler for the "startup" event, where it logs information about the agent's initialization. It defines an on_query handler for handling queries of type TestRequest. Upon receiving a query, it processes it and sends back a Response. The agent is then set to run.

Proxy

proxy.py
import json
 
from fastapi import FastAPI
from uagents import Model
from uagents.query import query
 
AGENT_ADDRESS = "agent1qt6ehs6kqdgtrsduuzslqnrzwkrcn3z0cfvwsdj22s27kvatrxu8sy3vag0"
 
class TestRequest(Model):
    message: str
 
async def agent_query(req):
    response = await query(destination=AGENT_ADDRESS, message=req, timeout=15.0)
    data = json.loads(response.decode_payload())
    return data["text"]
 
app = FastAPI()
 
@app.get("/")
def read_root():
    return "Hello from the Agent controller"
 
@app.post("/endpoint")
async def make_agent_call(req: TestRequest):
    try:
        res = await agent_query(req)
        return f"successful call - agent response: {res}"
    except Exception:
        return "unsuccessful agent call"

The proxy is implemented using FastAPI. It sets up two routes: "/" for a simple root message and "/endpoint" for receiving requests. When a POST request is made to "/endpoint" with a JSON payload containing a TestRequest, it triggers the make_agent_call function. Inside make_agent_call, it calls agent_query to communicate with the agent. The agent receives the query, processes it, and sends back a response. The proxy receives the response from the agent and sends back a success message along with the response text.

Run the example

In separate terminals:

  1. Run the FastAPI proxy: uvicorn proxy:app

  2. Run the agent: python agent.py

  3. Query the agent via the proxy: curl -d '{"message": "test"}' -H "Content-Type: application/json" -X POST http://localhost:8000/endpoint

Was this page helpful?

Agents Name ServiceRegister a dice roll agent as a Function
footer-logo

Main website

Integrations

Events

We’re hiring!

Twitter (opens in a new tab)Telegram (opens in a new tab)Discord (opens in a new tab)GitHub (opens in a new tab)Youtube (opens in a new tab)LinkedIn (opens in a new tab)Reddit (opens in a new tab)
Sign up for developer updates