|
| 1 | +import os |
| 2 | +import time |
| 3 | +from typing import Any, Dict, Union |
| 4 | + |
| 5 | +from azure.cosmos.aio import ContainerProxy, CosmosClient |
| 6 | +from azure.identity.aio import AzureDeveloperCliCredential, ManagedIdentityCredential |
| 7 | +from quart import Blueprint, current_app, jsonify, request |
| 8 | + |
| 9 | +from config import ( |
| 10 | + CONFIG_CHAT_HISTORY_COSMOS_ENABLED, |
| 11 | + CONFIG_COSMOS_HISTORY_CLIENT, |
| 12 | + CONFIG_COSMOS_HISTORY_CONTAINER, |
| 13 | + CONFIG_CREDENTIAL, |
| 14 | +) |
| 15 | +from decorators import authenticated |
| 16 | +from error import error_response |
| 17 | + |
| 18 | +chat_history_cosmosdb_bp = Blueprint("chat_history_cosmos", __name__, static_folder="static") |
| 19 | + |
| 20 | + |
| 21 | +@chat_history_cosmosdb_bp.post("/chat_history") |
| 22 | +@authenticated |
| 23 | +async def post_chat_history(auth_claims: Dict[str, Any]): |
| 24 | + if not current_app.config[CONFIG_CHAT_HISTORY_COSMOS_ENABLED]: |
| 25 | + return jsonify({"error": "Chat history not enabled"}), 400 |
| 26 | + |
| 27 | + container: ContainerProxy = current_app.config[CONFIG_COSMOS_HISTORY_CONTAINER] |
| 28 | + if not container: |
| 29 | + return jsonify({"error": "Chat history not enabled"}), 400 |
| 30 | + |
| 31 | + entra_oid = auth_claims.get("oid") |
| 32 | + if not entra_oid: |
| 33 | + return jsonify({"error": "User OID not found"}), 401 |
| 34 | + |
| 35 | + try: |
| 36 | + request_json = await request.get_json() |
| 37 | + id = request_json.get("id") |
| 38 | + answers = request_json.get("answers") |
| 39 | + title = answers[0][0][:50] + "..." if len(answers[0][0]) > 50 else answers[0][0] |
| 40 | + timestamp = int(time.time() * 1000) |
| 41 | + |
| 42 | + await container.upsert_item( |
| 43 | + {"id": id, "entra_oid": entra_oid, "title": title, "answers": answers, "timestamp": timestamp} |
| 44 | + ) |
| 45 | + |
| 46 | + return jsonify({}), 201 |
| 47 | + except Exception as error: |
| 48 | + return error_response(error, "/chat_history") |
| 49 | + |
| 50 | + |
| 51 | +@chat_history_cosmosdb_bp.post("/chat_history/items") |
| 52 | +@authenticated |
| 53 | +async def get_chat_history(auth_claims: Dict[str, Any]): |
| 54 | + if not current_app.config[CONFIG_CHAT_HISTORY_COSMOS_ENABLED]: |
| 55 | + return jsonify({"error": "Chat history not enabled"}), 400 |
| 56 | + |
| 57 | + container: ContainerProxy = current_app.config[CONFIG_COSMOS_HISTORY_CONTAINER] |
| 58 | + if not container: |
| 59 | + return jsonify({"error": "Chat history not enabled"}), 400 |
| 60 | + |
| 61 | + entra_oid = auth_claims.get("oid") |
| 62 | + if not entra_oid: |
| 63 | + return jsonify({"error": "User OID not found"}), 401 |
| 64 | + |
| 65 | + try: |
| 66 | + request_json = await request.get_json() |
| 67 | + count = request_json.get("count", 20) |
| 68 | + continuation_token = request_json.get("continuation_token") |
| 69 | + |
| 70 | + res = container.query_items( |
| 71 | + query="SELECT c.id, c.entra_oid, c.title, c.timestamp FROM c WHERE c.entra_oid = @entra_oid ORDER BY c.timestamp DESC", |
| 72 | + parameters=[dict(name="@entra_oid", value=entra_oid)], |
| 73 | + max_item_count=count, |
| 74 | + ) |
| 75 | + |
| 76 | + # set the continuation token for the next page |
| 77 | + pager = res.by_page(continuation_token) |
| 78 | + |
| 79 | + # Get the first page, and the continuation token |
| 80 | + try: |
| 81 | + page = await pager.__anext__() |
| 82 | + continuation_token = pager.continuation_token # type: ignore |
| 83 | + |
| 84 | + items = [] |
| 85 | + async for item in page: |
| 86 | + items.append( |
| 87 | + { |
| 88 | + "id": item.get("id"), |
| 89 | + "entra_oid": item.get("entra_oid"), |
| 90 | + "title": item.get("title", "untitled"), |
| 91 | + "timestamp": item.get("timestamp"), |
| 92 | + } |
| 93 | + ) |
| 94 | + |
| 95 | + # If there are no more pages, StopAsyncIteration is raised |
| 96 | + except StopAsyncIteration: |
| 97 | + items = [] |
| 98 | + continuation_token = None |
| 99 | + |
| 100 | + return jsonify({"items": items, "continuation_token": continuation_token}), 200 |
| 101 | + |
| 102 | + except Exception as error: |
| 103 | + return error_response(error, "/chat_history/items") |
| 104 | + |
| 105 | + |
| 106 | +@chat_history_cosmosdb_bp.get("/chat_history/items/<item_id>") |
| 107 | +@authenticated |
| 108 | +async def get_chat_history_session(auth_claims: Dict[str, Any], item_id: str): |
| 109 | + if not current_app.config[CONFIG_CHAT_HISTORY_COSMOS_ENABLED]: |
| 110 | + return jsonify({"error": "Chat history not enabled"}), 400 |
| 111 | + |
| 112 | + container: ContainerProxy = current_app.config[CONFIG_COSMOS_HISTORY_CONTAINER] |
| 113 | + if not container: |
| 114 | + return jsonify({"error": "Chat history not enabled"}), 400 |
| 115 | + |
| 116 | + entra_oid = auth_claims.get("oid") |
| 117 | + if not entra_oid: |
| 118 | + return jsonify({"error": "User OID not found"}), 401 |
| 119 | + |
| 120 | + try: |
| 121 | + res = await container.read_item(item=item_id, partition_key=entra_oid) |
| 122 | + return ( |
| 123 | + jsonify( |
| 124 | + { |
| 125 | + "id": res.get("id"), |
| 126 | + "entra_oid": res.get("entra_oid"), |
| 127 | + "title": res.get("title", "untitled"), |
| 128 | + "timestamp": res.get("timestamp"), |
| 129 | + "answers": res.get("answers", []), |
| 130 | + } |
| 131 | + ), |
| 132 | + 200, |
| 133 | + ) |
| 134 | + except Exception as error: |
| 135 | + return error_response(error, f"/chat_history/items/{item_id}") |
| 136 | + |
| 137 | + |
| 138 | +@chat_history_cosmosdb_bp.delete("/chat_history/items/<item_id>") |
| 139 | +@authenticated |
| 140 | +async def delete_chat_history_session(auth_claims: Dict[str, Any], item_id: str): |
| 141 | + if not current_app.config[CONFIG_CHAT_HISTORY_COSMOS_ENABLED]: |
| 142 | + return jsonify({"error": "Chat history not enabled"}), 400 |
| 143 | + |
| 144 | + container: ContainerProxy = current_app.config[CONFIG_COSMOS_HISTORY_CONTAINER] |
| 145 | + if not container: |
| 146 | + return jsonify({"error": "Chat history not enabled"}), 400 |
| 147 | + |
| 148 | + entra_oid = auth_claims.get("oid") |
| 149 | + if not entra_oid: |
| 150 | + return jsonify({"error": "User OID not found"}), 401 |
| 151 | + |
| 152 | + try: |
| 153 | + await container.delete_item(item=item_id, partition_key=entra_oid) |
| 154 | + return jsonify({}), 204 |
| 155 | + except Exception as error: |
| 156 | + return error_response(error, f"/chat_history/items/{item_id}") |
| 157 | + |
| 158 | + |
| 159 | +@chat_history_cosmosdb_bp.before_app_serving |
| 160 | +async def setup_clients(): |
| 161 | + USE_CHAT_HISTORY_COSMOS = os.getenv("USE_CHAT_HISTORY_COSMOS", "").lower() == "true" |
| 162 | + AZURE_COSMOSDB_ACCOUNT = os.getenv("AZURE_COSMOSDB_ACCOUNT") |
| 163 | + AZURE_CHAT_HISTORY_DATABASE = os.getenv("AZURE_CHAT_HISTORY_DATABASE") |
| 164 | + AZURE_CHAT_HISTORY_CONTAINER = os.getenv("AZURE_CHAT_HISTORY_CONTAINER") |
| 165 | + |
| 166 | + azure_credential: Union[AzureDeveloperCliCredential, ManagedIdentityCredential] = current_app.config[ |
| 167 | + CONFIG_CREDENTIAL |
| 168 | + ] |
| 169 | + |
| 170 | + if USE_CHAT_HISTORY_COSMOS: |
| 171 | + current_app.logger.info("USE_CHAT_HISTORY_COSMOS is true, setting up CosmosDB client") |
| 172 | + if not AZURE_COSMOSDB_ACCOUNT: |
| 173 | + raise ValueError("AZURE_COSMOSDB_ACCOUNT must be set when USE_CHAT_HISTORY_COSMOS is true") |
| 174 | + if not AZURE_CHAT_HISTORY_DATABASE: |
| 175 | + raise ValueError("AZURE_CHAT_HISTORY_DATABASE must be set when USE_CHAT_HISTORY_COSMOS is true") |
| 176 | + if not AZURE_CHAT_HISTORY_CONTAINER: |
| 177 | + raise ValueError("AZURE_CHAT_HISTORY_CONTAINER must be set when USE_CHAT_HISTORY_COSMOS is true") |
| 178 | + cosmos_client = CosmosClient( |
| 179 | + url=f"https://{AZURE_COSMOSDB_ACCOUNT}.documents.azure.com:443/", credential=azure_credential |
| 180 | + ) |
| 181 | + cosmos_db = cosmos_client.get_database_client(AZURE_CHAT_HISTORY_DATABASE) |
| 182 | + cosmos_container = cosmos_db.get_container_client(AZURE_CHAT_HISTORY_CONTAINER) |
| 183 | + |
| 184 | + current_app.config[CONFIG_COSMOS_HISTORY_CLIENT] = cosmos_client |
| 185 | + current_app.config[CONFIG_COSMOS_HISTORY_CONTAINER] = cosmos_container |
| 186 | + |
| 187 | + |
| 188 | +@chat_history_cosmosdb_bp.after_app_serving |
| 189 | +async def close_clients(): |
| 190 | + if current_app.config.get(CONFIG_COSMOS_HISTORY_CLIENT): |
| 191 | + cosmos_client: CosmosClient = current_app.config[CONFIG_COSMOS_HISTORY_CLIENT] |
| 192 | + await cosmos_client.close() |
0 commit comments