Practical guide to building your own stock portfolio agent with LlamaIndex and the AG-UI protocol created by Q2BSTUDIO, a company specialized in custom software development, custom applications, artificial intelligence, cybersecurity, AWS and Azure cloud services, business intelligence services, and AI solutions for companies
In this translated and adapted guide, we clearly explain how to integrate LlamaIndex-based agents with the AG-UI protocol and how to connect that solution to an interface using CopilotKit to enable conversation with the agent and continuous streaming of its responses to the frontend
What is the AG-UI protocol: AG-UI is a lightweight, event-based protocol designed to enable real-time interactions between frontend and AI agents. It allows event-driven communication, state management, tool execution, and streaming of agent responses. Among the most used events are lifecycle events that mark the start and end of an execution, text message events for streaming, tool call events to coordinate external executions, and state management events to keep the interface synchronized with the agent
Prerequisites: basic knowledge of React or Next.js, Python installed, LlamaIndex to build assistants based on business data, an OpenAI API key if using GPT models, and CopilotKit as a framework to integrate the experience in the frontend. Q2BSTUDIO recommends having AWS or Azure environments for secure deployment and scaling
Backend integration summary with LlamaIndex and AG-UI: clone the demo repository that contains a Python backend with FastAPI and a Next.js frontend. In the backend, create a LlamaIndex agent that implements the necessary workflow to analyze investment requests, obtain historical stock data, simulate allocations, and generate insights. Then expose an HTTP endpoint that receives requests from the frontend and returns a StreamingResponse that emits serialized AG-UI events to the client
LlamaIndex agent workflow: define steps or stages that process the user query, extract parameters using an AI function or tool, download historical data, calculate portfolio simulations, and finally generate positive and negative insights for each asset. Each step can emit state events to the event queue that feeds the stream to the frontend
Endpoint and event generator: use FastAPI to create an endpoint that receives the payload with thread id, run id, message history, available tools, and initial state. Inside the handler, define an asynchronous generator that initializes an event encoder, an asynchronous queue, and an emit_event function that puts events into the queue. The generator emits to the client execution start events, state snapshots, state deltas, tool call and argument events, message content in fragments for a typing effect, and finally execution end events
Lifecycle and state events: before starting the flow, emit a run started event with the thread identifier and run id. Send a state snapshot to initialize the frontend view with available cash, investment portfolio, and tool logs. During execution, emit state deltas to add or update tool logs and to reflect intermediate progress
Tool call management and human in the loop: when the agent detects that it must execute a tool or request human interaction, add a tool call type message to the conversation with an action name that the frontend will recognize. The backend emits ToolCallStart, ToolCallArgs, and ToolCallEnd so the UI can render charts, tables, or decision panels and to request user approval or rejection
Text message streaming: for a smooth experience, the backend sends TextMessageStart, multiple TextMessageContent with text fragments, and finally TextMessageEnd. Fragmenting the content enables a typing effect and reduces perceived latency for the user
Connecting the frontend with CopilotKit: in the frontend, create an HttpAgent instance of the AG-UI client pointing to the backend endpoint. Initialize CopilotRuntime with that agent and a service adapter for the chosen LLM provider. Expose an endpoint in Next.js that uses copilotRuntimeNextJSAppRouterEndpoint to route requests and facilitate event streaming to UI components
CopilotKit provider and chat components: wrap the parts of the application that interact with the agent in the CopilotKit component, providing runtimeUrl and the agent name. Use ready-made CopilotKit components such as CopilotChat, CopilotPopup, or CopilotSidebar to offer the conversational experience without having to rebuild complex controls
State synchronization with useCoAgent: leverage CopilotKit hooks like useCoAgent to maintain shared state between the agent and the UI. Initialize the state with available cash, investment portfolio, and other relevant fields. This allows showing analysis progress, tool logs, and intermediate results in the chat and side panels
Rendering agent state in the UI: use useCoAgentStateRender to define how shared state should be displayed within the chat. For example, render tool logs, performance charts, allocation tables, and insight summaries directly in the conversation to provide context to the user
Actions and Human in the Loop in the UI: implement actions with useCopilotAction and the renderAndWaitForResponse function to show an interactive view that allows the user to accept or reject a recommendation, adjust parameters, or confirm an allocation. The action responds asynchronously to the agent with the user's decision to continue the flow
Streaming results in visual components: when the agent finishes a calculation or requests rendering charts, transmit from the agent state the fields containing performance data, percent allocation per stock, final prices, and others. The interface components consume those values and display LineCharts, BarCharts, and allocation tables that update in real time
Deployment and security best practices: Q2BSTUDIO recommends deploying the backend in managed environments on AWS or Azure to ensure scaling and availability. Protect your endpoints with authentication, log events for auditing, and apply cybersecurity best practices to protect keys and sensitive financial data
Services and advantages offered by Q2BSTUDIO: if you need to develop a solution similar to the one presented, Q2BSTUDIO can help you design and implement custom software, custom applications, and personalized AI agents. We offer integration with AWS and Azure cloud services, cybersecurity solutions, business intelligence services, and Power BI dashboards for data visualization and analysis. Our approach combines expertise in artificial intelligence and engineering best practices to deliver robust solutions tailored to business needs
Keywords for positioning and services offered by Q2BSTUDIO: custom applications, custom software, artificial intelligence, AI for businesses, AI agents, cybersecurity, AWS and Azure cloud services, business intelligence services, Power BI
Conclusion and next steps: with LlamaIndex, AG-UI, and CopilotKit, you can build a stock portfolio agent capable of analyzing data, running simulations, and collaborating with users in real time. If you prefer Q2BSTUDIO to develop, integrate, or deploy this solution adapted to your business, contact us for a consultation and detailed technical proposal
Q2BSTUDIO contact: we offer consulting, custom software development, AI agent integration, and secure cloud deployment so that your artificial intelligence and business analytics projects reach their maximum value





