OpenBB
Product
Commercial OpenBB Workspace Snowflake Native App Security
Open Source Open Data Platform (ODP)
Introducing OpenBB Workspace Lite for small investment teams July 21, 2026 — 6 MIN Introducing OpenBB Workspace Lite for small investment teams Read post OpenBB Workspace Demo: Portfolio Analysis, Apps Marketplace, MCP & AI Agents July 1, 2026 — 11 MIN OpenBB Workspace Demo: Portfolio Analysis, Apps Marketplace, MCP & AI Agents Watch demo
Solutions
App Showcase App Marketplace
By audience Buy-Side AI Vendor
Introducing the OpenBB App Marketplace May 12, 2026 — 5 MIN Introducing the OpenBB App Marketplace Read post Introducing Workspace MCP: agentic financial workflows, governed by design May 26, 2026 — 8 MIN Introducing Workspace MCP: agentic financial workflows, governed by design Read post
Resources
Blog Videos About Documentation
Comparison
Streamlit Tableau Power BI
OpenBB Workspace Demo: Portfolio Analysis, Apps Marketplace, MCP & AI Agents July 1, 2026 — 11 MIN OpenBB Workspace Demo: Portfolio Analysis, Apps Marketplace, MCP & AI Agents Watch demo
Pricing
Commercial
OpenBB Workspace Snowflake Native App Security
Open Source
Open Data Platform (ODP)
App Showcase App Marketplace Buy-Side AI Vendor
Resources
Blog Videos About Documentation
Comparison
Streamlit Tableau Power BI
Pricing
Back to blog
Magnus Samuelsen

Author

Magnus Samuelsen

SHARE

Building AI agents for OpenBB Workspace with Pydantic AI

December 3, 2025 — 12 MIN

Building AI agents for OpenBB Workspace with Pydantic AI

Guest post by Magnus Samuelsen, Open Source Contributor and AI Engineer at Jyske Bank


Pydantic AI Meets OpenBB Workspace

Right now, OpenBB Workspace users can use the built-in Copilot with OpenAI, or build an integration from scratch. The OpenBB AI SDK gives you the protocol, but you're still left wiring up LLM calls, tool orchestration, and streaming events.

This is where openbb-pydantic-ai comes in. I built this library to handle all of that for you. It's a bridge that lets you write Pydantic AI agents that speak native OpenBB. It translates QueryRequest payloads into Pydantic AI runs and streams native OpenBB events back to the client, so you can focus on your agent's logic, not the integration plumbing.

This post will walk you through the architecture of the adapter that makes this possible, the key technical challenges I solved, and how you can get your own custom agent running in minutes.

The Challenge: Not Just a Chatbot

Integrating an AI agent into OpenBB Workspace is more complex than connecting to a chat interface. The Workspace is a dynamic environment where users and AI interact with data widgets, visualizations, and complex analysis dashboards.

An effective agent must:

  • "See" the Workspace: Understand the current state of the Workspace, including available widgets, data sources, and user interactions.

  • Access Remote Resources: Fetch data from widgets that exist on the client's browser and call external tools from MCP Servers, running locally on your machine or connected through the OpenBB Workspace via MCP.

  • Stream Rich Events: Stream reasoning steps, tool use, artifacts like tables and charts, and provide citations that the Workspace UI can render appropriately.

The Solution: A UI Event Stream Adapter

Fortunately, Pydantic AI has a flexible adapter system exactly for this type of job.

It's UIAdapter and UIEventStream abstract classes are designed for translating between agent events and different UI protocols. By implementing OpenBBAIAdapter and OpenBBAIEventStream, we can map OpenBB's QueryRequest payloads into Pydantic AI event streams, and vice versa.

As mentioned earlier, though, integration with OpenBB Workspace is more than just event translation, so there are some extra features in addition to basic request handling.

Workspace Context Injection

The first challenge is making the agent aware of the user's Workspace. The adapter extracts Workspace context (available widgets, URLs, defaults) from the QueryRequest, builds an OpenBBDeps dependency object, and injects it into the agent run as RunContext. This context updates the system prompt in the Pydantic AI message stack, giving the agent the necessary awareness to make informed decisions.

