1"use strict";(self.webpackChunkinnovation_labs=self.webpackChunkinnovation_labs||[]).push([[414],{12676:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>o,contentTitle:()=>l,default:()=>g,frontMatter:()=>r,metadata:()=>s,toc:()=>c});const s=JSON.parse('{"id":"agentverse/agentverse-based-application","title":"AI Agent - End to End Application with Agentverse Architecture","description":"This diagram depicts an agent-based architecture, where the Client Application interacts with a","source":"@site/versioned_docs/version-1.0.0/agentverse/agentverse-based-application.mdx","sourceDirName":"agentverse","slug":"/agentverse/agentverse-based-application","permalink":"/resources/docs/1.0.0/agentverse/agentverse-based-application","draft":false,"unlisted":false,"tags":[],"version":"1.0.0","frontMatter":{"id":"agentverse-based-application","title":"AI Agent - End to End Application with Agentverse Architecture"},"sidebar":"tutorialSidebar","previous":{"title":"Search Agent and MicroServices","permalink":"/resources/docs/1.0.0/agentverse/searching"},"next":{"title":"Langchain Agent","permalink":"/resources/docs/1.0.0/other-frameworks/langchain"}}');var i=t(74848),a=t(28453);const r={id:"agentverse-based-application",title:"AI Agent - End to End Application with Agentverse Architecture"},l=void 0,o={},c=[{value:"Client Application",id:"client-application",level:2},{value:"AgentVerse",id:"agentverse",level:2},{value:"Prime Agent",id:"prime-agent",level:2},{value:"Agent",id:"agent",level:2},{value:"System Components",id:"system-components",level:2},{value:"React Frontend (Client Application)",id:"react-frontend-client-application",level:3},{value:"Primary Agent (Query Router)",id:"primary-agent-query-router",level:3},{value:"Financial Analysis Agent",id:"financial-analysis-agent",level:3},{value:"Agentverse Integration",id:"agentverse-integration",level:3},{value:"Communication Flow",id:"communication-flow",level:3},{value:"Key Implementation Details",id:"key-implementation-details",level:2},{value:"Frontend",id:"frontend",level:3},{value:"Primary Agent",id:"primary-agent",level:3},{value:"Financial Agent",id:"financial-agent",level:3},{value:"Detailed Implementation Details",id:"detailed-implementation-details",level:2},{value:"Frontend Implementation (React)",id:"frontend-implementation-react",level:3},{value:"Message Handling and UI State",id:"message-handling-and-ui-state",level:4},{value:"Response Polling System",id:"response-polling-system",level:4},{value:"Primary Agent Implementation",id:"primary-agent-implementation",level:3},{value:"Agent Setup and Initialization",id:"agent-setup-and-initialization",level:4},{value:"Financial Agent Discovery and Communication",id:"financial-agent-discovery-and-communication",level:4},{value:"Response Management",id:"response-management",level:4},{value:"Financial Analysis Agent Implementation",id:"financial-analysis-agent-implementation",level:3},{value:"Agent Registration and Setup",id:"agent-registration-and-setup",level:4},{value:"Query Processing and Response",id:"query-processing-and-response",level:4}];function d(e){const n={code:"code",h2:"h2",h3:"h3",h4:"h4",li:"li",ol:"ol",p:"p",pre:"pre",ul:"ul",...(0,a.R)(),...e.components};return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(n.p,{children:"This diagram depicts an agent-based architecture, where the Client Application interacts with a\nPrime Agent to discover and utilize various specialized Agents registered within the AgentVerse.\nThe Prime Agent orchestrates the communication between the Client and the Agents to fulfill\nthe client's requests."}),"\n",(0,i.jsx)(n.h2,{id:"client-application",children:"Client Application"}),"\n",(0,i.jsx)(n.p,{children:"The client application can perform searches on the AgentVerse and send requests to the\nPrime Agent."}),"\n",(0,i.jsx)(n.h2,{id:"agentverse",children:"AgentVerse"}),"\n",(0,i.jsx)(n.p,{children:"The AgentVerse is responsible for agent discovery and registration. It maintains an Agent Registry."}),"\n",(0,i.jsx)(n.h2,{id:"prime-agent",children:"Prime Agent"}),"\n",(0,i.jsx)(n.p,{children:"The Prime Agent is the entry point for the client application.\nIt can search the AgentVerse's registry, communicate with the AgentVerse for discovery, send requests to the Agent, and return the response to the client."}),"\n",(0,i.jsx)(n.h2,{id:"agent",children:"Agent"}),"\n",(0,i.jsx)(n.p,{children:"The Agent represents a specific agent code that is registered with the AgentVerse. It can respond to requests from the Prime Agent."}),"\n",(0,i.jsx)(n.p,{children:"The flow of the system is as follows:"}),"\n",(0,i.jsxs)(n.ol,{children:["\n",(0,i.jsx)(n.li,{children:"The client application searches the AgentVerse to discover available agents."}),"\n",(0,i.jsx)(n.li,{children:"The client application sends a request to the Prime Agent."}),"\n",(0,i.jsx)(n.li,{children:"The Prime Agent communicates with the AgentVerse to find the appropriate Agent."}),"\n",(0,i.jsx)(n.li,{children:"The Prime Agent sends the request to the Agent."}),"\n",(0,i.jsx)(n.li,{children:"The Agent processes the request and sends the response back to the Prime Agent."}),"\n",(0,i.jsx)(n.li,{children:"The Prime Agent returns the final response to the client application."}),"\n"]}),"\n",(0,i.jsx)(n.p,{children:"This architecture allows for a modular and extensible system, where new agents can be easily\nintegrated, and the Prime Agent can orchestrate the interactions between agents to fulfill\ncomplex client requests."}),"\n",(0,i.jsx)("div",{style:{textAlign:"center"},children:(0,i.jsx)("img",{src:"/resources/img/architecture.png",alt:"tech-architecture",style:{width:"75%",maxWidth:"600px"}})}),"\n",(0,i.jsx)(n.h2,{id:"system-components",children:"System Components"}),"\n",(0,i.jsx)(n.h3,{id:"react-frontend-client-application",children:"React Frontend (Client Application)"}),"\n",(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsx)(n.li,{children:"React-based user interface (OptimusPrime component)"}),"\n",(0,i.jsxs)(n.li,{children:["Two main API endpoints:","\n",(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsx)(n.li,{children:"/api/send-request: Sends analysis queries"}),"\n",(0,i.jsx)(n.li,{children:"/api/get-response: Polls for results"}),"\n"]}),"\n"]}),"\n",(0,i.jsx)(n.li,{children:"Handles message display and user interactions"}),"\n"]}),"\n",(0,i.jsx)(n.h3,{id:"primary-agent-query-router",children:"Primary Agent (Query Router)"}),"\n",(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsx)(n.li,{children:"Port: 5001"}),"\n",(0,i.jsx)(n.li,{children:"Role: Routes queries to Financial Analysis Agent"}),"\n",(0,i.jsxs)(n.li,{children:["Key Functions:","\n",(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsx)(n.li,{children:"Discovers Financial Analysis Agent through Agentverse"}),"\n",(0,i.jsx)(n.li,{children:"Forwards user queries"}),"\n",(0,i.jsx)(n.li,{children:"Manages response polling"}),"\n"]}),"\n"]}),"\n",(0,i.jsxs)(n.li,{children:["Endpoints:","\n",(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsxs)(n.li,{children:["\n",(0,i.jsx)(n.p,{children:"/webhook: Receives responses from Financial Agent"}),"\n"]}),"\n"]}),"\n"]}),"\n"]}),"\n",(0,i.jsx)(n.h3,{id:"financial-analysis-agent",children:"Financial Analysis Agent"}),"\n",(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsx)(n.li,{children:"Port: 5008"}),"\n",(0,i.jsx)(n.li,{children:"Role: Processes financial analysis requests"}),"\n",(0,i.jsxs)(n.li,{children:["Components:","\n",(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsx)(n.li,{children:"Supervisor Agent: Coordinates analysis"}),"\n",(0,i.jsx)(n.li,{children:"Search Agent: Handles market research"}),"\n",(0,i.jsx)(n.li,{children:"SEC Analyst: Processes SEC filings"}),"\n"]}),"\n"]}),"\n",(0,i.jsxs)(n.li,{children:["Tools:","\n",(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsx)(n.li,{children:"RAG System for document analysis"}),"\n",(0,i.jsx)(n.li,{children:"Tavily Search for market data"}),"\n"]}),"\n"]}),"\n"]}),"\n",(0,i.jsx)(n.h3,{id:"agentverse-integration",children:"Agentverse Integration"}),"\n",(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsx)(n.li,{children:"Agent Discovery: Allows finding agents by capability"}),"\n",(0,i.jsx)(n.li,{children:"Agent Registry: Manages agent registration and lookup"}),"\n",(0,i.jsx)(n.li,{children:"Message Routing: Handles inter-agent communication"}),"\n"]}),"\n",(0,i.jsx)(n.h3,{id:"communication-flow",children:"Communication Flow"}),"\n",(0,i.jsxs)(n.ol,{children:["\n",(0,i.jsx)(n.li,{children:"User submits query through React UI"}),"\n",(0,i.jsx)(n.li,{children:"Primary Agent searches for Financial Analysis Agent"}),"\n",(0,i.jsx)(n.li,{children:"Primary Agent forwards query to Financial Agent"}),"\n",(0,i.jsx)(n.li,{children:"Financial Agent processes query using specialist team"}),"\n",(0,i.jsx)(n.li,{children:"Response returns through Agentverse to Primary Agent"}),"\n",(0,i.jsx)(n.li,{children:"Frontend polls Primary Agent for results"}),"\n",(0,i.jsx)(n.li,{children:"Results displayed to user"}),"\n"]}
1),"\n",(0,i.jsx)(n.h2,{id:"key-implementation-details",children:"Key Implementation Details"}),"\n",(0,i.jsx)(n.h3,{id:"frontend",children:"Frontend"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-python",children:"// Sends request and starts polling\nconst handleSendMessage = async () => {\n await fetch('/api/send-request', {...});\n startPolling(); // Begin checking for response\n};\n"})}),"\n",(0,i.jsx)(n.h3,{id:"primary-agent",children:"Primary Agent"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-python",children:"# Agent discovery and routing\ndef find_financial_agent():\n available_ais = fetch.ai(\"Financial Analysis Agent\")\n return available_ais.get('ais', [0])\n\[email protected]('/webhook', methods=['POST'])\ndef webhook():\n message = parse_message_from_agent(data)\n primary_agent.latest_response = message.payload\n"})}),"\n",(0,i.jsx)(n.h3,{id:"financial-agent",children:"Financial Agent"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-python",children:'# Agent registration\nregister_with_agentverse(\n identity=financial_identity,\n url="http://localhost:5008/webhook",\n agent_title="Financial Analysis Agent",\n readme="..." # Capabilities description\n)\n'})}),"\n",(0,i.jsx)(n.h2,{id:"detailed-implementation-details",children:"Detailed Implementation Details"}),"\n",(0,i.jsx)(n.h3,{id:"frontend-implementation-react",children:"Frontend Implementation (React)"}),"\n",(0,i.jsx)(n.h4,{id:"message-handling-and-ui-state",children:"Message Handling and UI State"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-python",children:"const OptimusPrime = () => {\n const [messages, setMessages] = useState([]);\n const [inputText, setInputText] = useState('');\n const [isProcessing, setIsProcessing] = useState(false);\n // Handles submitting new messages\n const handleSendMessage = async () => {\n if (!inputText.trim() || isProcessing) return;\n // Add user message to UI\n const userMessage = {\n type: 'user',\n content: inputText,\n timestamp: new Date().toLocaleTimeString()\n };\n setMessages(prev => [...prev, userMessage]);\n setInputText('');\n setIsProcessing(true);\n try {\n // Send request to primary agent\n await fetch('/api/send-request', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ input: inputText }),\n });\n // Start polling for response\n startPollingForResponse();\n } catch (error) {\n handleError(error);\n }\n};\n"})}),"\n",(0,i.jsx)(n.h4,{id:"response-polling-system",children:"Response Polling System"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-python",children:"// Polls for agent response\nconst startPollingForResponse = () => {\n const pollInterval = setInterval(async () => {\n try {\n const responseData = await fetch('/api/get-response');\n const data = await responseData.json();\n\n if (data.status !== 'waiting' && data.analysis_result) {\n clearInterval(pollInterval);\n setIsProcessing(false);\n // Process agent responses\n data.analysis_result.analysis.forEach(response => {\n setMessages(prev => [...prev, {\n type: 'agent',\n agentName: response.name || 'Agent',\n content: response.content,\n timestamp: new Date().toLocaleTimeString()\n }]);\n });\n }\n } catch (error) {\n clearInterval(pollInterval);\n setIsProcessing(false);\n handleError(error);\n }\n }, 1000);\n};\n"})}),"\n",(0,i.jsx)(n.h3,{id:"primary-agent-implementation",children:"Primary Agent Implementation"}),"\n",(0,i.jsx)(n.h4,{id:"agent-setup-and-initialization",children:"Agent Setup and Initialization"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-python",children:'class PrimaryAgent:\n def __init__(self):\n self.identity = None\n self.latest_response = None\n\n def initialize(self):\n try:\n # Initialize agent identity\n self.identity = Identity.from_seed(\n os.getenv("PRIMARY_AGENT_KEY"),\n 0\n )\n\n # Register with Agentverse\n register_with_agentverse(\n identity=self.identity,\n url="http://localhost:5001/webhook",\n agentverse_token=os.getenv("AGENTVERSE_API_KEY"),\n agent_title="Financial Query Router",\n readme="<description>Routes queries to Financial Analysis Agent</description>"\n )\n except Exception as e:\n logger.error(f"Initialization error: {e}")\n raise\n'})}),"\n",(0,i.jsx)(n.h4,{id:"financial-agent-discovery-and-communication",children:"Financial Agent Discovery and Communication"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-python",children:'def find_financial_agent(self):\n """Find registered financial analysis agent"""\n try:\n # Search for financial agent in Agentverse\n available_ais = fetch.ai("Financial Analysis Agent")\n agents = available_ais.get(\'ais\', [])\n [\'address\']}")\n if agents:\n logger.info(f"Found financial agent at address: {agents[0] [\'address\']}")\n return agents[0]\n return None\n\n except Exception as e:\n logger.error(f"Error finding financial agent: {e}")\n return None\n\[email protected](\'/api/send-request\', methods=[\'POST\'])\ndef send_request():\n try:\n # Extract user query\n data = request.json\n user_input = data.get(\'input\')\n # Find and validate financial agent\n agent = primary_agent.find_financial_agent()\n if not agent:\n return jsonify({"error": "Financial analysis agent not available"}), 404\n # Forward request to financial agent\n send_message_to_agent(\n primary_agent.identity,\n agent[\'address\'],\n {"request": user_input}\n )\n\n return jsonify({"status": "request_sent"})\n except Exception as e:\n logger.error(f"Error processing request: {e}")\n return jsonify({"error": str(e)}), 500\n'})}),"\n",(0,i.jsx)(n.h4,{id:"response-management",children:"Response Management"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-python",children:'@app.route(\'/webhook\', methods=[\'POST\'])\ndef webhook():\n try:\n # Parse incoming agent message\n data = request.get_data().decode("utf-8")\n message = parse_message_from_agent(data)\n # Store response for polling\n primary_agent.latest_response = message.payload\n return jsonify({"status": "success"})\n\n except Exception as e:\n logger.error(f"Error in webhook: {e}")\n return jsonify({"error": str(e)}), 500\n\[email protected](\'/api/get-response\', methods=[\'GET\'])\ndef get_response():\n try:\n if primary_agent.latest_response:\n response = primary_agent.latest_response\n primary_agent.latest_response = None\n return jsonify(response)\n return jsonify({"status": "
1waiting"})\n\n except Exception as e:\n logger.error(f"Error getting response: {e}")\n return jsonify({"error": str(e)}), 500\n'})}),"\n",(0,i.jsx)(n.h3,{id:"financial-analysis-agent-implementation",children:"Financial Analysis Agent Implementation"}),"\n",(0,i.jsx)(n.h4,{id:"agent-registration-and-setup",children:"Agent Registration and Setup"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-python",children:'def init_agent():\n """Initialize and register the agent with agentverse"""\n global financial_identity, research_chain\n try:\n # Initialize the research chain\n research_chain = init_financial_system()\n # Initialize identity and register with Agentverse\n financial_identity = Identity.from_seed(\n os.getenv("FINANCIAL_AGENT_KEY"),\n 0\n )\n \n # Register with detailed capabilities description\n register_with_agentverse(\n identity=financial_identity,\n url="http://localhost:5008/webhook",\n agentverse_token=os.getenv("AGENTVERSE_API_KEY"),\n agent_title="Financial Analysis Agent",\n readme = """\n <description>A comprehensive financial analysis agent that\n combines\n SEC filing analysis with real-time market data for Apple\n Inc.</description>\n filings</use_case>\n <use_cases>\n <use_case>Get detailed revenue analysis from SEC\n <use_case>Analyze risk factors from latest 10-\n K</use_case>\n <use_case>Track financial metrics and trends</use_case>\n </use_cases>\n <payload_requirements>\n <payload>\n <requirement>\n <parameter>query</parameter>\n <description>What would you like to know about\n Apple\'s financials?</description>\n </requirement>\n </payload>\n </payload_requirements>\n """\n )\n'})}),"\n",(0,i.jsx)(n.h4,{id:"query-processing-and-response",children:"Query Processing and Response"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-python",children:'@app.route(\'/webhook\', methods=[\'POST\'])\ndef webhook():\n try:\n # Parse incoming message\n data = request.get_data().decode(\'utf-8\')\n message = parse_message_from_agent(data)\n query = message.payload.get("request","")\n agent_address = message.sender\n # Validate query\n if not query:\n return jsonify({"status": "error", "message": "No query provided"}), 400\n \n # Process query using research chain\n result = research_chain.invoke({\n "messages": [HumanMessage(content=query)],\n "team_members": ["Search", "SECAnalyst"]\n })\n\n # Format response for client\n formatted_result = {\n "analysis": [\n {\n "role": msg.type if hasattr(msg, \'type\') else "message",\n "content": msg.content,\n "name": msg.name if hasattr(msg, \'name\') else None\n }\n for msg in result.get(\'messages\', [])\n ]\n }\n\n # Send response back through Agentverse\n send_message_to_agent(\n financial_identity,\n agent_address,\n {\'analysis_result\': formatted_result}\n )\n\n return jsonify({"status": "analysis_sent"})\n\n except Exception as e:\n logger.error(f"Error in webhook: {e}")\n return jsonify({"status": "error", "message": str(e)}), 500\n'})})]})}function g(e={}){const{wrapper:n}={...(0,a.R)(),...e.components};return n?(0,i.jsx)(n,{...e,children:(0,i.jsx)(d,{...e})}):d(e)}},28453:(e,n,t)=>{t.d(n,{R:()=>r,x:()=>l});var s=t(96540);const i={},a=s.createContext(i);function r(e){const n=s.useContext(a);return s.useMemo((function(){return"function"==typeof e?e(n):{...n,...e}}),[n,e])}function l(e){let n;return n=e.disableParentContext?"function"==typeof e.components?e.components(i):e.components||i:r(e.components),s.createElement(a.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.