How to Integrate FastAPI for investment banking with LangChain for startups
Combining FastAPI for investment banking with LangChain gives you a clean way to expose bank-grade workflows as APIs while letting an agent reason over them. The practical use case is simple: your startup can take a user request, route it through a FastAPI service that wraps investment banking logic, and let LangChain decide when to call that service versus answering directly.
This pattern works well when you need controlled access to sensitive operations like deal lookup, portfolio summaries, compliance checks, or document retrieval. FastAPI handles the service boundary; LangChain handles orchestration, tool selection, and response synthesis.
Prerequisites
- •Python 3.10+
- •A FastAPI app running locally or in your environment
- •LangChain installed with the OpenAI integration if you’re using an LLM-backed agent
- •
uvicornfor serving the API - •
httpxfor async HTTP calls from LangChain tools - •An API key for your model provider, stored in environment variables
- •Basic knowledge of Pydantic models and REST endpoints
Install the packages:
pip install fastapi uvicorn httpx langchain langchain-openai pydantic
Integration Steps
- •Build the FastAPI service for investment banking operations
Start by exposing the banking-side functionality as typed API endpoints. Keep the surface area small and explicit.
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List
app = FastAPI(title="Investment Banking API")
class DealRequest(BaseModel):
deal_id: str
class PortfolioRequest(BaseModel):
client_id: str
@app.get("/health")
def health():
return {"status": "ok"}
@app.post("/deals/summary")
def deal_summary(payload: DealRequest):
if payload.deal_id != "DEAL-1001":
raise HTTPException(status_code=404, detail="Deal not found")
return {
"deal_id": payload.deal_id,
"status": "live",
"sector": "Fintech",
"value_usd": 25000000,
}
@app.post("/portfolio/risk")
def portfolio_risk(payload: PortfolioRequest):
return {
"client_id": payload.client_id,
"risk_score": 72,
"flags": ["high concentration", "liquidity watch"],
}
Run it with:
uvicorn main:app --reload --port 8000
- •Wrap the FastAPI endpoint as a LangChain tool
LangChain needs a callable tool. Use StructuredTool so your agent can pass typed inputs instead of raw strings.
import httpx
from pydantic import BaseModel, Field
from langchain_core.tools import StructuredTool
class DealSummaryInput(BaseModel):
deal_id: str = Field(..., description="Investment banking deal identifier")
async def fetch_deal_summary(deal_id: str) -> dict:
async with httpx.AsyncClient(base_url="http://localhost:8000") as client:
response = await client.post("/deals/summary", json={"deal_id": deal_id})
response.raise_for_status()
return response.json()
deal_summary_tool = StructuredTool.from_function(
coroutine=fetch_deal_summary,
name="deal_summary",
description="Fetches summary details for an investment banking deal.",
args_schema=DealSummaryInput,
)
- •Create a LangChain agent that can call the tool
Use a chat model and bind the tool so the agent can decide when to invoke it.
import os
from langchain_openai import ChatOpenAI
from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate
llm = ChatOpenAI(
model="gpt-4o-mini",
api_key=os.environ["OPENAI_API_KEY"],
)
prompt = ChatPromptTemplate.from_messages([
("system", "You are an assistant for startup finance workflows. Use tools when banking data is required."),
("human", "{input}"),
])
tools = [deal_summary_tool]
agent = create_tool_calling_agent(llm, tools, prompt)
executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
- •Connect a startup-facing request flow to the agent
Now you can expose a second FastAPI endpoint that forwards user requests into the LangChain executor.
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class AgentRequest(BaseModel):
query: str
@app.post("/agent/query")
async def agent_query(payload: AgentRequest):
result = await executor.ainvoke({"input": payload.query})
return {"answer": result["output"]}
This gives you one API boundary for your startup product and one internal tool boundary for regulated banking logic.
- •Add another banking action and register it as a second tool
Once this pattern works, add more endpoints without changing your agent architecture.
class RiskInput(BaseModel):
client_id: str
async def fetch_portfolio_risk(client_id: str) -> dict:
async with httpx.AsyncClient(base_url="http://localhost:8000") as client:
response = await client.post("/portfolio/risk", json={"client_id": client_id})
response.raise_for_status()
return response.json()
risk_tool = StructuredTool.from_function(
coroutine=fetch_portfolio_risk,
name="portfolio_risk",
description="Returns risk metrics for a client portfolio.",
args_schema=RiskInput,
)
tools = [deal_summary_tool, risk_tool]
Testing the Integration
Hit the agent endpoint with a request that clearly needs banking data.
import httpx
import asyncio
async def test_agent():
async with httpx.AsyncClient(base_url="http://localhost:8000") as client:
response = await client.post(
"/agent/query",
json={"query": "Show me the summary for deal DEAL-1001"}
)
print(response.status_code)
print(response.json())
asyncio.run(test_agent())
Expected output:
{
"answer": "The deal DEAL-1001 is live in Fintech with an estimated value of 25000000 USD."
}
If the tool wiring is correct, you’ll see verbose=True traces from LangChain showing the tool call before the final answer.
Real-World Use Cases
- •
Deal desk assistant
- •Query live deal status, valuation snapshots, and sector summaries through controlled API calls.
- •Let analysts ask natural-language questions without touching raw internal systems.
- •
Portfolio risk copilot
- •Pull portfolio exposure metrics from FastAPI and let LangChain explain risk flags in plain English.
- •Useful for startup fintech products serving wealth managers or boutique banks.
- •
Compliance and document routing
- •Expose KYC/AML checks or document retrieval endpoints through FastAPI.
- •Use LangChain to decide whether to answer directly or escalate to a compliance workflow.
Keep learning
- •The complete AI Agents Roadmap — my full 8-step breakdown
- •Free: The AI Agent Starter Kit — PDF checklist + starter code
- •Work with me — I build AI for banks and insurance companies
By Cyprian Aarons, AI Consultant at Topiax.
Want the complete 8-step roadmap?
Grab the free AI Agent Starter Kit — architecture templates, compliance checklists, and a 7-email deep-dive course.
Get the Starter Kit