The Deferred Call Handshake

Next, we need to enable the agent to access client-side widget data. For this we build an ExternalToolset on the fly based on the widgets present in the OpenBBDeps object. We expose all available widgets as function tools to the agent. In addition, we build a separate toolset for MCP tools that are passed in the tools field of the QueryRequest.

When an agent needs widget data, we can't block the server waiting for the browser. Instead, we use a deferred execution pattern:

  1. Agent requests data: The agent calls a tool, which raises CallDeferred and ends the run with a DeferredToolRequests payload
  2. Connection closes: The adapter emits a final get_widget_data SSE event containing the widget IDs and closes the stream. We include the tool_call_id in extra_state.tool_calls, a pass-through object the frontend will return unchanged
  3. Frontend executes: The browser fetches the requested widget data or MCP tool results
  4. New request: The frontend sends a fresh POST /query request with the tool results and the original extra_state attached
  5. Agent resumes: It extracts tool_call_id values from extra_state.tool_calls to match each result back to its corresponding tool call, rebuilds the proper ToolReturnPart messages, and injects them into a new agent run to continue streaming

This explicit handshake keeps the server stateless, with no long-lived connections or session storage required, while giving the agent real-time access to client-side data. Each widget call also generates a citation, so users can track where data comes from.

Widget Type Agent Can Parse Status
Tables, JSON Yes Full support
Charts, Text Yes Full support
PDFs, Images No Tool available; agent receives raw bytes but cannot yet process
Custom widgets Partial Depends on output schema

Server-Side Visualization Tools

Not everything needs a round trip to the client. I also include some visualization tools, openbb_create_chart and openbb_create_table, that run as normal tools on the server side. When the agent uses this, it produces an OpenBB-ready artifact, so you can stream charts and tables correctly formatted for the Workspace UI without any extra effort.

If you instruct the agent to use placeholders (e.g. {{place_chart_here}}) in its response, the adapter will replace these with the correct artifact references automatically. If not they are emitted at the end of the run.

By using Pydantic AI's ToolReturn object, we can send the heavy chart configuration as a side-channel artifact to the UI, while returning a simple "Chart created successfully" message to the agent. This is an attempt at keeping the agent's context window clean and focused on the conversation.

Finally, the adapter translates every remaining Pydantic AI event into OpenBB SSE events. Text chunks are streamed as MessageChunkSSE, reasoning steps (including Thinking tokens) are grouped under a "Step-by-step reasoning" dropdown passed as StatusUpdateSSE, and any tool invocation that stays on the server is passed as details in a StatusUpdateSSE to the user so they can observe a complex, multi-tool workflow in real time. Tables and charts (whether produced by the visualization helpers or another tool) are emitted as MessageArtifactSSE events with the correct rendering parameters, and citations are buffered and emitted at the end of the run.

The end result is that you can build a fully-featured AI agent for OpenBB Workspace using Pydantic AI's high-level abstractions, while still taking advantage of the Workspace's dynamic environment and rich UI capabilities. Because the adapter handles all the translation and streaming logic, you can focus on designing your agent's behavior, tools, and prompts without worrying about the underlying protocol details.

In practice, this means you only need a single line of code to turn any Pydantic AI agent into an OpenBB Workspace agent:

OpenBBAIAdapter.dispatch_request(request, agent=agent)

Simply call dispatch_request with the incoming QueryRequest and your Pydantic AI agent instance, and the adapter takes care of the rest. (Full example below.)

What Does This Unlock?

By bridging Pydantic AI with OpenBB Workspace, you can now take full control over the AI agent's behavior, tools, and prompts while seamlessly integrating with the user's workspace environment. This means using any model provider supported by Pydantic AI, custom tools for analysis, and optimized prompts for your specific use case.

For example:

  • You could build an agent that focuses on a different domain than finance. Perhaps you want to analyze sports statistics or personal health data, all while leveraging the powerful Workspace UI for visualizations and interactivity.

  • You have trained a custom model that you run locally or on a private server, and you want to use that model to power your agent in the OpenBB Workspace.

  • You build custom agent workflows that follow a specific logic or sequence of tool calls tailored to your use case.

