How to Integrate CrewAI for pension funds with FastAPI for multi-agent systems
Combining CrewAI for pension funds with FastAPI gives you a clean way to expose multi-agent workflows as production APIs. That matters when you need pension operations like contribution checks, benefit estimates, document review, and case triage to run behind a single HTTP interface with clear request/response contracts.
FastAPI handles the API layer. CrewAI for pension funds handles the agent orchestration. Together, you get a service that can receive a pension case, fan it out to specialized agents, and return a structured decision payload your downstream systems can use.
Prerequisites
- •Python 3.10+
- •FastAPI installed
- •Uvicorn installed
- •CrewAI for pension funds SDK installed and configured
- •An LLM provider configured for your agents
- •Basic knowledge of Pydantic models and async Python
- •A local
.envfile or secrets manager for API keys
Install the core packages:
pip install fastapi uvicorn crewai pydantic python-dotenv
Integration Steps
- •Define your FastAPI request and response models
Start with explicit schemas. Pension workflows need predictable inputs like member ID, case type, and supporting documents.
from pydantic import BaseModel, Field
from typing import List, Optional
class PensionCaseRequest(BaseModel):
member_id: str = Field(..., examples=["M123456"])
case_type: str = Field(..., examples=["benefit_estimate", "contribution_review"])
documents: List[str] = Field(default_factory=list)
notes: Optional[str] = None
class PensionCaseResponse(BaseModel):
status: str
summary: str
agent_outputs: dict
- •Create CrewAI agents for pension fund tasks
Use separate agents for distinct responsibilities. In a real pension workflow, one agent should not do everything.
from crewai import Agent
benefits_agent = Agent(
role="Benefits Analyst",
goal="Review pension benefit questions and estimate outcomes from provided data.",
backstory="You analyze pension records, contribution history, and retirement eligibility.",
verbose=True,
)
compliance_agent = Agent(
role="Compliance Reviewer",
goal="Check the case for policy issues, missing documents, and compliance flags.",
backstory="You validate pension cases against internal rules and regulatory requirements.",
verbose=True,
)
- •Assemble the CrewAI crew and task flow
Build tasks that map to your business process. The output should be structured enough to return through FastAPI without extra parsing hacks.
from crewai import Task, Crew
benefit_task = Task(
description=(
"Review the pension case for benefit estimate guidance based on member data "
"and supporting documents."
),
expected_output="A concise benefit assessment with any assumptions listed.",
agent=benefits_agent,
)
compliance_task = Task(
description=(
"Review the same pension case for missing information, policy issues, "
"and compliance concerns."
),
expected_output="A compliance summary with flags and required follow-up items.",
agent=compliance_agent,
)
crew = Crew(
agents=[benefits_agent, compliance_agent],
tasks=[benefit_task, compliance_task],
)
- •Expose the crew through a FastAPI endpoint
This is where the integration becomes useful. The endpoint accepts a request, passes context into the crew execution path, then returns the result.
from fastapi import FastAPI, HTTPException
app = FastAPI(title="Pension Multi-Agent API")
@app.post("/pension/case", response_model=PensionCaseResponse)
def process_pension_case(payload: PensionCaseRequest):
try:
result = crew.kickoff(
inputs={
"member_id": payload.member_id,
"case_type": payload.case_type,
"documents": payload.documents,
"notes": payload.notes or "",
}
)
return PensionCaseResponse(
status="success",
summary=str(result),
agent_outputs={
"crew_result": str(result),
},
)
except Exception as exc:
raise HTTPException(status_code=500, detail=str(exc))
- •Run FastAPI and wire in environment configuration
Keep credentials out of code. Load them at startup so both FastAPI and CrewAI can access provider settings.
import os
from dotenv import load_dotenv
load_dotenv()
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY", "")
Then start the app:
uvicorn main:app --reload --port 8000
Testing the Integration
Use curl or any HTTP client to verify the endpoint returns a structured response.
curl -X POST "http://127.0.0.1:8000/pension/case" \
-H "Content-Type: application/json" \
-d '{
"member_id": "M123456",
"case_type": "benefit_estimate",
"documents": ["payslip.pdf", "statement.pdf"],
"notes": "Member plans to retire in 18 months"
}'
Expected output:
{
"status": "success",
"summary": "...crew output...",
"agent_outputs": {
"crew_result": "...crew output..."
}
}
If you want a quick smoke test inside Python:
from fastapi.testclient import TestClient
client = TestClient(app)
response = client.post(
"/pension/case",
json={
"member_id": "M123456",
"case_type": "contribution_review",
"documents": ["contributions.csv"],
"notes": "Check for missing employer payments"
},
)
print(response.status_code)
print(response.json())
Real-World Use Cases
- •
Benefit estimate API
Expose an endpoint that routes retirement projection requests to one agent while another checks policy constraints before returning a final estimate. - •
Case triage service
Accept incoming pension support tickets and have agents classify urgency, identify missing documents, and route cases to the right operations queue. - •
Compliance review workflow
Run multi-agent checks on withdrawals, transfers, or beneficiary changes before those requests hit your core administration system.
If you want this in production shape, add retries around LLM calls, store every request/response pair in an audit log, and make each agent return JSON instead of free-form text. That keeps your FastAPI layer predictable and makes downstream integration much easier.
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