How to Integrate CrewAI for investment banking with FastAPI for production AI
CrewAI gives you a clean way to orchestrate specialized agents for investment banking tasks like deal screening, market research, and memo drafting. FastAPI gives you the production HTTP layer to expose those workflows safely, with request validation, auth hooks, and predictable latency.
The real value is this: you can take a multi-agent banking workflow that normally lives in notebooks or scripts and turn it into an API your internal tools, analyst dashboards, or client-facing systems can call.
Prerequisites
- •Python 3.10+
- •
piporuv - •A working FastAPI app
- •CrewAI installed
- •An LLM provider configured through environment variables
- •Basic familiarity with async HTTP APIs and Pydantic models
- •Access to any internal banking data sources you plan to connect
Install the core packages:
pip install fastapi uvicorn crewai pydantic python-dotenv
Set your model credentials before running anything:
export OPENAI_API_KEY="your-key"
Integration Steps
- •Define your CrewAI agents and task flow
Start by modeling the banking workflow as a crew. For investment banking, keep agents narrow: one for company research, one for valuation summary, one for memo drafting.
from crewai import Agent, Task, Crew, Process
research_agent = Agent(
role="Equity Research Analyst",
goal="Summarize the target company and relevant market context",
backstory="You support investment banking teams with concise diligence notes.",
verbose=True,
)
valuation_agent = Agent(
role="Valuation Analyst",
goal="Extract valuation signals and comparable company context",
backstory="You produce banker-grade valuation summaries.",
verbose=True,
)
memo_agent = Agent(
role="Investment Banking Associate",
goal="Draft an investment memo from research and valuation inputs",
backstory="You write client-ready drafts for internal review.",
verbose=True,
)
research_task = Task(
description="Research the target company and summarize business model, risks, and recent news.",
expected_output="A concise diligence summary with bullets.",
agent=research_agent,
)
valuation_task = Task(
description="Review comparable companies and summarize valuation ranges.",
expected_output="A short valuation note with key metrics.",
agent=valuation_agent,
)
memo_task = Task(
description="Combine the findings into an investment banking memo draft.",
expected_output="A structured memo draft ready for analyst review.",
agent=memo_agent,
)
crew = Crew(
agents=[research_agent, valuation_agent, memo_agent],
tasks=[research_task, valuation_task, memo_task],
process=Process.sequential,
)
- •Wrap the crew in a service layer
Do not call crew.kickoff() directly from your route handler. Put it behind a service function so you can add retries, logging, tracing, and data access later.
from typing import Any
def run_investment_banking_workflow(company_name: str) -> Any:
kickoff_input = {
"company_name": company_name,
"industry": "investment banking target analysis",
}
result = crew.kickoff(inputs=kickoff_input)
return result
- •Expose the workflow through FastAPI
Use FastAPI’s request validation to keep your API contract tight. This is where production concerns start to matter: typed input, structured response, and clear failure modes.
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI(title="Investment Banking AI API")
class AnalysisRequest(BaseModel):
company_name: str
class AnalysisResponse(BaseModel):
company_name: str
report: str
@app.post("/analyze", response_model=AnalysisResponse)
def analyze_company(payload: AnalysisRequest):
try:
result = run_investment_banking_workflow(payload.company_name)
return AnalysisResponse(
company_name=payload.company_name,
report=str(result),
)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
- •Add startup configuration and run the app
For production AI systems, keep configuration outside code. Load secrets from environment variables or a secret manager before app startup.
import os
from dotenv import load_dotenv
load_dotenv()
if not os.getenv("OPENAI_API_KEY"):
raise RuntimeError("OPENAI_API_KEY is required")
# Run with:
# uvicorn main:app --host 0.0.0.0 --port 8000
- •Return structured outputs instead of raw text
In investment banking workflows, raw text is not enough. Convert agent output into sections so downstream systems can parse it for dashboards or review queues.
from pydantic import BaseModel
class MemoSection(BaseModel):
title: str
body: str
class StructuredMemo(BaseModel):
overview: MemoSection
risks: MemoSection
valuation: MemoSection
def parse_memo(raw_text: str) -> StructuredMemo:
# Replace this with deterministic parsing or an LLM-to-schema step.
return StructuredMemo(
overview=MemoSection(title="Overview", body=raw_text),
risks=MemoSection(title="Risks", body="Pending structured extraction"),
valuation=MemoSection(title="Valuation", body="Pending structured extraction"),
)
Testing the Integration
Use FastAPI’s test client to verify the endpoint returns a valid response shape.
from fastapi.testclient import TestClient
client = TestClient(app)
response = client.post("/analyze", json={"company_name": "Acme Holdings"})
print(response.status_code)
print(response.json())
Expected output:
200
{
"company_name": "Acme Holdings",
"report": "..."
}
If you want a quick manual check:
curl -X POST http://localhost:8000/analyze \
-H "Content-Type: application/json" \
-d '{"company_name":"Acme Holdings"}'
Real-World Use Cases
- •
Deal screening API
Feed target-company names into CrewAI agents that produce diligence summaries for bankers reviewing inbound opportunities. - •
Management presentation drafting
Generate first-pass slides or memo sections from market data, financials, and internal notes exposed through FastAPI endpoints. - •
Analyst research automation
Let internal tools call a/researchendpoint that returns structured outputs for comparables analysis, risk flags, and transaction context.
The pattern here is simple: CrewAI handles orchestration of specialist reasoning; FastAPI handles production delivery. If you keep those layers separate from day one, you get something that scales beyond demos without rewriting the whole stack later.
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