-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcreate_app.py
445 lines (386 loc) · 15.6 KB
/
create_app.py
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
"""
This module creates a Flask app that serves the web interface for the chatbot.
"""
import functools
import json
import logging
import mimetypes
from os import path
import sys
import requests
from openai import AzureOpenAI, Stream
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.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 azure.mgmt.cognitiveservices import CognitiveServicesManagementClient
from azure.identity import DefaultAzureCredential
logger = logging.getLogger(__name__)
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":
response_obj["choices"][0]["messages"][0]["content"] = json.dumps(
delta.model_extra["context"],
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."""
if env_helper.is_auth_type_keys():
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:
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,
)
messages = conversation.json["messages"]
# 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": "system_assigned_managed_identity",
}
),
"endpoint": env_helper.AZURE_SEARCH_SERVICE,
"index_name": env_helper.AZURE_SEARCH_INDEX,
"fields_mapping": {
"content_fields": (
env_helper.AZURE_SEARCH_CONTENT_COLUMNS.split("|")
if env_helper.AZURE_SEARCH_CONTENT_COLUMNS
else []
),
"vector_fields": [
env_helper.AZURE_SEARCH_CONTENT_VECTOR_COLUMNS
],
"title_field": env_helper.AZURE_SEARCH_TITLE_COLUMN or None,
"url_field": env_helper.AZURE_SEARCH_URL_COLUMN 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,
},
}
]
},
)
if not env_helper.SHOULD_STREAM:
response_obj = {
"id": response.id,
"model": response.model,
"created": response.created,
"object": response.object,
"choices": [
{
"messages": [
{
"content": json.dumps(
response.choices[0].message.model_extra["context"],
ensure_ascii=False,
),
"end_turn": False,
"role": "tool",
},
{
"end_turn": True,
"content": response.choices[0].message.content,
"role": "assistant",
},
]
}
],
}
return response_obj
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}]
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=DefaultAzureCredential(),
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()
logger.debug("Starting web app")
@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"
def conversation_azure_byod():
try:
if env_helper.should_use_data():
return conversation_with_data(request, env_helper)
else:
return conversation_without_data(request, env_helper)
except Exception as e:
error_message = str(e)
logger.exception("Exception in /api/conversation | %s", error_message)
return (
jsonify(
{
"error": "Exception in /api/conversation. See log for more details."
}
),
500,
)
async def conversation_custom():
message_orchestrator = get_message_orchestrator()
try:
user_message = request.json["messages"][-1]["content"]
conversation_id = request.json["conversation_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(),
)
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 Exception as e:
error_message = str(e)
logger.exception("Exception in /api/conversation | %s", error_message)
return (
jsonify(
{
"error": "Exception in /api/conversation. See log for more details."
}
),
500,
)
@app.route("/api/conversation", methods=["POST"])
async def conversation():
conversation_flow = env_helper.CONVERSATION_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:
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
return app