How to Integrate Azure OpenAI for payments with CosmosDB for AI agents

By Cyprian AaronsUpdated 2026-04-21
azure-openai-for-paymentscosmosdbai-agents

Combining Azure OpenAI with CosmosDB gives you a practical pattern for payment-aware AI agents: the model handles intent, extraction, and decision support, while CosmosDB stores transaction state, audit trails, and customer context. That means you can build agents that answer payment questions, validate payment workflows, and persist every step for compliance and recovery.

Prerequisites

  • Python 3.10+
  • An Azure subscription
  • An Azure OpenAI resource with:
    • endpoint
    • API key
    • deployed chat model name
  • An Azure Cosmos DB account with:
    • database created
    • container created
    • partition key defined
  • pip installed
  • Environment variables configured:
    • AZURE_OPENAI_ENDPOINT
    • AZURE_OPENAI_API_KEY
    • AZURE_OPENAI_DEPLOYMENT_NAME
    • COSMOS_ENDPOINT
    • COSMOS_KEY
    • COSMOS_DATABASE_NAME
    • COSMOS_CONTAINER_NAME

Install the SDKs:

pip install openai azure-cosmos python-dotenv

Integration Steps

  1. Set up your clients

You want two separate clients: one for Azure OpenAI and one for CosmosDB. Keep them isolated so your agent logic can swap storage or model providers later without rewriting everything.

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"],
    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"]
)

database = cosmos_client.get_database_client(os.environ["COSMOS_DATABASE_NAME"])
container = database.get_container_client(os.environ["COSMOS_CONTAINER_NAME"])
deployment_name = os.environ["AZURE_OPENAI_DEPLOYMENT_NAME"]
  1. Define the payment agent prompt

For payments, keep the prompt strict. You want structured output, not creative prose. Ask the model to extract intent, amount, currency, payer reference, and a confidence score.

def build_payment_prompt(user_message: str) -> list[dict]:
    return [
        {
            "role": "system",
            "content": (
                "You are a payments assistant. Extract payment intent as JSON only. "
                "Return fields: intent, amount, currency, payer_ref, confidence."
            ),
        },
        {"role": "user", "content": user_message},
    ]
  1. Call Azure OpenAI to classify or extract payment details

Use chat.completions.create() from the Azure OpenAI Python SDK. In a real agent system, this is where you turn unstructured user input into a normalized payment event.

def extract_payment_details(user_message: str) -> dict:
    response = azure_openai_client.chat.completions.create(
        model=deployment_name,
        messages=build_payment_prompt(user_message),
        temperature=0,
    )

    content = response.choices[0].message.content
    return {"raw_model_output": content}

If you want cleaner downstream handling, parse JSON from the response and validate it before writing to storage.

import json

def extract_payment_details_json(user_message: str) -> dict:
    response = azure_openai_client.chat.completions.create(
        model=deployment_name,
        messages=build_payment_prompt(user_message),
        temperature=0,
    )

    content = response.choices[0].message.content
    return json.loads(content)
  1. Persist the payment event in CosmosDB

Store both the extracted result and the raw message. That gives you traceability when finance teams ask why the agent made a decision.

from datetime import datetime, timezone

def save_payment_event(event: dict) -> dict:
    item = {
        "id": event.get("payer_ref", f"payment-{datetime.now(timezone.utc).timestamp()}"),
        "type": "payment_event",
        "createdAt": datetime.now(timezone.utc).isoformat(),
        "intent": event["intent"],
        "amount": event["amount"],
        "currency": event["currency"],
        "payer_ref": event["payer_ref"],
        "confidence": event["confidence"],
    }

    saved = container.upsert_item(body=item)
    return saved

If your container uses /id as partition key, this works directly. If you use another partition key like /type or /customerId, make sure the item includes that field.

  1. Build a simple end-to-end agent flow

This ties both systems together: extract payment data with Azure OpenAI, then write it to CosmosDB if confidence is high enough.

def process_payment_request(user_message: str) -> dict:
    extracted = extract_payment_details_json(user_message)

    if extracted.get("confidence", 0) < 0.8:
        return {
            "status": "needs_review",
            "reason": "Low confidence from model",
            "extracted": extracted,
        }

    saved = save_payment_event(extracted)

    return {
        "status": "saved",
        "extracted": extracted,
        "cosmos_record_id": saved["id"],
    }

Testing the Integration

Run a quick smoke test with a realistic payment request.

if __name__ == "__main__":
    test_input = "Pay $125.50 to invoice INV-2048 for Acme Supplies"

    result = process_payment_request(test_input)
    print(result)

Expected output:

{
  'status': 'saved',
  'extracted': {
    'intent': 'payment',
    'amount': 125.5,
    'currency': 'USD',
    'payer_ref': 'INV-2048',
    'confidence': 0.94
  },
  'cosmos_record_id': 'INV-2048'
}

If you want to verify persistence directly in CosmosDB:

record = container.read_item(item="INV-2048", partition_key="INV-2048")
print(record)

Real-World Use Cases

  • Payment intake agent
    Parse email or chat instructions into structured payment requests, then store them in CosmosDB for approval workflows.

  • Dispute and reconciliation assistant
    Let users ask about failed or pending payments while the agent fetches transaction history from CosmosDB and explains status using Azure OpenAI.

  • Compliance logging layer
    Save every model decision, extracted field, and human override in CosmosDB so audit teams can trace how each payment instruction was handled.


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