-
-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathazure_ai_foundry.py
More file actions
1819 lines (1582 loc) · 79.6 KB
/
azure_ai_foundry.py
File metadata and controls
1819 lines (1582 loc) · 79.6 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
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
title: Azure AI Foundry Pipeline
author: owndev
author_url: https://github.com/owndev/
project_url: https://github.com/owndev/Open-WebUI-Functions
funding_url: https://github.com/sponsors/owndev
version: 2.7.0
required_open_webui_version: 0.8.0
license: Apache License 2.0
description: A pipeline for interacting with Azure AI services, enabling seamless communication with various AI models via configurable headers and robust error handling. This includes support for Azure OpenAI models as well as other Azure AI models by dynamically managing headers and request configurations. Azure AI Search (RAG) integration is only supported with Azure OpenAI endpoints.
features:
- Supports dynamic model specification via headers.
- Filters valid parameters to ensure clean requests.
- Handles streaming and non-streaming responses.
- Provides flexible timeout and error handling mechanisms.
- Compatible with Azure OpenAI and other Azure AI models.
- Predefined models for easy access.
- Encrypted storage of sensitive API keys
- Azure AI Search / RAG integration with native OpenWebUI citations (Azure OpenAI only)
- Automatic [docX] to markdown link conversion for clickable citations
- Relevance scores from Azure AI Search displayed in citation cards
"""
from typing import (
List,
Union,
Generator,
Iterator,
Optional,
Dict,
Any,
AsyncIterator,
Set,
Callable,
)
from urllib.parse import urlparse
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, Field, GetCoreSchemaHandler
from open_webui.env import AIOHTTP_CLIENT_TIMEOUT, SRC_LOG_LEVELS
from cryptography.fernet import Fernet, InvalidToken
import aiohttp
import json
import os
import logging
import base64
import hashlib
import re
from pydantic_core import core_schema
# Simplified encryption implementation with automatic handling
class EncryptedStr(str):
"""A string type that automatically handles encryption/decryption"""
@classmethod
def _get_encryption_key(cls) -> Optional[bytes]:
"""
Generate encryption key from WEBUI_SECRET_KEY if available
Returns None if no key is configured
"""
secret = os.getenv("WEBUI_SECRET_KEY")
if not secret:
return None
hashed_key = hashlib.sha256(secret.encode()).digest()
return base64.urlsafe_b64encode(hashed_key)
@classmethod
def encrypt(cls, value: str) -> str:
"""
Encrypt a string value if a key is available
Returns the original value if no key is available
"""
if not value or value.startswith("encrypted:"):
return value
key = cls._get_encryption_key()
if not key: # No encryption if no key
return value
f = Fernet(key)
encrypted = f.encrypt(value.encode())
return f"encrypted:{encrypted.decode()}"
@classmethod
def decrypt(cls, value: str) -> str:
"""
Decrypt an encrypted string value if a key is available
Returns the original value if no key is available or decryption fails
"""
if not value or not value.startswith("encrypted:"):
return value
key = cls._get_encryption_key()
if not key: # No decryption if no key
return value[len("encrypted:") :] # Return without prefix
try:
encrypted_part = value[len("encrypted:") :]
f = Fernet(key)
decrypted = f.decrypt(encrypted_part.encode())
return decrypted.decode()
except (InvalidToken, Exception):
return value
# Pydantic integration
@classmethod
def __get_pydantic_core_schema__(
cls, _source_type: Any, _handler: GetCoreSchemaHandler
) -> core_schema.CoreSchema:
return core_schema.union_schema(
[
core_schema.is_instance_schema(cls),
core_schema.chain_schema(
[
core_schema.str_schema(),
core_schema.no_info_plain_validator_function(
lambda value: cls(cls.encrypt(value) if value else value)
),
]
),
],
serialization=core_schema.plain_serializer_function_ser_schema(
lambda instance: str(instance)
),
)
# Helper functions
async def cleanup_response(
response: Optional[aiohttp.ClientResponse],
session: Optional[aiohttp.ClientSession],
) -> None:
"""
Clean up the response and session objects.
Args:
response: The ClientResponse object to close
session: The ClientSession object to close
"""
if response:
response.close()
if session:
await session.close()
class Pipe:
# Regex pattern for matching [docX] citation references
DOC_REF_PATTERN = re.compile(r"\[doc(\d+)\]")
# Environment variables for API key, endpoint, and optional model
class Valves(BaseModel):
# Custom prefix for pipeline display name
AZURE_AI_PIPELINE_PREFIX: str = Field(
default=os.getenv("AZURE_AI_PIPELINE_PREFIX", "Azure AI"),
description="Custom prefix for the pipeline display name (e.g., 'Azure AI', 'My Azure', 'Company AI'). The final display will be: '<prefix>: <model_name>'",
)
# API key for Azure AI
AZURE_AI_API_KEY: EncryptedStr = Field(
default=os.getenv("AZURE_AI_API_KEY", "API_KEY"),
description="API key for Azure AI",
json_schema_extra={"input": {"type": "password"}},
)
# Endpoint for Azure AI (e.g. "https://<your-endpoint>/chat/completions?api-version=2024-05-01-preview" or "https://<your-endpoint>/openai/deployments/gpt-4o/chat/completions?api-version=2024-08-01-preview")
AZURE_AI_ENDPOINT: str = Field(
default=os.getenv(
"AZURE_AI_ENDPOINT",
"https://<your-endpoint>/chat/completions?api-version=2024-05-01-preview",
),
description="Endpoint for Azure AI",
)
# Optional model name, only necessary if not Azure OpenAI or if model name not in URL (e.g. "https://<your-endpoint>/openai/deployments/<model-name>/chat/completions")
# Multiple models can be specified as a semicolon-separated list (e.g. "gpt-4o;gpt-4o-mini")
# or a comma-separated list (e.g. "gpt-4o,gpt-4o-mini").
AZURE_AI_MODEL: str = Field(
default=os.getenv("AZURE_AI_MODEL", ""),
description="Optional model names for Azure AI (e.g. gpt-4o, gpt-4o-mini)",
)
# Switch for sending model name in request body
AZURE_AI_MODEL_IN_BODY: bool = Field(
default=bool(
os.getenv("AZURE_AI_MODEL_IN_BODY", "false").lower() == "true"
),
description="If True, include the model name in the request body instead of as a header.",
)
# Flag to indicate if predefined Azure AI models should be used
USE_PREDEFINED_AZURE_AI_MODELS: bool = Field(
default=bool(
os.getenv("USE_PREDEFINED_AZURE_AI_MODELS", "false").lower() == "true"
),
description="Flag to indicate if predefined Azure AI models should be used.",
)
# If True, use Authorization header with Bearer token instead of api-key header.
USE_AUTHORIZATION_HEADER: bool = Field(
default=bool(
os.getenv("AZURE_AI_USE_AUTHORIZATION_HEADER", "false").lower()
== "true"
),
description="Set to True to use Authorization header with Bearer token instead of api-key header.",
)
# Azure AI Data Sources Configuration (for Azure AI Search / RAG)
# Only works with Azure OpenAI endpoints: https://<deployment>.openai.azure.com/openai/deployments/<model>/chat/completions?api-version=2025-01-01-preview
AZURE_AI_DATA_SOURCES: str = Field(
default=os.getenv("AZURE_AI_DATA_SOURCES", ""),
description='JSON configuration for data_sources field (for Azure AI Search / RAG). Example: \'[{"type":"azure_search","parameters":{"endpoint":"https://xxx.search.windows.net","index_name":"your-index","authentication":{"type":"api_key","key":"your-key"}}}]\'',
)
# Enable relevance scores from Azure AI Search
AZURE_AI_INCLUDE_SEARCH_SCORES: bool = Field(
default=bool(
os.getenv("AZURE_AI_INCLUDE_SEARCH_SCORES", "true").lower() == "true"
),
description="If True, automatically add 'include_contexts' with 'all_retrieved_documents' to Azure AI Search requests to get relevance scores (original_search_score and rerank_score). This enables relevance percentage display in citation cards.",
)
# BM25 score normalization factor for relevance percentage display
# BM25 scores are unbounded and vary by collection. This value is used to normalize
# scores to 0-1 range: normalized = min(score / BM25_SCORE_MAX, 1.0)
# See: https://learn.microsoft.com/en-us/azure/search/index-ranking-similarity
BM25_SCORE_MAX: float = Field(
default=float(os.getenv("AZURE_AI_BM25_SCORE_MAX", "100.0")),
description="Normalization divisor for BM25 search scores (0-1 range). Adjust based on your index characteristics. Default 100.0 is suitable for typical collections; higher values (e.g., 200.0) reduce saturation for large documents.",
)
# Rerank score normalization factor for relevance percentage display
# Cohere rerankers via Azure return 0-4, most others 0-1. This value normalizes
# scores above 1.0 to 0-1 range: normalized = min(score / RERANK_SCORE_MAX, 1.0)
# See: https://learn.microsoft.com/en-us/azure/search/semantic-ranking
RERANK_SCORE_MAX: float = Field(
default=float(os.getenv("AZURE_AI_RERANK_SCORE_MAX", "4.0")),
description="Normalization divisor for rerank scores (0-1 range). Use 4.0 for Cohere rerankers, 1.0 for standard semantic rerankers.",
)
def __init__(self):
self.valves = self.Valves()
self.name: str = f"{self.valves.AZURE_AI_PIPELINE_PREFIX}:"
# Extract model name from Azure OpenAI URL if available
self._extracted_model_name = self._extract_model_from_url()
def _extract_model_from_url(self) -> Optional[str]:
"""
Extract model name from Azure OpenAI URL format.
Expected format: https://<deployment>.openai.azure.com/openai/deployments/<model>/chat/completions
Returns:
Model name if found in URL, None otherwise
"""
if not self.valves.AZURE_AI_ENDPOINT:
return None
try:
endpoint_host = urlparse(self.valves.AZURE_AI_ENDPOINT).hostname or ""
if (
endpoint_host == "openai.azure.com"
or endpoint_host.endswith(".openai.azure.com")
) and "/deployments/" in self.valves.AZURE_AI_ENDPOINT:
# Extract model name from URL pattern
# Pattern: .../deployments/{model}/chat/completions...
parts = self.valves.AZURE_AI_ENDPOINT.split("/deployments/")
if len(parts) > 1:
model_part = parts[1].split("/")[
0
] # Get first segment after deployments/
if model_part:
# Log for debugging
log = logging.getLogger("azure_ai._extract_model_from_url")
log.debug(
f"Extracted model name '{model_part}' from URL: {self.valves.AZURE_AI_ENDPOINT}"
)
return model_part
except Exception as e:
# Log parsing errors
log = logging.getLogger("azure_ai._extract_model_from_url")
log.warning(
f"Error extracting model from URL {self.valves.AZURE_AI_ENDPOINT}: {e}"
)
return None
def validate_environment(self) -> None:
"""
Validates that required environment variables are set.
Raises:
ValueError: If required environment variables are not set.
"""
# Access the decrypted API key
api_key = EncryptedStr.decrypt(self.valves.AZURE_AI_API_KEY)
if not api_key:
raise ValueError("AZURE_AI_API_KEY is not set!")
if not self.valves.AZURE_AI_ENDPOINT:
raise ValueError("AZURE_AI_ENDPOINT is not set!")
def get_headers(self, model_name: str = None) -> Dict[str, str]:
"""
Constructs the headers for the API request, including the model name if defined.
Args:
model_name: Optional model name to use instead of the default one
Returns:
Dictionary containing the required headers for the API request.
"""
# Access the decrypted API key
api_key = EncryptedStr.decrypt(self.valves.AZURE_AI_API_KEY)
if self.valves.USE_AUTHORIZATION_HEADER:
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
}
else:
headers = {"api-key": api_key, "Content-Type": "application/json"}
# If we have a model name and it shouldn't be in the body, add it to headers
if not self.valves.AZURE_AI_MODEL_IN_BODY:
# If specific model name provided, use it
if model_name:
headers["x-ms-model-mesh-model-name"] = model_name
# Otherwise, if AZURE_AI_MODEL has a single value, use that
elif (
self.valves.AZURE_AI_MODEL
and ";" not in self.valves.AZURE_AI_MODEL
and "," not in self.valves.AZURE_AI_MODEL
and " " not in self.valves.AZURE_AI_MODEL
):
headers["x-ms-model-mesh-model-name"] = self.valves.AZURE_AI_MODEL
return headers
def validate_body(self, body: Dict[str, Any]) -> None:
"""
Validates the request body to ensure required fields are present.
Args:
body: The request body to validate
Raises:
ValueError: If required fields are missing or invalid.
"""
if "messages" not in body or not isinstance(body["messages"], list):
raise ValueError("The 'messages' field is required and must be a list.")
def get_azure_ai_data_sources(self) -> Optional[List[Dict[str, Any]]]:
"""
Builds Azure AI data sources configuration from the AZURE_AI_DATA_SOURCES environment variable.
Only works with Azure OpenAI endpoints: https://<deployment>.openai.azure.com/openai/deployments/<model>/chat/completions?api-version=2025-01-01-preview
If AZURE_AI_INCLUDE_SEARCH_SCORES is enabled, automatically adds 'include_contexts'
with 'all_retrieved_documents' to get relevance scores from Azure AI Search.
Returns:
List containing Azure AI data source configuration, or None if not configured.
"""
if not self.valves.AZURE_AI_DATA_SOURCES:
return None
log = logging.getLogger("azure_ai.get_azure_ai_data_sources")
try:
data_sources = json.loads(self.valves.AZURE_AI_DATA_SOURCES)
if not isinstance(data_sources, list):
# If it's a single object, wrap it in a list
data_sources = [data_sources]
# If AZURE_AI_INCLUDE_SEARCH_SCORES is enabled, add include_contexts
if self.valves.AZURE_AI_INCLUDE_SEARCH_SCORES:
for source in data_sources:
if (
isinstance(source, dict)
and source.get("type") == "azure_search"
and "parameters" in source
):
params = source["parameters"]
# Get or create include_contexts list
include_contexts = params.get("include_contexts", [])
if not isinstance(include_contexts, list):
include_contexts = [include_contexts]
# Add 'citations' and 'all_retrieved_documents' if not present
if "citations" not in include_contexts:
include_contexts.append("citations")
if "all_retrieved_documents" not in include_contexts:
include_contexts.append("all_retrieved_documents")
params["include_contexts"] = include_contexts
log.debug(
f"Added include_contexts to Azure Search: {include_contexts}"
)
return data_sources
except json.JSONDecodeError as e:
# Log error and return None if JSON parsing fails
log.error(f"Error parsing AZURE_AI_DATA_SOURCES: {e}")
return None
def _extract_citations_from_response(
self, response_data: Dict[str, Any]
) -> Optional[List[Dict[str, Any]]]:
"""
Extract citations from an Azure AI response (streaming or non-streaming).
Supports both 'citations' and 'all_retrieved_documents' response structures.
When include_contexts includes 'all_retrieved_documents', the response contains
additional score fields like 'original_search_score' and 'rerank_score'.
Args:
response_data: Response data from Azure AI (can be a delta or full message)
Returns:
List of citation objects, or None if no citations found
"""
log = logging.getLogger("azure_ai._extract_citations_from_response")
if not isinstance(response_data, dict):
log.debug(f"Response data is not a dict: {type(response_data)}")
return None
# Try multiple possible locations for citations
citations = None
# Check in choices[0].delta.context or choices[0].message.context
if "choices" in response_data and response_data["choices"]:
choice = response_data["choices"][0]
context = None
# Get context from delta (streaming) or message (non-streaming)
if "delta" in choice and isinstance(choice["delta"], dict):
context = choice["delta"].get("context")
elif "message" in choice and isinstance(choice["message"], dict):
context = choice["message"].get("context")
if context and isinstance(context, dict):
# Try citations first
if "citations" in context:
citations = context["citations"]
log.info(
f"Found {len(citations) if citations else 0} citations in context.citations"
)
# If all_retrieved_documents is present, merge score data into citations
if "all_retrieved_documents" in context:
all_docs = context["all_retrieved_documents"]
log.debug(
f"Found {len(all_docs) if all_docs else 0} all_retrieved_documents"
)
# If we have both citations and all_retrieved_documents,
# try to merge score data from all_retrieved_documents into citations
if citations and all_docs:
self._merge_score_data(citations, all_docs, log)
elif all_docs and not citations:
# Use all_retrieved_documents as citations if no citations found
citations = all_docs
log.info(
f"Using {len(citations)} all_retrieved_documents as citations"
)
else:
log.debug(
f"No context found in response. Choice keys: {choice.keys() if isinstance(choice, dict) else 'not a dict'}"
)
else:
log.debug(f"No choices in response. Response keys: {response_data.keys()}")
if citations and isinstance(citations, list):
log.info(f"Extracted {len(citations)} citations from response")
# Log first citation structure for debugging (only if INFO logging is enabled)
if citations and log.isEnabledFor(logging.INFO):
log.info(
f"First citation structure: {json.dumps(citations[0], default=str)[:500]}"
)
return citations
log.debug("No valid citations found in response")
return None
def _merge_score_data(
self,
citations: List[Dict[str, Any]],
all_docs: List[Dict[str, Any]],
log: logging.Logger,
) -> None:
"""
Merge score data from all_retrieved_documents into citations.
When include_contexts includes 'all_retrieved_documents', Azure returns
additional documents with score fields. This method attempts to match
them with citations and copy over the score data.
Copies:
- original_search_score: BM25/keyword search score
- rerank_score: Semantic reranker score (if enabled)
- filter_reason: Indicates which score is relevant ("score" or "rerank")
Args:
citations: List of citation objects to update (modified in place)
all_docs: List of all_retrieved_documents with score data
log: Logger instance
"""
# Build multiple lookup maps to maximize matching chances
# all_retrieved_documents may have different keys than citations
doc_data_by_title = {}
doc_data_by_filepath = {}
doc_data_by_content = {}
doc_data_by_chunk_id = {}
for doc in all_docs:
doc_data = {
"original_search_score": doc.get("original_search_score"),
"rerank_score": doc.get("rerank_score"),
"filter_reason": doc.get("filter_reason"),
}
log.debug(
f"Processing all_retrieved_document: title='{doc.get('title')}', "
f"chunk_id='{doc.get('chunk_id')}', "
f"original_search_score={doc_data['original_search_score']}, "
f"rerank_score={doc_data['rerank_score']}, "
f"filter_reason={doc_data['filter_reason']}"
)
# Only store if we have at least one score
if (
doc_data["original_search_score"] is None
and doc_data["rerank_score"] is None
):
log.debug(f"Skipping doc with no scores: {doc.get('title')}")
continue
# Index by title
if doc.get("title"):
doc_data_by_title[doc["title"]] = doc_data
# Index by filepath
if doc.get("filepath"):
doc_data_by_filepath[doc["filepath"]] = doc_data
# Index by chunk_id (may include title as prefix for uniqueness)
if doc.get("chunk_id") is not None:
# Store by plain chunk_id
doc_data_by_chunk_id[str(doc["chunk_id"])] = doc_data
# Also store by title-prefixed chunk_id for uniqueness
if doc.get("title"):
chunk_key_with_title = f"{doc['title']}_{doc['chunk_id']}"
doc_data_by_chunk_id[chunk_key_with_title] = doc_data
# Index by content prefix (first 100 chars)
if doc.get("content"):
content_key = (
doc["content"][:100]
if len(doc.get("content", "")) > 100
else doc.get("content")
)
doc_data_by_content[content_key] = doc_data
log.debug(
f"Built score lookup: by_title={len(doc_data_by_title)}, "
f"by_filepath={len(doc_data_by_filepath)}, "
f"by_chunk_id={len(doc_data_by_chunk_id)}, "
f"by_content={len(doc_data_by_content)}"
)
# Match citations with score data using multiple strategies
matched = 0
for citation in citations:
doc_data = None
# Try matching by title first (most reliable)
if not doc_data and citation.get("title"):
doc_data = doc_data_by_title.get(citation["title"])
if doc_data:
log.debug(f"Matched citation by title: {citation['title']}")
# Try matching by filepath
if not doc_data and citation.get("filepath"):
doc_data = doc_data_by_filepath.get(citation["filepath"])
if doc_data:
log.debug(f"Matched citation by filepath: {citation['filepath']}")
# Try matching by chunk_id with title prefix
if not doc_data and citation.get("chunk_id") is not None:
chunk_key = str(citation["chunk_id"])
if citation.get("title"):
chunk_key_with_title = f"{citation['title']}_{citation['chunk_id']}"
doc_data = doc_data_by_chunk_id.get(chunk_key_with_title)
if not doc_data:
doc_data = doc_data_by_chunk_id.get(chunk_key)
if doc_data:
log.debug(f"Matched citation by chunk_id: {citation['chunk_id']}")
# Try matching by content prefix
if not doc_data and citation.get("content"):
content_key = (
citation["content"][:100]
if len(citation.get("content", "")) > 100
else citation.get("content")
)
doc_data = doc_data_by_content.get(content_key)
if doc_data:
log.debug("Matched citation by content prefix")
if doc_data:
if doc_data.get("original_search_score") is not None:
citation["original_search_score"] = doc_data[
"original_search_score"
]
if doc_data.get("rerank_score") is not None:
citation["rerank_score"] = doc_data["rerank_score"]
if doc_data.get("filter_reason") is not None:
citation["filter_reason"] = doc_data["filter_reason"]
matched += 1
log.debug(
f"Citation scores: original={doc_data.get('original_search_score')}, "
f"rerank={doc_data.get('rerank_score')}, "
f"filter_reason={doc_data.get('filter_reason')}"
)
log.info(f"Merged score data for {matched}/{len(citations)} citations")
def _normalize_citation_for_openwebui(
self, citation: Dict[str, Any], index: int
) -> Dict[str, Any]:
"""
Normalize an Azure citation object to OpenWebUI citation event format.
The format follows OpenWebUI's official citation event structure:
https://docs.openwebui.com/features/plugin/development/events#source-or-citation-and-code-execution
Args:
citation: Azure citation object
index: Citation index (1-based)
Returns:
Complete citation event object with type and data fields
"""
log = logging.getLogger("azure_ai._normalize_citation_for_openwebui")
# Get title with fallback chain: title → filepath → url → "Unknown Document"
# Handle None values explicitly since dict.get() returns None if key exists but value is None
title_raw = citation.get("title") or ""
filepath_raw = citation.get("filepath") or ""
url_raw = citation.get("url") or ""
base_title = (
title_raw.strip()
or filepath_raw.strip()
or url_raw.strip()
or "Unknown Document"
)
# Include [docX] prefix in OpenWebUI citation card titles for document identification
title = f"[doc{index}] - {base_title}"
# Build source URL for metadata
source_url = url_raw or filepath_raw
# Build metadata with source information
# Use title with [docX] prefix as metadata source for OpenWebUI display
# The UI may extract display name from metadata.source rather than source.name
metadata_entry = {"source": title, "url": source_url}
if citation.get("metadata"):
metadata_entry.update(citation.get("metadata", {}))
# Get document content (handle None values)
content = citation.get("content") or ""
# Build normalized citation data structure matching OpenWebUI format exactly
citation_data = {
"document": [content],
"metadata": [metadata_entry],
"source": {"name": title},
}
# Add URL to source if available
if source_url:
citation_data["source"]["url"] = source_url
# Add distances array for relevance score (OpenWebUI uses this for percentage display)
# Azure AI Search returns filter_reason to indicate which score type is relevant:
# - filter_reason not present or "score": use original_search_score (BM25/keyword)
# - filter_reason "rerank": use rerank_score (semantic reranker)
# Reference: https://learn.microsoft.com/en-us/azure/ai-foundry/openai/references/on-your-data
filter_reason = citation.get("filter_reason")
rerank_score = citation.get("rerank_score")
original_search_score = citation.get("original_search_score")
legacy_score = citation.get("score")
normalized_score = 0.0
# Select score based on filter_reason as per Azure documentation:
# - filter_reason="rerank": Document filtered by rerank score threshold, use rerank_score
# - filter_reason="score" or not present: Document filtered by/passed original search score, use original_search_score
if filter_reason == "rerank" and rerank_score is not None:
# Document filtered by rerank score - use rerank_score
# Cohere rerankers via Azure AI return scores in 0-4 range (source: Azure AI Search documentation)
# Most semantic rerankers return 0-1, so we normalize 0-4 range down to 0-1 for consistency.
# Reference: https://learn.microsoft.com/en-us/azure/search/semantic-ranking
score_val = float(rerank_score)
if score_val > 1.0:
normalized_score = min(score_val / self.valves.RERANK_SCORE_MAX, 1.0)
else:
normalized_score = score_val
log.debug(
f"Using rerank_score (filter_reason=rerank): {rerank_score} -> {normalized_score} "
f"(normalized via {self.valves.RERANK_SCORE_MAX})"
)
elif (
filter_reason is None or filter_reason == "score"
) and original_search_score is not None:
# filter_reason is "score" or not present - use original_search_score
# BM25 scores are unbounded and vary by collection size and term distribution.
# We normalize by dividing by BM25_SCORE_MAX to produce a value in 0-1 range.
# This preserves relative ranking without hard-capping high-relevance documents.
# Reference: https://learn.microsoft.com/en-us/azure/search/index-ranking-similarity
score_val = float(original_search_score)
if score_val > 1.0:
normalized_score = min(score_val / self.valves.BM25_SCORE_MAX, 1.0)
else:
normalized_score = score_val
log.debug(
f"Using original_search_score (filter_reason={filter_reason}): {original_search_score} -> {normalized_score} "
f"(normalized via {self.valves.BM25_SCORE_MAX})"
)
elif original_search_score is not None:
# Fallback for unknown filter_reason values - use original_search_score
score_val = float(original_search_score)
if score_val > 1.0:
normalized_score = min(score_val / self.valves.BM25_SCORE_MAX, 1.0)
else:
normalized_score = score_val
log.debug(
f"Using original_search_score (fallback, filter_reason={filter_reason}): {original_search_score} -> {normalized_score} "
f"(normalized via {self.valves.BM25_SCORE_MAX})"
)
elif rerank_score is not None:
# Fallback to rerank_score if available but filter_reason doesn't match
score_val = float(rerank_score)
if score_val > 1.0:
normalized_score = min(score_val / self.valves.RERANK_SCORE_MAX, 1.0)
else:
normalized_score = score_val
log.debug(
f"Using rerank_score (fallback): {rerank_score} -> {normalized_score} "
f"(normalized via {self.valves.RERANK_SCORE_MAX})"
)
elif legacy_score is not None:
normalized_score = float(legacy_score)
log.debug(f"Using legacy score: {legacy_score}")
else:
log.debug("No score available, using default 0.0")
citation_data["distances"] = [normalized_score]
# Build complete citation event structure
citation_event = {
"type": "citation",
"data": citation_data,
}
# Log the normalized citation for debugging (only if INFO logging is enabled)
if log.isEnabledFor(logging.INFO):
log.info(
f"Normalized citation {index}: title='{title}', "
f"content_length={len(content)}, "
f"url='{source_url}', "
f"filter_reason={filter_reason}, "
f"rerank_score={rerank_score}, original_search_score={original_search_score}, "
f"distances={citation_data['distances']}, "
f"event={json.dumps(citation_event, default=str)[:500]}"
)
return citation_event
def _build_citation_urls_map(
self, citations: Optional[List[Dict[str, Any]]]
) -> Dict[int, Optional[str]]:
"""
Build a mapping of citation indices to document URLs.
Args:
citations: List of citation objects with title, filepath, url, etc.
Returns:
Dict mapping 1-based citation index to URL (or None if no URL available)
"""
citation_urls: Dict[int, Optional[str]] = {}
if not citations:
return citation_urls
for i, citation in enumerate(citations, 1):
if isinstance(citation, dict):
# Get URL with fallback to filepath
url = citation.get("url") or ""
filepath = citation.get("filepath") or ""
citation_url = url.strip() or filepath.strip() or None
citation_urls[i] = citation_url
return citation_urls
def _format_citation_link(self, doc_num: int, url: Optional[str] = None) -> str:
"""
Format a markdown link for a [docX] reference.
If a URL is available, creates a clickable markdown link.
Otherwise, returns the original [docX] reference.
Args:
doc_num: The document number (1-based)
url: Optional URL for the document
Returns:
Formatted markdown link string or original [docX] reference
"""
if url:
# Create markdown link: [[doc1]](url)
return f"[[doc{doc_num}]]({url})"
else:
# No URL available, keep original reference
return f"[doc{doc_num}]"
def _convert_doc_refs_to_links(
self, content: str, citations: List[Dict[str, Any]]
) -> str:
"""
Convert [docX] references in content to markdown links with document URLs.
If a citation has a URL, [doc1] becomes [[doc1]](url). This creates clickable
links to the source documents in the response.
Args:
content: The response content containing [docX] references
citations: List of citation objects with title, url, etc.
Returns:
Content with [docX] references converted to markdown links
"""
if not content or not citations:
return content
log = logging.getLogger("azure_ai._convert_doc_refs_to_links")
# Build a mapping of citation index to URL
citation_urls = self._build_citation_urls_map(citations)
def replace_doc_ref(match):
"""Replace [docX] with [[docX]](url) if URL available"""
doc_num = int(match.group(1))
url = citation_urls.get(doc_num)
return self._format_citation_link(doc_num, url)
# Replace all [docX] references
converted = re.sub(self.DOC_REF_PATTERN, replace_doc_ref, content)
# Count conversions for logging
original_count = len(re.findall(self.DOC_REF_PATTERN, content))
linked_count = sum(
1 for i in range(1, len(citations) + 1) if citation_urls.get(i)
)
if original_count > 0:
log.info(
f"Converted {original_count} [docX] references to markdown links ({linked_count} with URLs)"
)
return converted
async def _emit_openwebui_citation_events(
self,
citations: List[Dict[str, Any]],
__event_emitter__: Optional[Callable[..., Any]],
content: str = "",
) -> None:
"""
Emit OpenWebUI citation events for citations.
Emits one citation event per source document, following the OpenWebUI
citation event format. Each citation is emitted separately to ensure
all sources appear in the UI.
Only emits citations that are actually referenced in the content (e.g., [doc1], [doc2]).
Args:
citations: List of Azure citation objects
__event_emitter__: Event emitter callable for sending citation events
content: The response content (used to filter only referenced citations)
"""
log = logging.getLogger("azure_ai._emit_openwebui_citation_events")
if not __event_emitter__:
log.warning("No __event_emitter__ provided, cannot emit citation events")
return
if not citations:
log.info("No citations to emit")
return
# Extract which citations are actually referenced in the content
referenced_indices = self._extract_referenced_citations(content)
# If we couldn't find any references, include all citations (backward compatibility)
if not referenced_indices:
referenced_indices = set(range(1, len(citations) + 1))
log.debug(
f"No [docX] references found in content, including all {len(citations)} citations"
)
else:
log.info(
f"Found {len(referenced_indices)} referenced citations: {sorted(referenced_indices)}"
)
log.info(
f"Emitting citation events for {len(referenced_indices)} referenced citations via __event_emitter__"
)
emitted_count = 0
for i, citation in enumerate(citations, 1):
# Skip citations that are not referenced in the content
if i not in referenced_indices:
log.debug(f"Skipping citation {i} - not referenced in content")
continue
if not isinstance(citation, dict):
log.warning(f"Citation {i} is not a dict, skipping: {type(citation)}")
continue
try:
normalized = self._normalize_citation_for_openwebui(citation, i)
# Log the full citation JSON for debugging
# log.debug(
# f"Full citation event JSON for doc{i}: {json.dumps(normalized, default=str)}"
# )
# Emit citation event for this individual source
source_name = (
normalized.get("data", {}).get("source", {}).get("name", "unknown")
)
log.info(
f"Emitting citation event {i}/{len(citations)} with source.name='{source_name}'"
)
await __event_emitter__(normalized)
emitted_count += 1
log.info(f"Successfully emitted citation event for doc{i}")
except Exception as e:
log.exception(f"Failed to emit citation event for citation {i}: {e}")
log.info(
f"Finished emitting {emitted_count}/{len(referenced_indices)} citation events"
)
def enhance_azure_search_response(self, response: Dict[str, Any]) -> Dict[str, Any]:
"""
Enhance Azure AI Search responses by converting [docX] references to markdown links.
Modifies the response in-place and returns it.
Args:
response: The original response from Azure AI (modified in-place)
Returns:
The enhanced response with markdown links for citations
"""
if not isinstance(response, dict):
return response
# Check if this is an Azure AI Search response with citations
if (
"choices" not in response
or not response["choices"]
or "message" not in response["choices"][0]
or "context" not in response["choices"][0]["message"]
or "citations" not in response["choices"][0]["message"]["context"]
):
return response
try:
choice = response["choices"][0]
message = choice["message"]
context = message["context"]
citations = context["citations"]
content = message["content"]
# Convert [docX] references to markdown links
enhanced_content = self._convert_doc_refs_to_links(content, citations)
# Update the message content
message["content"] = enhanced_content
return response
except Exception as e:
log = logging.getLogger("azure_ai.enhance_azure_search_response")
log.warning(f"Failed to enhance Azure Search response: {e}")