How to Integrate Azure OpenAI for wealth management with CosmosDB for multi-agent systems
Combining Azure OpenAI with Cosmos DB gives you a practical stack for wealth management agents that need both reasoning and durable memory. Azure OpenAI handles portfolio analysis, client summarization, and policy-aware recommendations, while Cosmos DB stores client profiles, interaction history, suitability constraints, and agent state across multiple workers.
That matters in multi-agent systems because each agent needs shared context without stepping on another agent’s state. You get a clean split: the model reasons, Cosmos DB persists.
Prerequisites
- •Python 3.10+
- •An Azure subscription with:
- •Azure OpenAI resource deployed
- •Cosmos DB account created
- •An Azure OpenAI deployment name for a chat model, such as
gpt-4o-mini - •Cosmos DB SQL API enabled
- •Environment variables set:
- •
AZURE_OPENAI_ENDPOINT - •
AZURE_OPENAI_API_KEY - •
AZURE_OPENAI_DEPLOYMENT - •
COSMOS_ENDPOINT - •
COSMOS_KEY - •
COSMOS_DATABASE - •
COSMOS_CONTAINER
- •
- •Installed packages:
- •
openai - •
azure-cosmos
- •
pip install openai azure-cosmos python-dotenv
Integration Steps
- •Set up your clients and environment variables.
Keep this boring and explicit. In production, don’t hardcode secrets or endpoints.
import os
from dotenv import load_dotenv
from openai import AzureOpenAI
from azure.cosmos import CosmosClient
load_dotenv()
azure_openai_client = AzureOpenAI(
api_key=os.environ["AZURE_OPENAI_API_KEY"],
azure_endpoint=os.environ["AZURE_OPENAI_ENDPOINT"],
api_version="2024-02-15-preview",
)
cosmos_client = CosmosClient(
url=os.environ["COSMOS_ENDPOINT"],
credential=os.environ["COSMOS_KEY"]
)
database_name = os.environ["COSMOS_DATABASE"]
container_name = os.environ["COSMOS_CONTAINER"]
database = cosmos_client.get_database_client(database_name)
container = database.get_container_client(container_name)
deployment_name = os.environ["AZURE_OPENAI_DEPLOYMENT"]
- •Create a container schema for agent memory.
For multi-agent wealth workflows, store one document per client or case. Use a stable partition key like /clientId so all related memory lands together.
from azure.cosmos import PartitionKey
database_name = os.environ["COSMOS_DATABASE"]
container_name = os.environ["COSMOS_CONTAINER"]
try:
database = cosmos_client.create_database_if_not_exists(id=database_name)
container = database.create_container_if_not_exists(
id=container_name,
partition_key=PartitionKey(path="/clientId"),
offer_throughput=400
)
except Exception as e:
print(f"Cosmos setup error: {e}")
A simple document shape works well:
client_profile = {
"id": "client-1001",
"clientId": "client-1001",
"name": "Amina Patel",
"riskProfile": "moderate",
"goals": ["retirement", "education funding"],
"constraints": {
"maxEquityAllocation": 0.65,
"liquidityNeedMonths": 6
},
"agentMemory": []
}
- •Use Azure OpenAI to generate a wealth-management recommendation.
The model should receive structured client data from Cosmos DB, not raw chat history dumps. That keeps prompts smaller and easier to audit.
import json
response = azure_openai_client.chat.completions.create(
model=deployment_name,
messages=[
{
"role": "system",
"content": (
"You are a wealth management assistant. "
"Return concise, compliant recommendations based on client constraints."
)
},
{
"role": "user",
"content": json.dumps({
"name": client_profile["name"],
"riskProfile": client_profile["riskProfile"],
"goals": client_profile["goals"],
"constraints": client_profile["constraints"]
})
}
],
temperature=0.2,
)
recommendation = response.choices[0].message.content
print(recommendation)
- •Persist the recommendation back into Cosmos DB for other agents.
This is the core multi-agent pattern: one agent reasons, another agent retrieves state later, and both share the same durable record.
from datetime import datetime, timezone
memory_event = {
"id": f"event-{datetime.now(timezone.utc).timestamp()}",
"clientId": client_profile["clientId"],
"type": "portfolio_recommendation",
"createdAtUtc": datetime.now(timezone.utc).isoformat(),
"sourceAgent": "advice-agent-1",
"content": recommendation
}
container.upsert_item(memory_event)
print("Saved recommendation to Cosmos DB")
- •Read shared memory before the next agent acts.
A planning agent can pull prior advice, risk flags, or compliance notes before generating the next step in the workflow.
query = """
SELECT * FROM c
WHERE c.clientId = @clientId
ORDER BY c.createdAtUtc DESC
"""
items = list(container.query_items(
query=query,
parameters=[{"name": "@clientId", "value": client_profile["clientId"]}],
enable_cross_partition_query=False
))
for item in items[:3]:
print(item["type"], item["createdAtUtc"])
Testing the Integration
Run an end-to-end check that reads a profile from Cosmos DB, asks Azure OpenAI for guidance, then stores the result back into Cosmos DB.
test_client_id = "client-1001"
profile = container.read_item(item=test_client_id, partition_key=test_client_id)
test_response = azure_openai_client.chat.completions.create(
model=deployment_name,
messages=[
{"role": "system", "content": "You are a wealth management assistant."},
{"role": "user", "content": f"Review this profile and suggest next action: {json.dumps(profile)}"}
],
)
result_text = test_response.choices[0].message.content
container.upsert_item({
"id": f"test-{test_client_id}",
"clientId": test_client_id,
"type": "test_result",
"createdAtUtc": datetime.now(timezone.utc).isoformat(),
"result": result_text
})
print("Integration OK")
print(result_text[:300])
Expected output:
Integration OK
Suggested next action: confirm liquidity needs for the next 6 months,
then rebalance toward a moderate-risk allocation...
Real-World Use Cases
- •Advisor copilot: One agent summarizes meeting notes with Azure OpenAI, another stores action items in Cosmos DB, and a third agent drafts follow-up tasks.
- •Suitability workflow: A policy agent checks constraints from Cosmos DB before the recommendation agent produces an investment proposal.
- •Client servicing orchestration: Multiple agents handle onboarding, portfolio review, and compliance review while sharing the same persistent case record.
The pattern is straightforward: use Azure OpenAI for reasoning and Cosmos DB for state. For wealth management systems with multiple agents, that separation is what keeps the architecture maintainable under real load.
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