Whether you have a specific analysis workflow in mind or want to experiment with different model providers and prompt strategies, this adapter gets you there faster. And if you build something useful, share it with the community!

Bringing It All Together: A Complete Example

Here's a complete example of how to set up a custom Pydantic AI agent using the openbb-pydantic-ai adapter, running it inside OpenBB Workspace with OpenRouter as the model provider and a local MCP server:

from anyio import BrokenResourceError
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerStreamableHTTP
from pydantic_ai.models.openai import OpenAIChatModel
from openbb_pydantic_ai import OpenBBAIAdapter, OpenBBDeps
# Connect to local MCP server for additional tools
mcp = MCPServerStreamableHTTP(
    url="http://localhost:8001/mcp/",
    max_retries=3,
)
# Use any OpenRouter model you prefer
model = OpenAIChatModel(
    provider="openrouter",
    model_name="prime-intellect/intellect-3",
)
# Define agent with workspace-aware instructions
agent = Agent(
    model,
    instructions=(
        """
        You have access to the OpenBB Workspace and you can use the widgets to get data.
        To get data use the widget tools.
        Other data sources and analysis tools are available via the MCP toolset.
        When you want to visualize data, use the `openbb_create_chart` tool.
        This tool supports line, bar, scatter, pie, and donut charts.
        Always use this tool when you want to display visualizations.
        For tables, simply output markdown tables and they will be rendered nicely.
        Or use the `openbb_create_table` tool for large tables.
        Use placerholder {{place_chart_here}} in your response to indicate where charts should go.
        Highlight key insights and suggest actionable next steps when helpful.
        If the next step is obvious, you can just do it without asking the user.
        """
    ),
    deps_type=OpenBBDeps,
    retries=3,
    toolsets=[mcp],
)
app = FastAPI()
AGENT_BASE_URL = "http://localhost:8003"
# OpenBB Workspace discovers agents via this endpoint
@app.get("/agents.json")
async def agents_json():
    return JSONResponse(
        content={
            "<agent-id>": {
                "name": "My Custom Agent",
                "description": "This is my custom agent",
                "image": f"{AGENT_BASE_URL}/my-custom-agent/logo.png",
                "endpoints": {
                    "query": f"{AGENT_BASE_URL}/query",
                },
                "features": {
                    "streaming": True,
                    "widget-dashboard-select": True,  # Access priority widgets
                    "widget-dashboard-search": True,  # Access non-priority widgets
                    "mcp-tools": True,               # Use MCP tools
                },
            }
        }
    )
# Main query endpoint that handles SSE streaming
@app.post("/query")
async def query(request: Request):
    """
    OpenBB Workspace sends POST requests with QueryRequest payload.
    The adapter handles SSE streaming automatically.
    """
    try:
        return await OpenBBAIAdapter.dispatch_request(
            request, agent=agent
        )
    except BrokenResourceError:
        # Client disconnected we expect this sometimes
        pass
# CORS configuration for OpenBB Workspace domain
app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://pro.openbb.co"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

Future Roadmap: Smarter Context Management

While the current adapter solves the connectivity problem, the next step is context efficiency.

Financial datasets can be massive, sometimes hundreds of thousands of tokens for a single widget. Feeding raw JSON into an LLM's context window is inefficient and prone to cause hallucinations.

Get Started Today

Install openbb-pydantic-ai from PyPI, plug in your model, and deploy your agent in no time. Build that niche earnings-call analyzer, ESG scoring agent, or custom quant workflow and share it with the OpenBB community.

If you have ideas on how to improve this or just want to discuss agents, reach me on LinkedIn or GitHub.


Magnus Samuelsen is an AI Engineer at Jyske Bank, working at the intersection of AI, finance and banking. He holds an MSc in Business Administration and Data Science from Copenhagen Business School. Magnus is also an active open-source contributor around AI in finance, having led the addition of MCP (Model Context Protocol) support to the Open Data Platform. You can find him on LinkedIn.

Overview

  • Pydantic AI Meets OpenBB Workspace
  • The Challenge: Not Just a Chatbot
  • The Solution: A UI Event Stream Adapter
  • Workspace Context Injection
  • The Deferred Call Handshake
  • Server-Side Visualization Tools
  • What Does This Unlock?
  • Bringing It All Together: A Complete Example
  • Future Roadmap: Smarter Context Management
  • Get Started Today

