How to Integrate Azure OpenAI for wealth management with CosmosDB for AI agents

By Cyprian AaronsUpdated 2026-04-21
azure-openai-for-wealth-managementcosmosdbai-agents

Why this integration matters

Wealth management agents need two things: strong language reasoning and durable state. Azure OpenAI handles the reasoning layer for portfolio Q&A, client communication, suitability checks, and summarization; CosmosDB stores client profiles, holdings, interaction history, and agent memory with low-latency access.

The combination gives you an agent that can answer questions like “What changed in this client’s risk exposure this month?” while keeping the underlying data model queryable, auditable, and ready for production workflows.

Prerequisites

  • An Azure subscription with:
    • Azure OpenAI resource
    • Azure Cosmos DB account
  • A deployed Azure OpenAI chat model, such as gpt-4o-mini or gpt-4.1
  • Python 3.10+
  • Installed packages:
    • openai
    • azure-cosmos
    • python-dotenv
  • Environment variables set:
    • AZURE_OPENAI_ENDPOINT
    • AZURE_OPENAI_API_KEY
    • AZURE_OPENAI_DEPLOYMENT
    • COSMOS_ENDPOINT
    • COSMOS_KEY
    • COSMOS_DATABASE_NAME
    • COSMOS_CONTAINER_NAME

Install the SDKs:

pip install openai azure-cosmos python-dotenv

Integration Steps

  1. Initialize both clients

    Start by wiring up Azure OpenAI and CosmosDB in the same Python process. Keep credentials out of code and load them from environment variables.

import os
from dotenv import load_dotenv
from openai import AzureOpenAI
from azure.cosmos import CosmosClient

load_dotenv()

aoai_client = AzureOpenAI(
    api_key=os.environ["AZURE_OPENAI_API_KEY"],
    api_version="2024-02-15-preview",
    azure_endpoint=os.environ["AZURE_OPENAI_ENDPOINT"],
)

cosmos_client = CosmosClient(
    url=os.environ["COSMOS_ENDPOINT"],
    credential=os.environ["COSMOS_KEY"],
)
  1. Connect to your database and container

    For wealth management agents, use a partition key that matches your access pattern. A common choice is clientId, because most lookups are per-client.

database_name = os.environ["COSMOS_DATABASE_NAME"]
container_name = os.environ["COSMOS_CONTAINER_NAME"]

database = cosmos_client.get_database_client(database_name)
container = database.get_container_client(container_name)

print("Connected to Cosmos DB container:", container_name)

If you are creating the resources from code during setup, use this pattern:

database = cosmos_client.create_database_if_not_exists(id=database_name)
container = database.create_container_if_not_exists(
    id=container_name,
    partition_key={"paths": ["/clientId"]},
    offer_throughput=400,
)
  1. Store client context in CosmosDB

    Your agent should not rely on prompt memory alone. Persist structured client context such as risk profile, goals, holdings snapshot, and recent interactions.

client_profile = {
    "id": "client-1001",
    "clientId": "client-1001",
    "name": "Amina Patel",
    "riskProfile": "moderate",
    "goal": "retirement income",
    "holdings": [
        {"ticker": "VTI", "weight": 0.45},
        {"ticker": "BND", "weight": 0.35},
        {"ticker": "AAPL", "weight": 0.20},
    ],
    "lastInteraction": "2026-04-21T10:00:00Z",
}

container.upsert_item(client_profile)
print("Saved client profile")

In production, store more than a single profile document:

  • current portfolio snapshot
  • suitability notes
  • conversation summaries
  • compliance flags
  • recommended actions
  1. Retrieve context and send it to Azure OpenAI

    Pull the relevant record from CosmosDB, then pass only the needed fields into the model prompt. This keeps token usage under control and makes responses grounded in stored data.

client_id = "client-1001"

query = f"SELECT * FROM c WHERE c.clientId = '{client_id}'"
items = list(container.query_items(query=query, enable_cross_partition_query=True))

if not items:
    raise ValueError("Client not found")

profile = items[0]

messages = [
    {
        "role": "system",
        "content": (
            "You are a wealth management assistant. "
            "Use the provided client data to answer clearly and concisely."
        ),
    },
    {
        "role": "user",
        "content": (
            f"Client profile:\n{profile}\n\n"
            "Summarize the portfolio risk level and suggest one rebalancing consideration."
        ),
    },
]

response = aoai_client.chat.completions.create(
    model=os.environ["AZURE_OPENAI_DEPLOYMENT"],
    messages=messages,
    temperature=0.2,
)

print(response.choices[0].message.content)
  1. Write back the agent result to CosmosDB

    After generating a response, persist the outcome so future turns can reference it. This is how you build traceability for advisor copilots and internal agent workflows.

agent_note = {
    "id": f"note-{client_id}-001",
    "clientId": client_id,
    "type": "agent_summary",
    "summary": response.choices[0].message.content,
}

container.upsert_item(agent_note)
print("Saved agent summary")

Testing the Integration

Run a full round trip: fetch client data from CosmosDB, generate advice with Azure OpenAI, then save the result back to CosmosDB.

test_client_id = "client-1001"

doc = container.read_item(item=test_client_id, partition_key=test_client_id)

prompt = f"""
Client name: {doc['name']}
Risk profile: {doc['riskProfile']}
Goal: {doc['goal']}
Holdings: {doc['holdings']}

Give a short wealth management summary.
"""

result = aoai_client.chat.completions.create(
    model=os.environ["AZURE_OPENAI_DEPLOYMENT"],
    messages=[
        {"role": "system", "content": "You are a wealth management assistant."},
        {"role": "user", "content": prompt},
    ],
)

summary_text = result.choices[0].message.content

container.upsert_item({
    "id": f"test-summary-{test_client_id}",
    "clientId": test_client_id,
    "type": "test_summary",
    "summary": summary_text,
})

print(summary_text)

Expected output:

Client has a moderate risk profile with a retirement income goal.
The current allocation appears balanced but may benefit from reviewing equity concentration...

If this works end-to-end, you have validated:

  • document retrieval from CosmosDB
  • prompt assembly for Azure OpenAI
  • response generation
  • persistence of agent output

Real-World Use Cases

  • Advisor copilot

    • Pull client history from CosmosDB
    • Ask Azure OpenAI to draft meeting prep notes, follow-up emails, or portfolio summaries
  • Suitability and risk review assistant

    • Store risk questionnaires and account snapshots in CosmosDB
    • Use Azure OpenAI to explain mismatches between stated goals and actual allocations
  • Client servicing workflow automation

    • Save interaction logs in CosmosDB
    • Let the agent summarize conversations, flag missing KYC fields, and generate next-step tasks

Keep learning

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

Related Guides