-
Notifications
You must be signed in to change notification settings - Fork 627
Expand file tree
/
Copy pathcreate_app.py
More file actions
783 lines (679 loc) · 31.8 KB
/
create_app.py
File metadata and controls
783 lines (679 loc) · 31.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
"""
This module creates a Flask app that serves the web interface for the chatbot.
"""
import contextvars
import functools
import json
import logging
import mimetypes
from os import path
import sys
import re
from urllib.parse import quote, unquote
import requests
from openai import AzureOpenAI, Stream, APIStatusError
from openai.types.chat import ChatCompletionChunk
from flask import Flask, Response, request, Request, jsonify
from dotenv import load_dotenv
from backend.batch.utilities.helpers.env_helper import EnvHelper
from backend.batch.utilities.helpers.azure_search_helper import AzureSearchHelper
from backend.batch.utilities.helpers.orchestrator_helper import Orchestrator
from backend.batch.utilities.helpers.config.config_helper import ConfigHelper
from backend.batch.utilities.helpers.config.conversation_flow import ConversationFlow
from backend.batch.utilities.helpers.prompt_utils import get_current_date_suffix
from backend.api.chat_history import bp_chat_history_response
from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient
from azure.core.exceptions import ClientAuthenticationError, ResourceNotFoundError, ServiceRequestError
from backend.batch.utilities.helpers.azure_credential_utils import get_azure_credential
from backend.batch.utilities.helpers.azure_blob_storage_client import (
AzureBlobStorageClient,
)
from backend.batch.utilities.loggers.event_utils import track_event_if_configured
from backend.batch.utilities.chat_history.auth_utils import get_authenticated_user_details
from opentelemetry import trace
from opentelemetry.sdk.trace import SpanProcessor
_conversation_id_var: contextvars.ContextVar[str] = contextvars.ContextVar("conversation_id", default="")
_user_id_var: contextvars.ContextVar[str] = contextvars.ContextVar("user_id", default="")
class ConversationSpanProcessor(SpanProcessor):
"""Attaches conversation_id and user_id to every span created during a request."""
def on_start(self, span, parent_context=None):
conversation_id = _conversation_id_var.get()
user_id = _user_id_var.get()
if conversation_id:
span.set_attribute("conversation_id", conversation_id)
if user_id:
span.set_attribute("user_id", user_id)
ERROR_429_MESSAGE = "We're currently experiencing a high number of requests for the service you're trying to access. Please wait a moment and try again."
ERROR_GENERIC_MESSAGE = "An error occurred. Please try again. If the problem persists, please contact the site administrator."
logger = logging.getLogger(__name__)
def get_markdown_url(source, title, container_sas):
"""Get Markdown URL for a citation"""
url = quote(source, safe=":/")
if "_SAS_TOKEN_PLACEHOLDER_" in url:
url = url.replace("_SAS_TOKEN_PLACEHOLDER_", container_sas)
return f"[{title}]({url})"
def get_citations(citation_list):
"""Returns Formated Citations."""
logger.info("Method get_citations started")
blob_client = AzureBlobStorageClient()
container_sas = blob_client.get_container_sas()
citations_dict = {"citations": []}
for citation in citation_list.get("citations"):
metadata = (
json.loads(citation["url"])
if isinstance(citation["url"], str)
else citation["url"]
)
title = citation["title"]
source = metadata["source"]
if "_SAS_TOKEN_PLACEHOLDER_" not in source:
source += "_SAS_TOKEN_PLACEHOLDER_"
url = get_markdown_url(source, title, container_sas)
citations_dict["citations"].append(
{
"content": url + "\n\n\n" + citation["content"],
"id": metadata["id"],
"chunk_id": (
re.findall(r"\d+", metadata["chunk_id"])[-1]
if metadata.get("chunk_id") is not None
else metadata["chunk"]
),
"title": title,
"filepath": title.split("/")[-1],
"url": url,
}
)
logger.info("Method get_citations ended")
return citations_dict
def should_use_data(
env_helper: EnvHelper, azure_search_helper: AzureSearchHelper
) -> bool:
if (
env_helper.AZURE_SEARCH_SERVICE
and env_helper.AZURE_SEARCH_INDEX
and (env_helper.AZURE_SEARCH_KEY or env_helper.AZURE_AUTH_TYPE == "rbac")
and not azure_search_helper._index_not_exists(env_helper.AZURE_SEARCH_INDEX)
):
return True
return False
def stream_with_data(response: Stream[ChatCompletionChunk]):
"""This function streams the response from Azure OpenAI with data."""
response_obj = {
"id": "",
"model": "",
"created": 0,
"object": "",
"choices": [
{
"messages": [
{
"content": "",
"end_turn": False,
"role": "tool",
},
{
"content": "",
"end_turn": False,
"role": "assistant",
},
]
}
],
}
for line in response:
choice = line.choices[0]
if choice.model_extra["end_turn"]:
response_obj["choices"][0]["messages"][1]["end_turn"] = True
yield json.dumps(response_obj, ensure_ascii=False) + "\n"
return
response_obj["id"] = line.id
response_obj["model"] = line.model
response_obj["created"] = line.created
response_obj["object"] = line.object
delta = choice.delta
role = delta.role
if role == "assistant":
citations = get_citations(delta.model_extra["context"])
response_obj["choices"][0]["messages"][0]["content"] = json.dumps(
citations,
ensure_ascii=False,
)
else:
response_obj["choices"][0]["messages"][1]["content"] += delta.content
yield json.dumps(response_obj, ensure_ascii=False) + "\n"
def conversation_with_data(conversation: Request, env_helper: EnvHelper):
"""This function streams the response from Azure OpenAI with data."""
logger.info("Method conversation_with_data started")
if env_helper.is_auth_type_keys():
logger.info("Using key-based authentication for Azure OpenAI")
openai_client = AzureOpenAI(
azure_endpoint=env_helper.AZURE_OPENAI_ENDPOINT,
api_version=env_helper.AZURE_OPENAI_API_VERSION,
api_key=env_helper.AZURE_OPENAI_API_KEY,
)
else:
logger.info("Using RBAC authentication for Azure OpenAI")
openai_client = AzureOpenAI(
azure_endpoint=env_helper.AZURE_OPENAI_ENDPOINT,
api_version=env_helper.AZURE_OPENAI_API_VERSION,
azure_ad_token_provider=env_helper.AZURE_TOKEN_PROVIDER,
)
request_messages = conversation.json["messages"]
messages = []
config = ConfigHelper.get_active_config_or_default()
date_suffix = get_current_date_suffix()
if config.prompts.use_on_your_data_format:
messages.append(
{"role": "system", "content": config.prompts.answering_system_prompt + date_suffix}
)
for message in request_messages:
messages.append({"role": message["role"], "content": message["content"]})
# Azure OpenAI takes the deployment name as the model name, "AZURE_OPENAI_MODEL" means
# deployment name.
response = openai_client.chat.completions.create(
model=env_helper.AZURE_OPENAI_MODEL,
messages=messages,
temperature=float(env_helper.AZURE_OPENAI_TEMPERATURE),
max_tokens=int(env_helper.AZURE_OPENAI_MAX_TOKENS),
top_p=float(env_helper.AZURE_OPENAI_TOP_P),
stop=(
env_helper.AZURE_OPENAI_STOP_SEQUENCE.split("|")
if env_helper.AZURE_OPENAI_STOP_SEQUENCE
else None
),
stream=env_helper.SHOULD_STREAM,
extra_body={
"data_sources": [
{
"type": "azure_search",
"parameters": {
"authentication": (
{
"type": "api_key",
"key": env_helper.AZURE_SEARCH_KEY,
}
if env_helper.is_auth_type_keys()
else {
"type": "user_assigned_managed_identity",
"managed_identity_resource_id": env_helper.MANAGED_IDENTITY_RESOURCE_ID,
}
),
"endpoint": env_helper.AZURE_SEARCH_SERVICE,
"index_name": env_helper.AZURE_SEARCH_INDEX,
"fields_mapping": {
"content_fields": (
env_helper.AZURE_SEARCH_CONTENT_COLUMN.split("|")
if env_helper.AZURE_SEARCH_CONTENT_COLUMN
else []
),
"vector_fields": [
env_helper.AZURE_SEARCH_CONTENT_VECTOR_COLUMN
],
"title_field": env_helper.AZURE_SEARCH_TITLE_COLUMN or None,
"url_field": env_helper.AZURE_SEARCH_FIELDS_METADATA
or None,
"filepath_field": (
env_helper.AZURE_SEARCH_FILENAME_COLUMN or None
),
},
"filter": env_helper.AZURE_SEARCH_FILTER,
"in_scope": env_helper.AZURE_SEARCH_ENABLE_IN_DOMAIN,
"top_n_documents": env_helper.AZURE_SEARCH_TOP_K,
"embedding_dependency": {
"type": "deployment_name",
"deployment_name": env_helper.AZURE_OPENAI_EMBEDDING_MODEL,
},
"query_type": (
"vector_semantic_hybrid"
if env_helper.AZURE_SEARCH_USE_SEMANTIC_SEARCH
else "vector_simple_hybrid"
),
"semantic_configuration": (
env_helper.AZURE_SEARCH_SEMANTIC_SEARCH_CONFIG
if env_helper.AZURE_SEARCH_USE_SEMANTIC_SEARCH
and env_helper.AZURE_SEARCH_SEMANTIC_SEARCH_CONFIG
else ""
),
"role_information": env_helper.AZURE_OPENAI_SYSTEM_MESSAGE + get_current_date_suffix(),
},
}
]
},
)
if not env_helper.SHOULD_STREAM:
citations = get_citations(response.choices[0].message.model_extra["context"])
response_obj = {
"id": response.id,
"model": response.model,
"created": response.created,
"object": response.object,
"choices": [
{
"messages": [
{
"content": json.dumps(
citations,
ensure_ascii=False,
),
"end_turn": False,
"role": "tool",
},
{
"end_turn": True,
"content": response.choices[0].message.content,
"role": "assistant",
},
]
}
],
}
return response_obj
logger.info("Method conversation_with_data ended")
return Response(stream_with_data(response), mimetype="application/json-lines")
def stream_without_data(response: Stream[ChatCompletionChunk]):
"""This function streams the response from Azure OpenAI without data."""
response_text = ""
for line in response:
if not line.choices:
continue
delta_text = line.choices[0].delta.content
if delta_text is None:
return
response_text += delta_text
response_obj = {
"id": line.id,
"model": line.model,
"created": line.created,
"object": line.object,
"choices": [
{"messages": [{"role": "assistant", "content": response_text}]}
],
}
yield json.dumps(response_obj, ensure_ascii=False) + "\n"
def get_message_orchestrator():
"""This function gets the message orchestrator."""
return Orchestrator()
def get_orchestrator_config():
"""This function gets the orchestrator configuration."""
return ConfigHelper.get_active_config_or_default().orchestrator
def conversation_without_data(conversation: Request, env_helper: EnvHelper):
"""This function streams the response from Azure OpenAI without data."""
if env_helper.AZURE_AUTH_TYPE == "rbac":
openai_client = AzureOpenAI(
azure_endpoint=env_helper.AZURE_OPENAI_ENDPOINT,
api_version=env_helper.AZURE_OPENAI_API_VERSION,
azure_ad_token_provider=env_helper.AZURE_TOKEN_PROVIDER,
)
else:
openai_client = AzureOpenAI(
azure_endpoint=env_helper.AZURE_OPENAI_ENDPOINT,
api_version=env_helper.AZURE_OPENAI_API_VERSION,
api_key=env_helper.AZURE_OPENAI_API_KEY,
)
request_messages = conversation.json["messages"]
messages = [{"role": "system", "content": env_helper.AZURE_OPENAI_SYSTEM_MESSAGE + get_current_date_suffix()}]
for message in request_messages:
messages.append({"role": message["role"], "content": message["content"]})
# Azure Open AI takes the deployment name as the model name, "AZURE_OPENAI_MODEL" means
# deployment name.
response = openai_client.chat.completions.create(
model=env_helper.AZURE_OPENAI_MODEL,
messages=messages,
temperature=float(env_helper.AZURE_OPENAI_TEMPERATURE),
max_tokens=int(env_helper.AZURE_OPENAI_MAX_TOKENS),
top_p=float(env_helper.AZURE_OPENAI_TOP_P),
stop=(
env_helper.AZURE_OPENAI_STOP_SEQUENCE.split("|")
if env_helper.AZURE_OPENAI_STOP_SEQUENCE
else None
),
stream=env_helper.SHOULD_STREAM,
)
if not env_helper.SHOULD_STREAM:
response_obj = {
"id": response.id,
"model": response.model,
"created": response.created,
"object": response.object,
"choices": [
{
"messages": [
{
"role": "assistant",
"content": response.choices[0].message.content,
}
]
}
],
}
return jsonify(response_obj), 200
return Response(stream_without_data(response), mimetype="application/json-lines")
@functools.cache
def get_speech_key(env_helper: EnvHelper):
"""
Get the Azure Speech key directly from Azure.
This is required to generate short-lived tokens when using RBAC.
"""
client = CognitiveServicesManagementClient(
credential=get_azure_credential(env_helper.MANAGED_IDENTITY_CLIENT_ID),
subscription_id=env_helper.AZURE_SUBSCRIPTION_ID,
)
keys = client.accounts.list_keys(
resource_group_name=env_helper.AZURE_RESOURCE_GROUP,
account_name=env_helper.AZURE_SPEECH_SERVICE_NAME,
)
return keys.key1
def create_app():
"""This function creates the Flask app."""
# Fixing MIME types for static files under Windows
mimetypes.add_type("application/javascript", ".js")
mimetypes.add_type("text/css", ".css")
sys.path.append(path.join(path.dirname(__file__), ".."))
load_dotenv(
path.join(path.dirname(__file__), "..", "..", ".env")
) # Load environment variables from .env file
app = Flask(__name__)
env_helper: EnvHelper = EnvHelper()
azure_search_helper: AzureSearchHelper = AzureSearchHelper()
logger.debug("Starting web app")
@app.before_request
def set_span_attributes():
"""Middleware to attach conversation_id and user_id to the current OpenTelemetry span and context vars."""
if request.method == "POST" and request.is_json:
try:
body = request.get_json(silent=True) or {}
conversation_id = body.get("conversation_id", "")
authenticated_user = get_authenticated_user_details(request_headers=request.headers)
user_id = authenticated_user.get("user_principal_id", "")
_conversation_id_var.set(conversation_id)
_user_id_var.set(user_id)
span = trace.get_current_span()
if span:
if conversation_id:
span.set_attribute("conversation_id", conversation_id)
if user_id:
span.set_attribute("user_id", user_id)
except Exception:
pass # Don't let telemetry middleware break requests
@app.teardown_request
def clear_span_context(exc=None):
"""Clear conversation context vars after each request."""
_conversation_id_var.set("")
_user_id_var.set("")
@app.route("/", defaults={"path": "index.html"})
@app.route("/<path:path>")
def static_file(path):
return app.send_static_file(path)
@app.route("/api/health", methods=["GET"])
def health():
return "OK"
@app.route("/api/files/<path:filename>", methods=["GET"])
def get_file(filename):
"""
Download a file from the 'docs' container in Azure Blob Storage using Managed Identity.
Args:
filename (str): Name of the file to retrieve from storage
Returns:
Flask Response: The file content with appropriate headers, or error response
"""
logger.info("File download request (raw): %s", filename)
logger.info("File download request (repr): %r", filename)
try:
# URL decode the filename (Flask's path converter doesn't decode)
try:
decoded_filename = unquote(filename)
logger.info("Decoded filename: %s", decoded_filename)
logger.info("Decoded filename (repr): %r", decoded_filename)
# Detect double-encoding attack
# If decoding again changes the value, it was double-encoded
double_decoded = unquote(decoded_filename)
if double_decoded != decoded_filename:
logger.warning("Double-encoded filename detected: %s", filename)
return jsonify({"error": "Invalid filename encoding"}), 400
except Exception as decode_error:
logger.error("Failed to decode filename: %s", decode_error)
return jsonify({"error": "Invalid filename encoding"}), 400
# Use decoded filename for all subsequent operations
filename = decoded_filename
# Enhanced input validation - prevent path traversal and unauthorized access
if not filename:
logger.warning("Empty filename provided")
return jsonify({"error": "Filename is required"}), 400
# Detect if it's a URL vs regular filename
is_url = filename.startswith(('http://', 'https://'))
# Check for path traversal attacks
if is_url:
# For URLs, block directory traversal patterns
if '/../' in filename or '\\..\\' in filename or filename.endswith('/..') or filename.endswith('\\..'):
logger.warning("Path traversal attempt in URL: %s", filename)
return jsonify({"error": "Invalid filename"}), 400
else:
# For regular files, block path separators first
if '/' in filename or '\\' in filename:
logger.warning("Path separators in regular filename: %s", filename)
return jsonify({"error": "Invalid filename"}), 400
# Note: .. without path separators is safe (e.g., version..2.pdf)
# Validate filename length (URLs can be longer)
max_length = 2048 if is_url else 255
if len(filename) > max_length:
logger.warning("Filename too long: %s", filename)
return jsonify({"error": "Filename too long"}), 400
# Block control characters - allows multilingual filenames (Japanese, Hebrew, Arabic, etc.)
# This regex allows all Unicode characters except control characters
if not re.match(r'^[^\x00-\x1f\x7f]+$', filename):
logger.warning("Filename contains invalid control characters: %s", filename)
return jsonify({"error": "Invalid filename characters"}), 400
# For URLs, additional URL-specific validation
if is_url:
# Validate URL format: must start with http:// or https:// and not contain whitespace or control chars
if not re.match(r'^https?://[^\s\x00-\x1f\x7f]+$', filename):
logger.warning("Invalid URL format: %s", filename)
return jsonify({"error": "Invalid URL format"}), 400
# Initialize blob storage client with 'documents' container
blob_client = AzureBlobStorageClient(container_name="documents")
# Check if file exists
if not blob_client.file_exists(filename):
logger.info("File not found: %s", filename)
return jsonify({"error": "File not found"}), 404
# Download the file
file_data = blob_client.download_file(filename)
# Determine content type based on file extension
content_type, _ = mimetypes.guess_type(filename)
if not content_type:
content_type = 'application/octet-stream'
file_size = len(file_data)
logger.info("File downloaded successfully: %s, size: %d bytes", filename, file_size)
# For large files (>10MB), consider implementing streaming
if file_size > 10 * 1024 * 1024: # 10MB threshold
logger.info("Large file detected: %s, size: %d bytes", filename, file_size)
# Create response with comprehensive headers
# Use RFC 5987 encoding for Unicode filenames in Content-Disposition
encoded_filename = quote(filename)
response = Response(
file_data,
status=200,
mimetype=content_type,
headers={
'Content-Disposition': f"inline; filename*=UTF-8''{encoded_filename}",
'Content-Length': str(file_size),
'Cache-Control': 'public, max-age=3600',
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
'Content-Security-Policy': "default-src 'none'"
}
)
return response
except (ClientAuthenticationError, ResourceNotFoundError, ServiceRequestError) as e:
# Handle specific Azure errors
if isinstance(e, ClientAuthenticationError):
logger.error("Authentication failed for file %s: %s", filename, str(e))
return jsonify({"error": "Authentication failed"}), 401
elif isinstance(e, ResourceNotFoundError):
logger.info("File not found: %s", filename)
return jsonify({"error": "File not found"}), 404
elif isinstance(e, ServiceRequestError):
logger.error("Storage service error for file %s: %s", filename, str(e))
return jsonify({"error": "Storage service unavailable"}), 503
except Exception as e:
error_message = str(e)
logger.exception("Unexpected error downloading file %s: %s", filename, error_message)
return jsonify({"error": "Internal server error"}), 500
def conversation_azure_byod():
logger.info("Method conversation_azure_byod started")
try:
authenticated_user = get_authenticated_user_details(request_headers=request.headers)
user_id = authenticated_user.get("user_principal_id", "")
conversation_id = request.json.get("conversation_id", "")
track_event_if_configured("ConversationBYODRequestReceived", {
"conversation_id": conversation_id,
"user_id": user_id,
})
if should_use_data(env_helper, azure_search_helper):
return conversation_with_data(request, env_helper)
else:
return conversation_without_data(request, env_helper)
except APIStatusError as e:
error_message = str(e)
logger.exception("Exception in /api/conversation | %s", error_message)
track_event_if_configured("ConversationBYODError", {
"conversation_id": locals().get("conversation_id", ""),
"user_id": locals().get("user_id", ""),
"error": error_message,
"error_type": type(e).__name__,
})
response_json = e.response.json()
response_message = response_json.get("error", {}).get("message", "")
response_code = response_json.get("error", {}).get("code", "")
if response_code == "429" or "429" in response_message:
return jsonify({"error": ERROR_429_MESSAGE}), 429
return jsonify({"error": ERROR_GENERIC_MESSAGE}), 500
except Exception as e:
error_message = str(e)
logger.exception("Exception in /api/conversation | %s", error_message)
track_event_if_configured("ConversationBYODError", {
"conversation_id": locals().get("conversation_id", ""),
"user_id": locals().get("user_id", ""),
"error": error_message,
"error_type": type(e).__name__,
})
return jsonify({"error": ERROR_GENERIC_MESSAGE}), 500
finally:
logger.info("Method conversation_azure_byod ended")
async def conversation_custom():
message_orchestrator = get_message_orchestrator()
try:
logger.info("Method conversation_custom started")
authenticated_user = get_authenticated_user_details(request_headers=request.headers)
user_id = authenticated_user.get("user_principal_id", "")
user_message = request.json["messages"][-1]["content"]
conversation_id = request.json["conversation_id"]
track_event_if_configured("ConversationCustomRequestReceived", {
"conversation_id": conversation_id,
"user_id": user_id,
})
user_assistant_messages = list(
filter(
lambda x: x["role"] in ("user", "assistant"),
request.json["messages"][0:-1],
)
)
messages = await message_orchestrator.handle_message(
user_message=user_message,
chat_history=user_assistant_messages,
conversation_id=conversation_id,
orchestrator=get_orchestrator_config(),
)
track_event_if_configured("ConversationCustomSuccess", {
"conversation_id": conversation_id,
"user_id": user_id,
})
response_obj = {
"id": "response.id",
"model": env_helper.AZURE_OPENAI_MODEL,
"created": "response.created",
"object": "response.object",
"choices": [{"messages": messages}],
}
return jsonify(response_obj), 200
except APIStatusError as e:
error_message = str(e)
logger.exception("Exception in /api/conversation | %s", error_message)
track_event_if_configured("ConversationCustomError", {
"conversation_id": locals().get("conversation_id", ""),
"user_id": locals().get("user_id", ""),
"error": error_message,
"error_type": type(e).__name__,
})
response_json = e.response.json()
response_message = response_json.get("error", {}).get("message", "")
response_code = response_json.get("error", {}).get("code", "")
if response_code == "429" or "429" in response_message:
return jsonify({"error": ERROR_429_MESSAGE}), 429
return jsonify({"error": ERROR_GENERIC_MESSAGE}), 500
except Exception as e:
error_message = str(e)
logger.exception("Exception in /api/conversation | %s", error_message)
track_event_if_configured("ConversationCustomError", {
"conversation_id": locals().get("conversation_id", ""),
"user_id": locals().get("user_id", ""),
"error": error_message,
"error_type": type(e).__name__,
})
return jsonify({"error": ERROR_GENERIC_MESSAGE}), 500
finally:
logger.info("Method conversation_custom ended")
@app.route("/api/conversation", methods=["POST"])
async def conversation():
ConfigHelper.get_active_config_or_default.cache_clear()
result = ConfigHelper.get_active_config_or_default()
conversation_flow = result.prompts.conversational_flow
if conversation_flow == ConversationFlow.CUSTOM.value:
return await conversation_custom()
elif conversation_flow == ConversationFlow.BYOD.value:
return conversation_azure_byod()
else:
return (
jsonify(
{
"error": "Invalid conversation flow configured. Value can only be 'custom' or 'byod'."
}
),
500,
)
@app.route("/api/speech", methods=["GET"])
def speech_config():
"""Get the speech config for Azure Speech."""
try:
logger.info("Method speech_config started")
speech_key = env_helper.AZURE_SPEECH_KEY or get_speech_key(env_helper)
response = requests.post(
f"{env_helper.AZURE_SPEECH_REGION_ENDPOINT}sts/v1.0/issueToken",
headers={
"Ocp-Apim-Subscription-Key": speech_key,
},
timeout=5,
)
if response.status_code == 200:
return {
"token": response.text,
"region": env_helper.AZURE_SPEECH_SERVICE_REGION,
"languages": env_helper.AZURE_SPEECH_RECOGNIZER_LANGUAGES,
}
logger.error("Failed to get speech config: %s", response.text)
return {"error": "Failed to get speech config"}, response.status_code
except Exception as e:
logger.exception("Exception in /api/speech | %s", str(e))
return {"error": "Failed to get speech config"}, 500
finally:
logger.info("Method speech_config ended")
@app.route("/api/assistanttype", methods=["GET"])
def assistanttype():
ConfigHelper.get_active_config_or_default.cache_clear()
result = ConfigHelper.get_active_config_or_default()
return jsonify({"ai_assistant_type": result.prompts.ai_assistant_type})
@app.route("/api/checkauth", methods=["GET"])
async def check_auth_enforced():
"""Check if the authentiction is enforced."""
return jsonify({"is_auth_enforced": env_helper.ENFORCE_AUTH})
app.register_blueprint(bp_chat_history_response, url_prefix="/api")
return app