Recommended For You

OpenBB belongs to everyone
August 25, 2026 — 8 MIN

OpenBB belongs to everyone

Read more
SnapTrade brings connected brokerage account data into OpenBB
August 5, 2026 — 5 MIN

SnapTrade brings connected brokerage account data into OpenBB

Read more
Carbon Arc brings card spend, web traffic, and more into OpenBB
July 23, 2026 — 7 MIN

Carbon Arc brings card spend, web traffic, and more into OpenBB

Read more

Analysts shouldn't need a data scientist to get an answer

The firms that fix that first will have a structural advantage

Start now
OpenBB
OpenBB Workspace Snowflake Native App Security Open Data Platform (ODP)
App Showcase App Marketplace Buy-Side AI Vendor
Blog Videos About Documentation Streamlit Tableau Power BI
Pricing Open Startup Support Contact Sitemap
Product
OpenBB Workspace Snowflake Native App Security
Open Data Platform (ODP)
Solutions
App Showcase App Marketplace Buy-Side AI Vendor
Resources
Blog Videos About Documentation Streamlit Tableau Power BI
Other
Pricing Open Startup Support Contact Sitemap

Copyright © 2026 OpenBB Inc. All rights reserved.
Privacy Policy Terms Trust Center OSS Friends

August 25, 2026

OpenBB belongs to everyone

Didier Lopes

Founder & CEO, OpenBB


TL;DR: We are open-sourcing the entire OpenBB product suite under a permissive open source license

Today is bittersweet.

On December 20, 2020, over the Christmas holidays, I wrote the first lines of Gamestonk Terminal, what would eventually become OpenBB. My flight home to visit my parents had been cancelled because of COVID, so I stayed in London and started building a tool to streamline my own investment research process.

At the time, the idea was simple: individuals (and firms) should be able to own their research platforms. They shouldn't have to adapt their workflows to whatever a data or software vendor decided to build. They should own the entire experience - from the data they connect to, to the interface analysts and PMs use every day, to the APIs, models, skills, tools and AI agents that increasingly form part of the investment process.

Over the last almost six years, OpenBB evolved far beyond anything I imagined when writing those first lines of code. We started as an open-source terminal and went on to build the SDK (now Open Data Platform), the OpenBB Bot, the OpenBB Workspace, the OpenBB Copilot, the Excel Add-in, and an ecosystem of applications created by our team, our partners and the community.

We kept innovating and being at the forefront of what user experience should be. I was prepared to die on the hill that if we were to become the financial infrastructure software for the buy-side and sell-side, then we could not monetize data. Monetizing data would have made us a data vendor. The margins would have been higher, but the incentive would have shifted from offering a better UI/UX to selling more datasets. Selling an infrastructure platform is incredibly challenging, for many reasons. And so we died on that hill. Along the way, we built an incredible community, reached millions of people through our open-source project, worked with some of the largest financial institutions in the world and assembled a team that consistently built far beyond what should have been possible for a company of 10 people. There is a lot to be proud of.

But despite all of that, we couldn't find the product-market fit needed to build a sustainable business around this vision within the time we had.

As a founder, I've always bet the house on the next customer, the next feature or the next launch to change the trajectory of the company. Until even just last weeks, when we announced self-serve Workspace Lite. If we were ever going to close doors, then we never wanted to look back and think "what if".

In hindsight, we could obviously have made different decisions - e.g., surrounding data, or going more vertical with clients and their workflows. But short-term monetization was not something I was prioritizing over where I thought the industry was heading. Ultimately, I wanted us to stand for something.

In the last phase of the company, I explored many paths to give OpenBB a better home. We spoke with larger companies that shared parts of our vision and tried to find a home where the products, and ideally the team behind them, could continue to grow. Ultimately, we weren't able to make that happen.

I left London with my wife to build OpenBB and dedicated almost six years of my life to it. So did the team. We built at the intersection of finance, AI, open source and software infrastructure, often working on problems before they became obvious to the broader market.

