We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Error: Diagnostic settings does not support retention for new diagnostic settings
After a couple of attempts to deploy the PubSec suite (deploy, delete, repeat switching from australia east to eastus), I began to encounter this error 'Diagnostic settings does not support retention for new diagnostic settings.' and the deployment would fail. With each attempt I had deleted all of the services created by the previous attempt, and changed the WORKSPACE="" to be unique. 

I happened to come across this article:
https://learn.microsoft.com/en-us/azure/azure-monitor/essentials/migrate-to-azure-storage-lifecycle-policy

After changing lines 138, 146 and 156 in the main.bicep file, setting the days value to 0 (instead of the default value of 30) the deployment completed successfully. 

based on the information in the article, we'll need to update these setting after September when the deprecation comes into effect.


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `app/backend/app.py`
Content:
```
1 # Copyright (c) Microsoft Corporation.
2 # Licensed under the MIT license.
3 
4 import logging
5 import mimetypes
6 import os
7 import urllib.parse
8 from datetime import datetime, timedelta
9 
10 import openai
11 from approaches.chatreadretrieveread import ChatReadRetrieveReadApproach
12 from azure.core.credentials import AzureKeyCredential
13 from azure.identity import DefaultAzureCredential
14 from azure.search.documents import SearchClient
15 from azure.storage.blob import (
16     AccountSasPermissions,
17     BlobServiceClient,
18     ResourceTypes,
19     generate_account_sas,
20 )
21 from flask import Flask, jsonify, request
22 from shared_code.status_log import State, StatusLog
23 
24 # Replace these with your own values, either in environment variables or directly here
25 AZURE_BLOB_STORAGE_ACCOUNT = (
26     os.environ.get("AZURE_BLOB_STORAGE_ACCOUNT") or "mystorageaccount"
27 )
28 AZURE_BLOB_STORAGE_KEY = os.environ.get("AZURE_BLOB_STORAGE_KEY")
29 AZURE_BLOB_STORAGE_CONTAINER = (
30     os.environ.get("AZURE_BLOB_STORAGE_CONTAINER") or "content"
31 )
32 AZURE_SEARCH_SERVICE = os.environ.get("AZURE_SEARCH_SERVICE") or "gptkb"
33 AZURE_SEARCH_SERVICE_KEY = os.environ.get("AZURE_SEARCH_SERVICE_KEY")
34 AZURE_SEARCH_INDEX = os.environ.get("AZURE_SEARCH_INDEX") or "gptkbindex"
35 AZURE_OPENAI_SERVICE = os.environ.get("AZURE_OPENAI_SERVICE") or "myopenai"
36 AZURE_OPENAI_CHATGPT_DEPLOYMENT = (
37     os.environ.get("AZURE_OPENAI_CHATGPT_DEPLOYMENT") or "chat"
38 )
39 AZURE_OPENAI_SERVICE_KEY = os.environ.get("AZURE_OPENAI_SERVICE_KEY")
40 
41 KB_FIELDS_CONTENT = os.environ.get("KB_FIELDS_CONTENT") or "merged_content"
42 KB_FIELDS_CATEGORY = os.environ.get("KB_FIELDS_CATEGORY") or "category"
43 KB_FIELDS_SOURCEPAGE = os.environ.get("KB_FIELDS_SOURCEPAGE") or "file_storage_path"
44 
45 COSMOSDB_URL = os.environ.get("COSMOSDB_URL")
46 COSMODB_KEY = os.environ.get("COSMOSDB_KEY")
47 COSMOSDB_DATABASE_NAME = os.environ.get("COSMOSDB_DATABASE_NAME") or "statusdb"
48 COSMOSDB_CONTAINER_NAME = os.environ.get("COSMOSDB_CONTAINER_NAME") or "statuscontainer"
49 
50 QUERY_TERM_LANGUAGE = os.environ.get("QUERY_TERM_LANGUAGE") or "English"
51 
52 # Use the current user identity to authenticate with Azure OpenAI, Cognitive Search and Blob Storage (no secrets needed,
53 # just use 'az login' locally, and managed identity when deployed on Azure). If you need to use keys, use separate AzureKeyCredential instances with the
54 # keys for each service
55 # If you encounter a blocking error during a DefaultAzureCredntial resolution, you can exclude the problematic credential by using a parameter (ex. exclude_shared_token_cache_credential=True)
56 azure_credential = DefaultAzureCredential()
57 azure_search_key_credential = AzureKeyCredential(AZURE_SEARCH_SERVICE_KEY)
58 
59 # Used by the OpenAI SDK
60 openai.api_type = "azure"
61 openai.api_base = f"https://{AZURE_OPENAI_SERVICE}.openai.azure.com"
62 openai.api_version = "2023-06-01-preview"
63 
64 # Setup StatusLog to allow access to CosmosDB for logging
65 statusLog = StatusLog(
66     COSMOSDB_URL, COSMODB_KEY, COSMOSDB_DATABASE_NAME, COSMOSDB_CONTAINER_NAME
67 )
68 
69 # Comment these two lines out if using keys, set your API key in the OPENAI_API_KEY environment variable instead
70 # openai.api_type = "azure_ad"
71 # openai_token = azure_credential.get_token("https://cognitiveservices.azure.com/.default")
72 openai.api_key = AZURE_OPENAI_SERVICE_KEY
73 
74 # Set up clients for Cognitive Search and Storage
75 search_client = SearchClient(
76     endpoint=f"https://{AZURE_SEARCH_SERVICE}.search.windows.net",
77     index_name=AZURE_SEARCH_INDEX,
78     credential=azure_search_key_credential,
79 )
80 blob_client = BlobServiceClient(
81     account_url=f"https://{AZURE_BLOB_STORAGE_ACCOUNT}.blob.core.windows.net",
82     credential=AZURE_BLOB_STORAGE_KEY,
83 )
84 blob_container = blob_client.get_container_client(AZURE_BLOB_STORAGE_CONTAINER)
85 
86 
87 chat_approaches = {
88     "rrr": ChatReadRetrieveReadApproach(
89         search_client,
90         AZURE_OPENAI_SERVICE,
91         AZURE_OPENAI_SERVICE_KEY,
92         AZURE_OPENAI_CHATGPT_DEPLOYMENT,
93         KB_FIELDS_SOURCEPAGE,
94         KB_FIELDS_CONTENT,
95         blob_client,
96         QUERY_TERM_LANGUAGE,
97     )
98 }
99 
100 app = Flask(__name__)
101 
102 
103 @app.route("/", defaults={"path": "index.html"})
104 @app.route("/<path:path>")
105 def static_file(path):
106     return app.send_static_file(path)
107 
108 
109 # Return blob path with SAS token for citation access
110 @app.route("/content/<path:path>")
111 def content_file(path):
112     blob = blob_container.get_blob_client(path).download_blob()
113     mime_type = blob.properties["content_settings"]["content_type"]
114     file_extension = blob.properties["name"].split(".")[-1:]
115     if mime_type == "application/octet-stream":
116         mime_type = mimetypes.guess_type(path)[0] or "application/octet-stream"
117     if mime_type == "text/plain" and file_extension[0] in ["htm", "html"]:
118         mime_type = "text/html"
119     print(
120         "Using mime type: "
121         + mime_type
122         + "for file with extension: "
123         + file_extension[0]
124     )
125     return (
126         blob.readall(),
127         200,
128         {
129             "Content-Type": mime_type,
130             "Content-Disposition": f"inline; filename={urllib.parse.quote(path, safe='')}",
131         },
132     )
133 
134 
135 @app.route("/chat", methods=["POST"])
136 def chat():
137     approach = request.json["approach"]
138     try:
139         impl = chat_approaches.get(approach)
140         if not impl:
141             return jsonify({"error": "unknown approach"}), 400
142         r = impl.run(request.json["history"], request.json.get("overrides") or {})
143 
144         # return jsonify(r)
145         # To fix citation bug,below code is added.aparmar
146         return jsonify(
147             {
148                 "data_points": r["data_points"],
149                 "answer": r["answer"],
150                 "thoughts": r["thoughts"],
151                 "citation_lookup": r["citation_lookup"],
152             }
153         )
154 
155     except Exception as e:
156         logging.exception("Exception in /chat")
157         return jsonify({"error": str(e)}), 500
158 
159 
160 @app.route("/getblobclienturl")
161 def get_blob_client_url():
162     sas_token = generate_account_sas(
163         AZURE_BLOB_STORAGE_ACCOUNT,
164         AZURE_BLOB_STORAGE_KEY,
165         resource_types=ResourceTypes(object=True, service=True, container=True),
166         permission=AccountSasPermissions(
167             read=True,
168             write=True,
169             list=True,
170             delete=False,
171             add=True,
172             create=True,
173             update=True,
174             process=False,
175         ),
176         expiry=datetime.utcnow() + timedelta(hours=1),
177     )
178     return jsonify({"url": f"{blob_client.url}?{sas_token}"})
179 
180 
181 if __name__ == "__main__":
182     app.run()
183 
184 
185 @app.route("/getalluploadstatus", methods=["POST"])
186 def get_all_upload_status():
187     timeframe = request.json["timeframe"]
188     state = request.json["state"]
189     try:
190         results = statusLog.read_files_status_by_timeframe(timeframe, State[state])
191     except Exception as e:
192         logging.exception("Exception in /getalluploadstatus")
193         return jsonify({"error": str(e)}), 500
194     return jsonify(results)
195
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/app/backend/app.py b/app/backend/app.py
--- a/app/backend/app.py
+++ b/app/backend/app.py
@@ -192,3 +192,10 @@
         logging.exception("Exception in /getalluploadstatus")
         return jsonify({"error": str(e)}), 500
     return jsonify(results)
+
+
+# Return AZURE_OPENAI_CHATGPT_DEPLOYMENT
+@app.route("/getInfoData")
+def get_info_data():
+    response = jsonify({"AZURE_OPENAI_CHATGPT_DEPLOYMENT": f"{AZURE_OPENAI_CHATGPT_DEPLOYMENT}"})
+    return response
\ No newline at end of file

{"golden_diff": "diff --git a/app/backend/app.py b/app/backend/app.py\n--- a/app/backend/app.py\n+++ b/app/backend/app.py\n@@ -192,3 +192,10 @@\n         logging.exception(\"Exception in /getalluploadstatus\")\n         return jsonify({\"error\": str(e)}), 500\n     return jsonify(results)\n+\n+\n+# Return AZURE_OPENAI_CHATGPT_DEPLOYMENT\n+@app.route(\"/getInfoData\")\n+def get_info_data():\n+    response = jsonify({\"AZURE_OPENAI_CHATGPT_DEPLOYMENT\": f\"{AZURE_OPENAI_CHATGPT_DEPLOYMENT}\"})\n+    return response\n\\ No newline at end of file\n", "issue": "Error: Diagnostic settings does not support retention for new diagnostic settings\nAfter a couple of attempts to deploy the PubSec suite (deploy, delete, repeat switching from australia east to eastus), I began to encounter this error 'Diagnostic settings does not support retention for new diagnostic settings.' and the deployment would fail. With each attempt I had deleted all of the services created by the previous attempt, and changed the WORKSPACE=\"\" to be unique. \r\n\r\nI happened to come across this article:\r\nhttps://learn.microsoft.com/en-us/azure/azure-monitor/essentials/migrate-to-azure-storage-lifecycle-policy\r\n\r\nAfter changing lines 138, 146 and 156 in the main.bicep file, setting the days value to 0 (instead of the default value of 30) the deployment completed successfully. \r\n\r\nbased on the information in the article, we'll need to update these setting after September when the deprecation comes into effect.\r\n\n", "before_files": [{"content": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\nimport logging\nimport mimetypes\nimport os\nimport urllib.parse\nfrom datetime import datetime, timedelta\n\nimport openai\nfrom approaches.chatreadretrieveread import ChatReadRetrieveReadApproach\nfrom azure.core.credentials import AzureKeyCredential\nfrom azure.identity import DefaultAzureCredential\nfrom azure.search.documents import SearchClient\nfrom azure.storage.blob import (\n    AccountSasPermissions,\n    BlobServiceClient,\n    ResourceTypes,\n    generate_account_sas,\n)\nfrom flask import Flask, jsonify, request\nfrom shared_code.status_log import State, StatusLog\n\n# Replace these with your own values, either in environment variables or directly here\nAZURE_BLOB_STORAGE_ACCOUNT = (\n    os.environ.get(\"AZURE_BLOB_STORAGE_ACCOUNT\") or \"mystorageaccount\"\n)\nAZURE_BLOB_STORAGE_KEY = os.environ.get(\"AZURE_BLOB_STORAGE_KEY\")\nAZURE_BLOB_STORAGE_CONTAINER = (\n    os.environ.get(\"AZURE_BLOB_STORAGE_CONTAINER\") or \"content\"\n)\nAZURE_SEARCH_SERVICE = os.environ.get(\"AZURE_SEARCH_SERVICE\") or \"gptkb\"\nAZURE_SEARCH_SERVICE_KEY = os.environ.get(\"AZURE_SEARCH_SERVICE_KEY\")\nAZURE_SEARCH_INDEX = os.environ.get(\"AZURE_SEARCH_INDEX\") or \"gptkbindex\"\nAZURE_OPENAI_SERVICE = os.environ.get(\"AZURE_OPENAI_SERVICE\") or \"myopenai\"\nAZURE_OPENAI_CHATGPT_DEPLOYMENT = (\n    os.environ.get(\"AZURE_OPENAI_CHATGPT_DEPLOYMENT\") or \"chat\"\n)\nAZURE_OPENAI_SERVICE_KEY = os.environ.get(\"AZURE_OPENAI_SERVICE_KEY\")\n\nKB_FIELDS_CONTENT = os.environ.get(\"KB_FIELDS_CONTENT\") or \"merged_content\"\nKB_FIELDS_CATEGORY = os.environ.get(\"KB_FIELDS_CATEGORY\") or \"category\"\nKB_FIELDS_SOURCEPAGE = os.environ.get(\"KB_FIELDS_SOURCEPAGE\") or \"file_storage_path\"\n\nCOSMOSDB_URL = os.environ.get(\"COSMOSDB_URL\")\nCOSMODB_KEY = os.environ.get(\"COSMOSDB_KEY\")\nCOSMOSDB_DATABASE_NAME = os.environ.get(\"COSMOSDB_DATABASE_NAME\") or \"statusdb\"\nCOSMOSDB_CONTAINER_NAME = os.environ.get(\"COSMOSDB_CONTAINER_NAME\") or \"statuscontainer\"\n\nQUERY_TERM_LANGUAGE = os.environ.get(\"QUERY_TERM_LANGUAGE\") or \"English\"\n\n# Use the current user identity to authenticate with Azure OpenAI, Cognitive Search and Blob Storage (no secrets needed,\n# just use 'az login' locally, and managed identity when deployed on Azure). If you need to use keys, use separate AzureKeyCredential instances with the\n# keys for each service\n# If you encounter a blocking error during a DefaultAzureCredntial resolution, you can exclude the problematic credential by using a parameter (ex. exclude_shared_token_cache_credential=True)\nazure_credential = DefaultAzureCredential()\nazure_search_key_credential = AzureKeyCredential(AZURE_SEARCH_SERVICE_KEY)\n\n# Used by the OpenAI SDK\nopenai.api_type = \"azure\"\nopenai.api_base = f\"https://{AZURE_OPENAI_SERVICE}.openai.azure.com\"\nopenai.api_version = \"2023-06-01-preview\"\n\n# Setup StatusLog to allow access to CosmosDB for logging\nstatusLog = StatusLog(\n    COSMOSDB_URL, COSMODB_KEY, COSMOSDB_DATABASE_NAME, COSMOSDB_CONTAINER_NAME\n)\n\n# Comment these two lines out if using keys, set your API key in the OPENAI_API_KEY environment variable instead\n# openai.api_type = \"azure_ad\"\n# openai_token = azure_credential.get_token(\"https://cognitiveservices.azure.com/.default\")\nopenai.api_key = AZURE_OPENAI_SERVICE_KEY\n\n# Set up clients for Cognitive Search and Storage\nsearch_client = SearchClient(\n    endpoint=f\"https://{AZURE_SEARCH_SERVICE}.search.windows.net\",\n    index_name=AZURE_SEARCH_INDEX,\n    credential=azure_search_key_credential,\n)\nblob_client = BlobServiceClient(\n    account_url=f\"https://{AZURE_BLOB_STORAGE_ACCOUNT}.blob.core.windows.net\",\n    credential=AZURE_BLOB_STORAGE_KEY,\n)\nblob_container = blob_client.get_container_client(AZURE_BLOB_STORAGE_CONTAINER)\n\n\nchat_approaches = {\n    \"rrr\": ChatReadRetrieveReadApproach(\n        search_client,\n        AZURE_OPENAI_SERVICE,\n        AZURE_OPENAI_SERVICE_KEY,\n        AZURE_OPENAI_CHATGPT_DEPLOYMENT,\n        KB_FIELDS_SOURCEPAGE,\n        KB_FIELDS_CONTENT,\n        blob_client,\n        QUERY_TERM_LANGUAGE,\n    )\n}\n\napp = Flask(__name__)\n\n\n@app.route(\"/\", defaults={\"path\": \"index.html\"})\n@app.route(\"/<path:path>\")\ndef static_file(path):\n    return app.send_static_file(path)\n\n\n# Return blob path with SAS token for citation access\n@app.route(\"/content/<path:path>\")\ndef content_file(path):\n    blob = blob_container.get_blob_client(path).download_blob()\n    mime_type = blob.properties[\"content_settings\"][\"content_type\"]\n    file_extension = blob.properties[\"name\"].split(\".\")[-1:]\n    if mime_type == \"application/octet-stream\":\n        mime_type = mimetypes.guess_type(path)[0] or \"application/octet-stream\"\n    if mime_type == \"text/plain\" and file_extension[0] in [\"htm\", \"html\"]:\n        mime_type = \"text/html\"\n    print(\n        \"Using mime type: \"\n        + mime_type\n        + \"for file with extension: \"\n        + file_extension[0]\n    )\n    return (\n        blob.readall(),\n        200,\n        {\n            \"Content-Type\": mime_type,\n            \"Content-Disposition\": f\"inline; filename={urllib.parse.quote(path, safe='')}\",\n        },\n    )\n\n\n@app.route(\"/chat\", methods=[\"POST\"])\ndef chat():\n    approach = request.json[\"approach\"]\n    try:\n        impl = chat_approaches.get(approach)\n        if not impl:\n            return jsonify({\"error\": \"unknown approach\"}), 400\n        r = impl.run(request.json[\"history\"], request.json.get(\"overrides\") or {})\n\n        # return jsonify(r)\n        # To fix citation bug,below code is added.aparmar\n        return jsonify(\n            {\n                \"data_points\": r[\"data_points\"],\n                \"answer\": r[\"answer\"],\n                \"thoughts\": r[\"thoughts\"],\n                \"citation_lookup\": r[\"citation_lookup\"],\n            }\n        )\n\n    except Exception as e:\n        logging.exception(\"Exception in /chat\")\n        return jsonify({\"error\": str(e)}), 500\n\n\n@app.route(\"/getblobclienturl\")\ndef get_blob_client_url():\n    sas_token = generate_account_sas(\n        AZURE_BLOB_STORAGE_ACCOUNT,\n        AZURE_BLOB_STORAGE_KEY,\n        resource_types=ResourceTypes(object=True, service=True, container=True),\n        permission=AccountSasPermissions(\n            read=True,\n            write=True,\n            list=True,\n            delete=False,\n            add=True,\n            create=True,\n            update=True,\n            process=False,\n        ),\n        expiry=datetime.utcnow() + timedelta(hours=1),\n    )\n    return jsonify({\"url\": f\"{blob_client.url}?{sas_token}\"})\n\n\nif __name__ == \"__main__\":\n    app.run()\n\n\n@app.route(\"/getalluploadstatus\", methods=[\"POST\"])\ndef get_all_upload_status():\n    timeframe = request.json[\"timeframe\"]\n    state = request.json[\"state\"]\n    try:\n        results = statusLog.read_files_status_by_timeframe(timeframe, State[state])\n    except Exception as e:\n        logging.exception(\"Exception in /getalluploadstatus\")\n        return jsonify({\"error\": str(e)}), 500\n    return jsonify(results)\n", "path": "app/backend/app.py"}], "after_files": [{"content": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\nimport logging\nimport mimetypes\nimport os\nimport urllib.parse\nfrom datetime import datetime, timedelta\n\nimport openai\nfrom approaches.chatreadretrieveread import ChatReadRetrieveReadApproach\nfrom azure.core.credentials import AzureKeyCredential\nfrom azure.identity import DefaultAzureCredential\nfrom azure.search.documents import SearchClient\nfrom azure.storage.blob import (\n    AccountSasPermissions,\n    BlobServiceClient,\n    ResourceTypes,\n    generate_account_sas,\n)\nfrom flask import Flask, jsonify, request\nfrom shared_code.status_log import State, StatusLog\n\n# Replace these with your own values, either in environment variables or directly here\nAZURE_BLOB_STORAGE_ACCOUNT = (\n    os.environ.get(\"AZURE_BLOB_STORAGE_ACCOUNT\") or \"mystorageaccount\"\n)\nAZURE_BLOB_STORAGE_KEY = os.environ.get(\"AZURE_BLOB_STORAGE_KEY\")\nAZURE_BLOB_STORAGE_CONTAINER = (\n    os.environ.get(\"AZURE_BLOB_STORAGE_CONTAINER\") or \"content\"\n)\nAZURE_SEARCH_SERVICE = os.environ.get(\"AZURE_SEARCH_SERVICE\") or \"gptkb\"\nAZURE_SEARCH_SERVICE_KEY = os.environ.get(\"AZURE_SEARCH_SERVICE_KEY\")\nAZURE_SEARCH_INDEX = os.environ.get(\"AZURE_SEARCH_INDEX\") or \"gptkbindex\"\nAZURE_OPENAI_SERVICE = os.environ.get(\"AZURE_OPENAI_SERVICE\") or \"myopenai\"\nAZURE_OPENAI_CHATGPT_DEPLOYMENT = (\n    os.environ.get(\"AZURE_OPENAI_CHATGPT_DEPLOYMENT\") or \"chat\"\n)\nAZURE_OPENAI_SERVICE_KEY = os.environ.get(\"AZURE_OPENAI_SERVICE_KEY\")\n\nKB_FIELDS_CONTENT = os.environ.get(\"KB_FIELDS_CONTENT\") or \"merged_content\"\nKB_FIELDS_CATEGORY = os.environ.get(\"KB_FIELDS_CATEGORY\") or \"category\"\nKB_FIELDS_SOURCEPAGE = os.environ.get(\"KB_FIELDS_SOURCEPAGE\") or \"file_storage_path\"\n\nCOSMOSDB_URL = os.environ.get(\"COSMOSDB_URL\")\nCOSMODB_KEY = os.environ.get(\"COSMOSDB_KEY\")\nCOSMOSDB_DATABASE_NAME = os.environ.get(\"COSMOSDB_DATABASE_NAME\") or \"statusdb\"\nCOSMOSDB_CONTAINER_NAME = os.environ.get(\"COSMOSDB_CONTAINER_NAME\") or \"statuscontainer\"\n\nQUERY_TERM_LANGUAGE = os.environ.get(\"QUERY_TERM_LANGUAGE\") or \"English\"\n\n# Use the current user identity to authenticate with Azure OpenAI, Cognitive Search and Blob Storage (no secrets needed,\n# just use 'az login' locally, and managed identity when deployed on Azure). If you need to use keys, use separate AzureKeyCredential instances with the\n# keys for each service\n# If you encounter a blocking error during a DefaultAzureCredntial resolution, you can exclude the problematic credential by using a parameter (ex. exclude_shared_token_cache_credential=True)\nazure_credential = DefaultAzureCredential()\nazure_search_key_credential = AzureKeyCredential(AZURE_SEARCH_SERVICE_KEY)\n\n# Used by the OpenAI SDK\nopenai.api_type = \"azure\"\nopenai.api_base = f\"https://{AZURE_OPENAI_SERVICE}.openai.azure.com\"\nopenai.api_version = \"2023-06-01-preview\"\n\n# Setup StatusLog to allow access to CosmosDB for logging\nstatusLog = StatusLog(\n    COSMOSDB_URL, COSMODB_KEY, COSMOSDB_DATABASE_NAME, COSMOSDB_CONTAINER_NAME\n)\n\n# Comment these two lines out if using keys, set your API key in the OPENAI_API_KEY environment variable instead\n# openai.api_type = \"azure_ad\"\n# openai_token = azure_credential.get_token(\"https://cognitiveservices.azure.com/.default\")\nopenai.api_key = AZURE_OPENAI_SERVICE_KEY\n\n# Set up clients for Cognitive Search and Storage\nsearch_client = SearchClient(\n    endpoint=f\"https://{AZURE_SEARCH_SERVICE}.search.windows.net\",\n    index_name=AZURE_SEARCH_INDEX,\n    credential=azure_search_key_credential,\n)\nblob_client = BlobServiceClient(\n    account_url=f\"https://{AZURE_BLOB_STORAGE_ACCOUNT}.blob.core.windows.net\",\n    credential=AZURE_BLOB_STORAGE_KEY,\n)\nblob_container = blob_client.get_container_client(AZURE_BLOB_STORAGE_CONTAINER)\n\n\nchat_approaches = {\n    \"rrr\": ChatReadRetrieveReadApproach(\n        search_client,\n        AZURE_OPENAI_SERVICE,\n        AZURE_OPENAI_SERVICE_KEY,\n        AZURE_OPENAI_CHATGPT_DEPLOYMENT,\n        KB_FIELDS_SOURCEPAGE,\n        KB_FIELDS_CONTENT,\n        blob_client,\n        QUERY_TERM_LANGUAGE,\n    )\n}\n\napp = Flask(__name__)\n\n\n@app.route(\"/\", defaults={\"path\": \"index.html\"})\n@app.route(\"/<path:path>\")\ndef static_file(path):\n    return app.send_static_file(path)\n\n\n# Return blob path with SAS token for citation access\n@app.route(\"/content/<path:path>\")\ndef content_file(path):\n    blob = blob_container.get_blob_client(path).download_blob()\n    mime_type = blob.properties[\"content_settings\"][\"content_type\"]\n    file_extension = blob.properties[\"name\"].split(\".\")[-1:]\n    if mime_type == \"application/octet-stream\":\n        mime_type = mimetypes.guess_type(path)[0] or \"application/octet-stream\"\n    if mime_type == \"text/plain\" and file_extension[0] in [\"htm\", \"html\"]:\n        mime_type = \"text/html\"\n    print(\n        \"Using mime type: \"\n        + mime_type\n        + \"for file with extension: \"\n        + file_extension[0]\n    )\n    return (\n        blob.readall(),\n        200,\n        {\n            \"Content-Type\": mime_type,\n            \"Content-Disposition\": f\"inline; filename={urllib.parse.quote(path, safe='')}\",\n        },\n    )\n\n\n@app.route(\"/chat\", methods=[\"POST\"])\ndef chat():\n    approach = request.json[\"approach\"]\n    try:\n        impl = chat_approaches.get(approach)\n        if not impl:\n            return jsonify({\"error\": \"unknown approach\"}), 400\n        r = impl.run(request.json[\"history\"], request.json.get(\"overrides\") or {})\n\n        # return jsonify(r)\n        # To fix citation bug,below code is added.aparmar\n        return jsonify(\n            {\n                \"data_points\": r[\"data_points\"],\n                \"answer\": r[\"answer\"],\n                \"thoughts\": r[\"thoughts\"],\n                \"citation_lookup\": r[\"citation_lookup\"],\n            }\n        )\n\n    except Exception as e:\n        logging.exception(\"Exception in /chat\")\n        return jsonify({\"error\": str(e)}), 500\n\n\n@app.route(\"/getblobclienturl\")\ndef get_blob_client_url():\n    sas_token = generate_account_sas(\n        AZURE_BLOB_STORAGE_ACCOUNT,\n        AZURE_BLOB_STORAGE_KEY,\n        resource_types=ResourceTypes(object=True, service=True, container=True),\n        permission=AccountSasPermissions(\n            read=True,\n            write=True,\n            list=True,\n            delete=False,\n            add=True,\n            create=True,\n            update=True,\n            process=False,\n        ),\n        expiry=datetime.utcnow() + timedelta(hours=1),\n    )\n    return jsonify({\"url\": f\"{blob_client.url}?{sas_token}\"})\n\n\nif __name__ == \"__main__\":\n    app.run()\n\n\n@app.route(\"/getalluploadstatus\", methods=[\"POST\"])\ndef get_all_upload_status():\n    timeframe = request.json[\"timeframe\"]\n    state = request.json[\"state\"]\n    try:\n        results = statusLog.read_files_status_by_timeframe(timeframe, State[state])\n    except Exception as e:\n        logging.exception(\"Exception in /getalluploadstatus\")\n        return jsonify({\"error\": str(e)}), 500\n    return jsonify(results)\n\n\n# Return AZURE_OPENAI_CHATGPT_DEPLOYMENT\n@app.route(\"/getInfoData\")\ndef get_info_data():\n    response = jsonify({\"AZURE_OPENAI_CHATGPT_DEPLOYMENT\": f\"{AZURE_OPENAI_CHATGPT_DEPLOYMENT}\"})\n    return response", "path": "app/backend/app.py"}]}