Azure AI foundry-conversation-memory-cosmosDB-blob

extend the persistent memory + conversation lifecycle system so it can integrate directly with an Azure AI Foundry Agent.

This means your multi-turn conversation memory, file state tracking, and cached/non-cached container logic will be available to an Azure AI Foundry Agent for:

  • Context injection into the agentโ€™s reasoning.
  • Tool orchestration (e.g., search, indexing, analytics).
  • Lifecycle-aware responses (knowing which conversations are completed vs in-progress).

Integration Goals

  1. Expose conversation + file state memory to Azure AI Foundry Agent via an API endpoint.
  2. Allow the agent to query Cosmos DB for:
    • Conversations linked to non-cached-container files.
    • Completed conversations.
    • Tool usage history.
  3. Enable the agent to update conversation state when it processes files or uses tools.

Architecture

Copy codeAzure Function (Memory + Sync)
    ↕
Cosmos DB (Persistent Memory)
    ↕
Azure AI Foundry Agent
    ↕
Tools (Azure Search, Blob Storage, MCP)

Step 1 โ€” API Endpoint for Agent

Weโ€™ll expose a REST API from the Azure Function so the Azure AI Foundry Agent can call it.

PythonCopy codefrom flask import Flask, request, jsonify

app = Flask(__name__)

@app.route("/agent/memory/conversations", methods=["GET"])
def get_conversations_for_agent():
    """Return conversations and file states for Azure AI Foundry Agent."""
    status_filter = request.args.get("status")  # optional: 'completed' or 'in-progress'
    try:
        query = "SELECT * FROM c WHERE c.type = 'conversation'"
        if status_filter:
            query += f" AND c.status = '{status_filter}'"

        conversations = list(cosmos_container.query_items(
            query=query,
            enable_cross_partition_query=True
        ))
        return jsonify(conversations), 200
    except Exception as e:
        logging.error(f"Error fetching conversations for agent: {e}")
        return jsonify({"error": str(e)}), 500

@app.route("/agent/memory/files", methods=["GET"])
def get_files_for_agent():
    """Return file states for Azure AI Foundry Agent."""
    container_type = request.args.get("containerType")  # optional: 'cached-container' or 'non-cached-container'
    try:
        query = "SELECT * FROM c WHERE c.type = 'file_state'"
        if container_type:
            query += f" AND c.containerType = '{container_type}'"

        files = list(cosmos_container.query_items(
            query=query,
            enable_cross_partition_query=True
        ))
        return jsonify(files), 200
    except Exception as e:
        logging.error(f"Error fetching files for agent: {e}")
        return jsonify({"error": str(e)}), 500

@app.route("/agent/memory/update", methods=["POST"])
def update_conversation_from_agent():
    """Allow Azure AI Foundry Agent to update conversation state."""
    data = request.json
    doc_id = data.get("doc_id")
    status = data.get("status")
    summary = data.get("summary")
    try:
        items = list(cosmos_container.query_items(
            query="SELECT * FROM c WHERE c.id = @id AND c.type = 'conversation'",
            parameters=[{"name": "@id", "value": doc_id}],
            enable_cross_partition_query=True
        ))
        if not items:
            return jsonify({"error": "Conversation not found"}), 404

        convo = items[0]
        if status:
            convo["status"] = status
        if summary:
            convo["summary"] = summary
        cosmos_container.upsert_item(convo)
        return jsonify({"message": "Conversation updated"}), 200
    except Exception as e:
        logging.error(f"Error updating conversation from agent: {e}")
        return jsonify({"error": str(e)}), 500

Step 2 โ€” Azure AI Foundry Agent Tool Definition

In Azure AI Foundry, you can define a custom tool that calls these endpoints.

Example tool definition in the agentโ€™s config:

JsonCopy code{
  "name": "ConversationMemoryTool",
  "description": "Fetch and update conversation memory from Cosmos DB",
  "endpoint": "https://<your-function-app>.azurewebsites.net/agent/memory/conversations",
  "methods": [
    {
      "name": "get_conversations",
      "description": "Retrieve conversations with optional status filter",
      "parameters": {
        "status": {
          "type": "string",
          "description": "Filter by conversation status (completed or in-progress)"
        }
      }
    },
    {
      "name": "get_files",
      "description": "Retrieve file states with optional containerType filter",
      "parameters": {
        "containerType": {
          "type": "string",
          "description": "Filter by container type (cached-container or non-cached-container)"
        }
      }
    },
    {
      "name": "update_conversation",
      "description": "Update conversation status or summary",
      "parameters": {
        "doc_id": { "type": "string" },
        "status": { "type": "string" },
        "summary": { "type": "string" }
      }
    }
  ]
}

Step 3 โ€” Agent Workflow

When the Azure AI Foundry Agent runs:

  1. Fetch conversations:PythonCopy codeGET /agent/memory/conversations?status=in-progress
  2. Fetch non-cached files:PythonCopy codeGET /agent/memory/files?containerType=non-cached-container
  3. Process files (e.g., run indexing, summarization).
  4. Update conversation status:PythonCopy codePOST /agent/memory/update { "doc_id": "session_2026-10-06T12:30:00Z", "status": "completed", "summary": "All linked files processed and indexed." }

Benefits

  • Direct integration โ€” Azure AI Foundry Agent can query and update memory in real-time.
  • Tool orchestration โ€” Agent can decide which files to process based on conversation state.
  • Lifecycle awareness โ€” Agent knows which conversations are completed vs pending.
  • Persistent context โ€” Agent can recall multi-turn history and tool usage.

If you want, I can extend this further so that the Azure AI Foundry Agent can also trigger the sync process directly via a tool call โ€” meaning it can initiate file processing and indexing without manual intervention.

=====================================================================


Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post