1"use strict";(self.webpackChunkinnovation_labs=self.webpackChunkinnovation_labs||[]).push([[3045],{23196:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>g,contentTitle:()=>r,default:()=>c,frontMatter:()=>o,metadata:()=>a,toc:()=>d});const a=JSON.parse('{"id":"agent-communication/sdk-uagent-communication","title":"AI Agent to uAgent Communication","description":"This guide demonstrates how to enable communication between a Microservice Agent created using the uagents framework and an AI Agent created using the Fetch.ai SDK.","source":"@site/versioned_docs/version-1.0.3/agent-communication/sdk-uagent-communication.md","sourceDirName":"agent-communication","slug":"/agent-communication/sdk-uagent-communication","permalink":"/resources/docs/1.0.3/agent-communication/sdk-uagent-communication","draft":false,"unlisted":false,"tags":[],"version":"1.0.3","frontMatter":{"id":"sdk-uagent-communication","title":"AI Agent to uAgent Communication"},"sidebar":"tutorialSidebar","previous":{"title":"AI Agent to AI Agent Communication","permalink":"/resources/docs/1.0.3/agent-communication/sdk-sdk-communication"},"next":{"title":"Agent Chat Protocol","permalink":"/resources/docs/1.0.3/agent-communication/agent-chat-protocol"}}');var s=t(74848),i=t(28453);const o={id:"sdk-uagent-communication",title:"AI Agent to uAgent Communication"},r="uAgent \u2194 AI Agent Communication Using Fetch.ai SDK and uAgents",g={},d=[{value:"uAgent Script (uagent.py)",id:"uagent-script-uagentpy",level:3},{value:"Explanation",id:"explanation",level:3},{value:"Setting Up the AI Agent",id:"setting-up-the-ai-agent",level:2},{value:"AI Agent Script (ai_agent.py)",id:"ai-agent-script-ai_agentpy",level:3},{value:"Explanation",id:"explanation-1",level:3},{value:"Environment Variables",id:"environment-variables",level:2},{value:"Testing the Communication",id:"testing-the-communication",level:2},{value:"Step 1: Running the uAgent",id:"step-1-running-the-uagent",level:3},{value:"uAgent Logs",id:"uagent-logs",level:4},{value:"Copy the uAgent Address",id:"copy-the-uagent-address",level:4},{value:"Step 2: Running the AI Agent",id:"step-2-running-the-ai-agent",level:3},{value:"AI Agent Logs",id:"ai-agent-logs",level:4},{value:"Step 3: Sending a message from Agent2 to Agent1",id:"step-3-sending-a-message-from-agent2-to-agent1",level:3},{value:"Expected Logs on the uAgent Terminal",id:"expected-logs-on-the-uagent-terminal",level:4},{value:"Expected Logs on the AI Agent Terminal",id:"expected-logs-on-the-ai-agent-terminal",level:4},{value:"Explanation of Communication Flow",id:"explanation-of-communication-flow",level:2},{value:"Key Takeaways",id:"key-takeaways",level:2}];function l(e){const n={a:"a",code:"code",h1:"h1",h2:"h2",h3:"h3",h4:"h4",header:"header",li:"li",p:"p",pre:"pre",strong:"strong",ul:"ul",...(0,i.R)(),...e.components};return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(n.header,{children:(0,s.jsx)(n.h1,{id:"uagent--ai-agent-communication-using-fetchai-sdk-and-uagents",children:"uAgent \u2194 AI Agent Communication Using Fetch.ai SDK and uAgents"})}),"\n",(0,s.jsx)(n.p,{children:"This guide demonstrates how to enable communication between a Microservice Agent created using the uagents framework and an AI Agent created using the Fetch.ai SDK."}),"\n",(0,s.jsx)(n.h3,{id:"uagent-script-uagentpy",children:"uAgent Script (uagent.py)"}),"\n",(0,s.jsxs)(n.p,{children:["Please remember to have the ",(0,s.jsx)(n.strong,{children:"uagents"})," and the ",(0,s.jsx)(n.strong,{children:"fetchai"})," package installed in the terminal in order to create and run the agents."]}),"\n",(0,s.jsx)(n.p,{children:"This uAgent will receive a message from the AI Agent and send a response back."}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{className:"language-py",metastring:"title='uagent.py'",children:'from uagents import Agent, Context, Model\n\n# Define the request model the uAgent will handle\nclass Request(Model):\n message: str\n\n# Define the response model the uAgent will send back\nclass Response(Model):\n response: str\n\n# Initialize the uAgent\nuagent = Agent(\n name="Sample uAgent",\n port=8000,\n endpoint=["http://localhost:8000/submit"]\n)\n\n# Handle incoming messages with the Request model\[email protected]_message(model=Request)\nasync def message_handler(ctx: Context, sender: str, msg: Request):\n ctx.logger.info(f"Received message from {sender}: {msg.message}")\n\n # Generate a response message\n response = Response(response=f\'Hello, AI Agent! I received your message:{msg.message}\')\n \n # Send the response back to the AI Agent\n await ctx.send(sender, response)\n\nif __name__ == "__main__":\n uagent.run()\n'})}),"\n",(0,s.jsx)(n.h3,{id:"explanation",children:"Explanation"}),"\n",(0,s.jsxs)(n.ul,{children:["\n",(0,s.jsxs)(n.li,{children:[(0,s.jsx)(n.strong,{children:"Agent Initialization"}),": The uAgent listens on port 8000 for incoming messages."]}),"\n",(0,s.jsxs)(n.li,{children:[(0,s.jsx)(n.strong,{children:"Message Handling"}),": When a message matching the ",(0,s.jsx)(n.code,{children:"Request"})," model is received, the agent logs it and responds with a predefined message using the ",(0,s.jsx)(n.code,{children:"Response"})," model."]}),"\n"]}),"\n",(0,s.jsx)(n.h2,{id:"setting-up-the-ai-agent",children:"Setting Up the AI Agent"}),"\n",(0,s.jsx)(n.p,{children:"The AI Agent will send messages to the uAgent and handle the response received from the uAgent."}),"\n",(0,s.jsx)(n.h3,{id:"ai-agent-script-ai_agentpy",children:"AI Agent Script (ai_agent.py)"}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{className:"language-py",metastring:"title='ai_agent.py'",children:'import os\nfrom flask import Flask, request, jsonify\nfrom flask_cors import CORS\nfrom uagents_core.crypto import Identity\nfrom fetchai.communication import send_message_to_agent, parse_message_from_agent\nimport logging\nfrom dotenv import load_dotenv\n\n# Configure logging\nlogging.basicConfig(level=logging.INFO, format=\'%(asctime)s - %(name)s - %(levelname)s - %(message)s\')\nlogger = logging.getLogger(__name__)\n\n# Initialize Flask app\napp = Flask(__name__)\nCORS(app)\n\nclient_identity = None\nagent_response = None\n\nclass Request
1(Model):\n message: str\n\n# Load environment variables from .env file\nload_dotenv()\n\ndef init_client():\n """Initialize and register the client agent."""\n global client_identity\n try:\n # Load the client identity from environment variables\n client_identity = Identity.from_seed("Sample AI AGENT SEED PHRASE for communication", 0)\n logger.info(f"Client agent started with address: {client_identity.address}")\n\n readme = """\n \n domain:domain-of-your-agent\n\n <description>This Agent can send a message to a uAgent and receive a message from a uAgent in string format.</description>\n <use_cases>\n <use_case>Send and receive messages with another uAgent.</use_case>\n </use_cases>\n <payload_requirements>\n <description>This agent can only send and receive messages in text format.</description>\n <payload>\n <requirement>\n <parameter>message</parameter>\n <description>The agent sends and receives messages in text format.</description>\n </requirement>\n </payload>\n </payload_requirements>\n """\n\n # Register the agent with Agentverse\n register_with_agentverse(\n identity=client_identity,\n url="http://localhost:5002/api/webhook",\n agentverse_token = os.getenv("AGENTVERSE_API_KEY"),\n agent_title="Sample AI Agent communication"\n readme=readme\n )\n\n logger.info("Client agent registration complete!")\n\n except Exception as e:\n logger.error(f"Initialization error: {e}")\n raise\n\n\[email protected](\'/request\', methods=[\'POST\'])\ndef send_data():\n """Send payload to the selected agent based on provided address."""\n global agent_response\n agent_response = None\n\n try:\n # Parse the request payload\n data = request.json\n payload = data.get(\'payload\') # Extract the payload dictionary\n\n uagent_address = "agent1qgd54rrq8ex4uhdxe6qg0sklz7h7dkacdk9rz4ec0l304wghw88sg35rfk6" #run the uagent.py copy the address and paste here\n \n # Build the Data Model digest for the Request model to ensure message format consistency between the uAgent and AI Agent\n model_digest = Model.build_schema_digest(Request)\n\n # Send the payload to the specified agent\n send_message_to_agent(\n client_identity, # Frontend client identity\n uagent_address, # Agent address where we have to send the data\n payload, # Payload containing the data\n model_digest=model_digest\n )\n\n return jsonify({"status": "request_sent", "payload": payload})\n\n except Exception as e:\n logger.error(f"Error sending data to agent: {e}")\n return jsonify({"error": str(e)}), 500\n\n\n\n# app route to get recieve the messages on the agent\[email protected](\'/api/webhook\', methods=[\'POST\'])\ndef webhook():\n """Handle incoming messages from the dashboard agent."""\n global agent_response\n try:\n # Parse the incoming webhook message\n data = request.get_data().decode("utf-8")\n logger.info("Received response")\n message = parse_message_from_agent(data)\n agent_response = message.payload\n logger.info(f"Processed response: {agent_response}")\n return jsonify({"status": "success"})\n except Exception as e:\n logger.error(f"Error in webhook: {e}")\n return jsonify({"error": str(e)}), 500\n\nif __name__ == "__main__":\n load_dotenv()\n init_client()\n app.run(host="0.0.0.0", port=5002)\n'})}),"\n",(0,s.jsx)(n.h3,{id:"explanation-1",children:"Explanation"}),"\n",(0,s.jsxs)(n.ul,{children:["\n",(0,s.jsxs)(n.li,{children:[(0,s.jsx)(n.strong,{children:"Data Model"}),": The Request and Response models define the structure of messages exchanged between the AI Agent and the uAgent. A correctly defined data model is essential for sending a message to the uAgent from an SDK-based AI Agent."]}),"\n",(0,s.jsxs)(n.li,{children:[(0,s.jsx)(n.strong,{children:"Schema Validation"}),": The model digest ensures that messages conform to the expected schema before transmission, preventing format mismatches."]}),"\n",(0,s.jsxs)(n.li,{children:[(0,s.jsx)(n.strong,{children:"Sending Data"}),": The AI Agent sends a message to the uAgent using the /request endpoint."]}),"\n",(0,s.jsxs)(n.li,{children:[(0,s.jsx)(n.strong,{children:"Handling Response"}),": The AI Agent listens for responses using the /api/webhook endpoint."]}),"\n"]}),"\n",(0,s.jsx)(n.h2,{id:"environment-variables",children:"Environment Variables"}),"\n",(0,s.jsx)(n.p,{children:"Create a .env file and add the following environment variables:"}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{className:"language-bash",children:'AGENTVERSE_API_KEY="YOUR_AGENTVERSE_API_KEY"\nAGENT_SECRET_KEY="YOUR_SECRET_KEY_FOR_AI_AGENT"\n'})}),"\n",(0,s.jsxs)(n.p,{children:["Replace the placeholders with your actual API keys and agent secrets. Refer to this ",(0,s.jsx)(n.a,{href:"../agentverse/agentverse-api-key",children:"guide"})," to get your Agentverse API Key."]}),"\n",(0,s.jsx)(n.h2,{id:"testing-the-communication",children:"Testing the Communication"}),"\n",(0,s.jsx)(n.h3,{id:"step-1-running-the-uagent",children:"Step 1: Running the uAgent"}),"\n",(0,s.jsx)(n.p,{children:"Start the uAgent by running the following command in your terminal:"}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{className:"language-bash",children:"python uagent.py\n"})}),"\n",(0,s.jsx)(n.h4,{id:"uagent-logs",children:"uAgent Logs"}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{className:"language-bash",children:"(venv) abhi@Fetchs-MacBook-Pro ILAgents % python3 uagent.py\nINFO: [Sample uAgent]: Starting agent with address: agent1qgd54rrq8ex4uhdxe6qg0sklz7h7dkacdk9rz4ec0l304wghw88sg35rfk6\nINFO: [Sample uAgent]: My name is Sample uAgent and my address is agent1qgd54rrq8ex4uhdxe6qg0sklz7h7dkacdk9rz4ec0l304wghw88sg35rfk6\nINFO: [Sample uAgent]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8000&address=agent1qgd54rrq8ex4uhdxe6qg0sklz7h7dkacdk9rz4ec0l304wghw88sg35rfk6\nINFO: [Sample uAgent]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)\nINFO: [uagents.registration]: Registration on Almanac API successful\nINFO: [uagents.registration]: Registering on almanac contract...\nINFO: [uagents.registration]: Registering on almanac contract...complete\n"})}),"\n",(0,s.jsx)(n.h4,{id:"copy-the-uagent-address",children:"Copy the uAgent Address"}),"\n",(0,s.jsx)(n.p,{children:"Look for the uAgent address in the logs, which appears in this format:"}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{className:"language-bash",children:"agent1qgd54rrq8ex4uhdxe6qg0sklz7h7dkacdk9rz4ec0l304wghw88sg35rfk6\n"})}),"\n",(0,s.jsx)(n.p,{children:"Copy this uAgent address and paste it into the AI Agent script at the following line:"}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{className:"language-bash",children:'uagent_address="PASTE YOUR UAGENT ADDRESS HERE"\n'})}),"\n",(0,s.jsx)(n.h3,{id:"step-2-running-the-ai-agent",children:"Step 2: Running the AI Agent"}),"\n",(0,s.jsx)(n.p,{children:"Start the AI Agent by running the following command in your terminal:"}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{className:"language-bash",children:"python ai_agent.py\n"})}),"\n",(0,s.jsx)(n.h4,{id:"ai-agent-logs",children:"AI Agent Logs"}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{className:"language-bash",children:"(venv) abhi@Fetchs-MacBook-Pro ILAgents % python3 ai_agent.py\nINFO:__main__:Client agent started with address: agent1qw7u5sw63a88kmcn5j5kxf7q326u5hgmppvy2vpxlh3re6y0yp8253ec7xl\nINFO:fetchai:Registering with Almanac API\nINFO:fetchai:Completed registering agent with Agentverse\nINFO:__main__:Client agent registration complete!\n * Serving Flask app 'ai_agent'\n * Debug mode: off\nINFO:werkzeug:WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.\n * Running on all addresses (0.0.0.0)\n * Running on http://127.0.0.1:5002\n * Running on http://172.20.10.2:5002\nINFO:werkzeug:Press CTRL+C to quit\n\n"})}),"\n",(0,s.jsx)(n.h3,{id:"step-3-sending-a-message-from-agent2-to-agent1",children:"Step 3: Sending a message from Agent2 to Agent1"}),"\n",(0,s.jsx)(n.p,{children:"We will use the following curl command to send a message from the AI Agent to the uAgent:"}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{className:"language-bash",children:'curl -X POST http://localhost:5002/request \\\n-H "Content-Type: application/json" \\\n-d \'{\n "payload": {"message": "Hello uAgent!"}\n}\'\n'})}),"\n",(0,s.jsx)(n.h4,{id:"expected-logs-on-the-uagent-terminal",children:"Expected Logs on the uAgent Terminal"}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{className:"language-bash",children:"(venv) abhi@Fetchs-MacBook-Pro ILAgents % python3 uagent.py\nINFO: [Sample uAgent]: Starting agent with address: agent1qgd54rrq8ex4uhdxe6qg0sklz7h7dkacdk9rz4ec0l304wghw88sg35rfk6\nINFO: [Sample uAgent]: My name is Sample uAgent and my address is agent1qgd54rrq8ex4uhdxe6qg0sklz7h7dkacdk9rz4ec0l304wghw88sg35rfk6\nINFO: [Sample uAgent]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8000&address=agent1qgd54rrq8ex4uhdxe6qg0sklz7h7dkacdk9rz4ec0l304wghw88sg35rfk6\nINFO: [Sample uAgent]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)\nINFO: [uagents.registration]: Registration on Almanac API successful\nINFO: [uagents.registration]: Registering on almanac contract...\nINFO: [uagents.registration]: Registering on almanac contract...complete\nINFO: [Sample uAgent]: Received message from agent1qw7u5sw63a88kmcn5j5kxf7q326u5hgmppvy2vpxlh3re6y0yp8253ec7xl: Hello uAgent!\n"})}),"\n",(0,s.jsx)(n.h4,{id:"expected-logs-on-the-ai-agent-terminal",children:"Expected Logs on the AI Agent Terminal"}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{className:"language-bash",children:'(venv) abhi@Fetchs-MacBook-Pro ILAgents % python3 ai_agent.py\nINFO:__main__:Client agent started with address: agent1qw7u5sw63a88kmcn5j5kxf7q326u5hgmppvy2vpxlh3re6y0yp8253ec7xl\nINFO:fetchai:Registering with Almanac API\nINFO:fetchai:Completed registering agent with Agentverse\nINFO:__main__:Client agent registration complete!\n * Serving Flask app \'ai_agent\'\n * Debug mode: off\nINFO:werkzeug:WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.\n * Running on all addresses (0.0.0.0)\n * Running on http://127.0.0.1:5002\n * Running on http://172.20.10.2:5002\nINFO:werkzeug:Press CTRL+C to quit\n{"version":1,"sender":"agent1qw7u5sw63a88kmcn5j5kxf7q326u5hgmppvy2vpxlh3re6y0yp8253ec7xl","target":"agent1qgd54rrq8ex4uhdxe6qg0sklz7h7dkacdk9rz4ec0l304wghw88sg35rfk6","session":"c28d03fd-ad42-4c09-80b8-2bb8df9d7c3e","schema_digest":"model:14d760ab9a6127711e530c0f1bd84d5caa48c6bc6566ca489581d6918e6dff85","protocol_digest":"proto:a03398ea81d7aaaf67e72940937676eae0d019f8e1d8b5efbadfef9fd2e98bb2","payload":"eyJtZXNzYWdlIjoiaGV5In0=","expires":null,"nonce":null,"signature":"sig14ukfdrc98924wvx66xa2c32pk2wqyn69cepkvcpwahlygv3tc2t8hrzfkuzc9earscpnasdt8txpu99cyw24gmyspfdhqkxsn7a3lnq60mpaq"}\nINFO:fetchai:Got response looking up agent endpoint\nhttp://localhost:8000/submit\nINFO:fetchai:Sent message to agent\nINFO:werkzeug:127.0.0.1 - - [30/Jan/2025 14:21:58] "POST /request HTTP/1.1" 200 -\nINFO:__main__:Received response\nINFO:__main__:Processed response: {\'response\': \'Hello, AI Agent! I received your message: Hello uAgent!\'}\nINFO:werkzeug:127.0.0.1 - - [30/Jan/2025 14:21:58] "POST /api/webhook HTTP/1.1" 200 -\n'})}),"\n",(0,s.jsx)(n.h2,{id:"explanation-of-communication-flow",children:"Explanation of Communication Flow"}),"\n",(0,s.jsxs)(n.ul,{children:["\n",(0,s.jsxs)(n.li,{children:["The AI Agent sends a message using the ",(0,s.jsx)(n.strong,{children:"send_message_to_agent"})," function."]}),"\n",(0,s.jsxs)(n.li,{children:["The uAgent receives the message via the ",(0,s.jsx)(n.strong,{children:"@uagent.on_message"})," handler."]}),"\n",(0,s.jsxs)(n.li,{children:["The uAgent processes the message and responds using ",(0,s.jsx)(n.strong,{children:"await ctx.send()"}),"."]}),"\n",(0,s.jsxs)(n.li,{children:["The AI Agent receives the response through the ",(0,s.jsx)(n.strong,{children:"/api/webhook"})," endpoint."]}),"\n"]}),"\n",(0,s.jsx)(n.h2,{id:"key-takeaways",children:"Key Takeaways"}),"\n",(0,s.jsxs)(n.ul,{children:["\n",(0,s.jsxs)(n.li,{children:["The ",(0,s.jsx)(n.strong,{children:"uAgent"})," handles structured messages using Fetch.ai\u2019s uAgents framework."]}),"\n",(0,s.jsxs)(n.li,{children:["The ",(0,s.jsx)(n.strong,{children:"AI Agent"})," utilizes Fetch.ai\u2019s SDK for message transmission and parsing."]}),"\n",(0,s.jsx)(n.li,{children:"Communication between the two agents follows a request-response pattern using their respective handlers."}),"\n"]}),"\n",(0,s.jsx)(n.p,{children:"This setup can be extended to build more complex agent interactions involving dynamic data exchange, service orchestration, and autonomous decision-making."})]})}function c(e={}){const{wrapper:n}={...(0,i.R)(),...e.components};return n?(0,s.jsx)(n,{...e,children:(0,s.jsx)(l,{...e})}):l(e)}},28453:(e,n,t)=>{t.d(n,{R:()=>o,x:()=>r});var a=t(96540);const s={},i=a.createContext(s);function o(e){const n=a.useContext(i);return a.useMemo((function(){return"function"==typeof e?e(n):{...n,...e}}),[n,e])}function r(e){let n;return n=e.disableParentContext?"function"==typeof e.components?e.components(s):e.components||s:o(e.components),a.createElement(i.Provider,{value:n},e.children)}}}]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.