Before MCP existed, we had created our own API protocol so agents could interact with the data and analytics widgets in the workspace. In 2023, we built askobb, which let anyone ask investment research questions in natural language that required joining multiple different datasets together.

What this team created deserves to continue existing.

More importantly, I still believe the original vision is inevitable. The future of financial software is not a single platform every firm is forced to use. It is thousands of firms building environments that reflect how they actually work - their own data, internal systems, investment processes, risk models and compliance requirements. Increasingly, their own APIs, MCP servers, models and AI agents too.

If that future is coming, then the technology we built shouldn't disappear simply because we weren't able to commercialize it successfully.

It should become available to everyone.

Today, with the support of the team and OSS Capital, we are committing to releasing the entire OpenBB product suite under a permissive license. This includes OpenBB Workspace, Open Data Platform, OpenBB Copilot and the OpenBB Excel Add-in.

These products represent over 5 years of engineering, millions of dollars invested in R&D and thousands of decisions, experiments and iterations with users. They will become a foundation that individuals, startups, data providers and financial institutions can freely use, modify and build on top of.

We will share more details about the order and timing of each release as we complete that work. In parallel, we will determine the right long-term structure to steward the projects, support contributors and preserve what made OpenBB special in the first place. Existing customers and users of the hosted products will hear from us directly about timelines.

For the partners who built applications for the OpenBB ecosystem, I hope this decision makes your products even more valuable. You already did the work of turning your datasets and analytics into applications that users can interact with. Now, those applications will be able to run inside infrastructure that firms can fully own, extend and customize, while combining them with data and tools from other providers across the ecosystem.

The same applies to the broader community. Developers will be able to use the entire OpenBB stack as a starting point rather than rebuilding the same infrastructure from scratch. Firms will be able to deploy it, adapt it to their requirements and connect it to the systems where their differentiated knowledge already lives.

Over the years, many talented people helped make OpenBB what it is today - employees, contributors, partners. Every one of them left a mark on the product.

But I want to recognize the people who carried OpenBB to the very end. Through the uncertainty and the final stretch, they kept building. They are engineers, product builders, designers and operators who have worked across financial data, AI, developer infrastructure and open source. In alphabetical order, they are:

  • Andrew Kenreich, Head of Product Engineering - LinkedIn
  • Darren Lee, Software Engineer - GitHub, LinkedIn
  • Ihsan Saracgil, CPO - LinkedIn
  • José Donato, Software Engineer - LinkedIn, X, GitHub, Website
  • Juan Alfonso, Software Engineer - GitHub, LinkedIn
  • Minh Hoang, Head of Product - LinkedIn, GitHub
  • Ogonna Nnamani, DevOps - LinkedIn, Medium
  • Rita Figueiredo, Head of Marketing - LinkedIn, Website
  • Rita Soares, Head of Design - LinkedIn, Website
  • Theodore Aptekarev, CTO - LinkedIn, GitHub

To our customers: thank you for trusting a small team with such an ambitious vision.

To our partners: thank you for building alongside us and helping create a more open financial data ecosystem. I hope the next chapter gives you even more freedom to serve your users.

To our investors: thank you for believing in us, including when OpenBB was little more than an idea being built from my living room in London. In particular, I want to thank OSS Capital and Joseph Jacks for supporting this decision and enabling the technology to live beyond the company. Two people I want to name separately: Justin Hoffman and Larry Augustin - working with both of you made me a better founder, but more importantly, a better person.

To every contributor who opened a pull request, reported a bug, wrote documentation, answered a question in Discord, built an integration or simply told someone else about OpenBB: thank you. OpenBB would not have been possible without you.

Finally, to every person who spent part of their career building OpenBB: thank you. We pushed the industry forward and proved that world-class financial infrastructure can be built in the open. The commercial outcome doesn't change the quality of the work.

OpenBB didn't become the company I imagined when I started this journey. But the mission was always larger than the company, and I still believe the ideas behind it are right.

If, ten years from now, firms around the world are using OpenBB as the foundation for software they truly own - connecting their own data, building their own workflows and deploying their own AI agents - then what we built will have achieved something that lasts far beyond us; which was my goal all along: have an impact.

Thank you for one hell of a ride.

Didier Lopes
(LinkedIn, X, GitHub)