path
stringlengths 9
117
| type
stringclasses 2
values | project
stringclasses 10
values | commit_hash
stringlengths 40
40
| commit_message
stringlengths 1
137
| ground_truth
stringlengths 0
2.74k
| main_code
stringlengths 102
3.37k
| context
stringlengths 0
14.7k
|
---|---|---|---|---|---|---|---|
tests.test_blob_manager/test_create_container_upon_upload
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
0124725ad85726aa3f62450e16fb136a63154f69
|
Adds storageURL field to track file location (#1535)
|
<17>:<add> return azure.storage.blob.aio.BlobClient.from_blob_url(
<add> "https://test.blob.core.windows.net/test/test.pdf", credential=MockAzureCredential()
<add> )
<del> return True
<22>:<add> assert f.url == "https://test.blob.core.windows.net/test/test.pdf"
|
# module: tests.test_blob_manager
@pytest.mark.asyncio
@pytest.mark.skipif(sys.version_info.minor < 10, reason="requires Python 3.10 or higher")
async def test_create_container_upon_upload(monkeypatch, mock_env, blob_manager):
<0> with NamedTemporaryFile(suffix=".pdf") as temp_file:
<1> f = File(temp_file.file)
<2> filename = os.path.basename(f.content.name)
<3>
<4> # Set up mocks used by upload_blob
<5> async def mock_exists(*args, **kwargs):
<6> return False
<7>
<8> monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.exists", mock_exists)
<9>
<10> async def mock_create_container(*args, **kwargs):
<11> return
<12>
<13> monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.create_container", mock_create_container)
<14>
<15> async def mock_upload_blob(self, name, *args, **kwargs):
<16> assert name == filename
<17> return True
<18>
<19> monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.upload_blob", mock_upload_blob)
<20>
<21> await blob_manager.upload_blob(f)
<22>
|
===========unchanged ref 0===========
at: _pytest.mark.structures
MARK_GEN = MarkGenerator(_ispytest=True)
at: _pytest.mark.structures.MarkGenerator
skipif: _SkipifMarkDecorator
at: os.path
basename(p: _PathLike[AnyStr]) -> AnyStr
basename(p: AnyStr) -> AnyStr
at: sys
version_info: _version_info
at: sys._version_info
minor: int
at: tempfile
NamedTemporaryFile(mode: str=..., buffering: int=..., encoding: Optional[str]=..., newline: Optional[str]=..., suffix: Optional[AnyStr]=..., prefix: Optional[AnyStr]=..., dir: Optional[_DirT[AnyStr]]=..., delete: bool=..., *, errors: Optional[str]=...) -> IO[Any]
NamedTemporaryFile(mode: Literal["r", "w", "a", "x", "r+", "w+", "a+", "x+", "rt", "wt", "at", "xt", "r+t", "w+t", "a+t", "x+t"], buffering: int=..., encoding: Optional[str]=..., newline: Optional[str]=..., suffix: Optional[AnyStr]=..., prefix: Optional[AnyStr]=..., dir: Optional[_DirT[AnyStr]]=..., delete: bool=..., *, errors: Optional[str]=...) -> IO[str]
NamedTemporaryFile(mode: Literal["rb", "wb", "ab", "xb", "r+b", "w+b", "a+b", "x+b"]=..., buffering: int=..., encoding: Optional[str]=..., newline: Optional[str]=..., suffix: Optional[AnyStr]=..., prefix: Optional[AnyStr]=..., dir: Optional[_DirT[AnyStr]]=..., delete: bool=..., *, errors: Optional[str]=...) -> IO[bytes]
===========unchanged ref 1===========
at: tests.test_blob_manager.test_upload_and_remove_all
mock_delete_blob(self, name, *args, **kwargs)
===========changed ref 0===========
# module: tests.test_blob_manager
@pytest.mark.asyncio
@pytest.mark.skipif(sys.version_info.minor < 10, reason="requires Python 3.10 or higher")
async def test_upload_and_remove_all(monkeypatch, mock_env, blob_manager):
with NamedTemporaryFile(suffix=".pdf") as temp_file:
f = File(temp_file.file)
filename = os.path.basename(f.content.name)
# Set up mocks used by upload_blob
async def mock_exists(*args, **kwargs):
return True
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.exists", mock_exists)
async def mock_upload_blob(self, name, *args, **kwargs):
assert name == filename
+ return azure.storage.blob.aio.BlobClient.from_blob_url(
+ "https://test.blob.core.windows.net/test/test.pdf", credential=MockAzureCredential()
+ )
- return True
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.upload_blob", mock_upload_blob)
await blob_manager.upload_blob(f)
+ assert f.url == "https://test.blob.core.windows.net/test/test.pdf"
# Set up mocks used by remove_blob
def mock_list_blob_names(*args, **kwargs):
assert kwargs.get("name_starts_with") is None
class AsyncBlobItemsIterator:
def __init__(self, file):
self.files = [file]
def __aiter__(self):
return self
async def __anext__(self):
if self.files:
return self.files.pop()
raise StopAsyncIteration
return AsyncBlobItemsIterator(filename)
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.list_blob_names", mock_list_blob_names)
async def mock_delete_</s>
===========changed ref 1===========
# module: tests.test_blob_manager
@pytest.mark.asyncio
@pytest.mark.skipif(sys.version_info.minor < 10, reason="requires Python 3.10 or higher")
async def test_upload_and_remove_all(monkeypatch, mock_env, blob_manager):
# offset: 1
<s>.aio.ContainerClient.list_blob_names", mock_list_blob_names)
async def mock_delete_blob(self, name, *args, **kwargs):
assert name == filename
return True
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.delete_blob", mock_delete_blob)
await blob_manager.remove_blob()
===========changed ref 2===========
# module: tests.test_blob_manager
@pytest.mark.asyncio
@pytest.mark.skipif(sys.version_info.minor < 10, reason="requires Python 3.10 or higher")
async def test_upload_and_remove(monkeypatch, mock_env, blob_manager):
with NamedTemporaryFile(suffix=".pdf") as temp_file:
f = File(temp_file.file)
filename = os.path.basename(f.content.name)
# Set up mocks used by upload_blob
async def mock_exists(*args, **kwargs):
return True
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.exists", mock_exists)
async def mock_upload_blob(self, name, *args, **kwargs):
assert name == filename
+ return azure.storage.blob.aio.BlobClient.from_blob_url(
+ "https://test.blob.core.windows.net/test/test.pdf", credential=MockAzureCredential()
+ )
- return True
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.upload_blob", mock_upload_blob)
await blob_manager.upload_blob(f)
+ assert f.url == "https://test.blob.core.windows.net/test/test.pdf"
# Set up mocks used by remove_blob
def mock_list_blob_names(*args, **kwargs):
assert kwargs.get("name_starts_with") == filename.split(".pdf")[0]
class AsyncBlobItemsIterator:
def __init__(self, file):
self.files = [file, "dontdelete.pdf"]
def __aiter__(self):
return self
async def __anext__(self):
if self.files:
return self.files.pop()
raise StopAsyncIteration
return AsyncBlobItemsIterator(filename)
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.list_blob_names", mock_list</s>
===========changed ref 3===========
# module: tests.test_blob_manager
@pytest.mark.asyncio
@pytest.mark.skipif(sys.version_info.minor < 10, reason="requires Python 3.10 or higher")
async def test_upload_and_remove(monkeypatch, mock_env, blob_manager):
# offset: 1
<s>
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.list_blob_names", mock_list_blob_names)
async def mock_delete_blob(self, name, *args, **kwargs):
assert name == filename
return True
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.delete_blob", mock_delete_blob)
await blob_manager.remove_blob(f.content.name)
|
tests.test_blob_manager/test_upload_blob_no_image
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
0124725ad85726aa3f62450e16fb136a63154f69
|
Adds storageURL field to track file location (#1535)
|
<22>:<add> return azure.storage.blob.aio.BlobClient.from_blob_url(
<add> "https://test.blob.core.windows.net/test/test.xlsx", credential=MockAzureCredential()
<add> )
<del> return True
<28>:<add> assert f.url == "https://test.blob.core.windows.net/test/test.xlsx"
|
# module: tests.test_blob_manager
@pytest.mark.asyncio
@pytest.mark.skipif(sys.version_info.minor < 10, reason="requires Python 3.10 or higher")
async def test_upload_blob_no_image(monkeypatch, mock_env, caplog):
<0> blob_manager = BlobManager(
<1> endpoint=f"https://{os.environ['AZURE_STORAGE_ACCOUNT']}.blob.core.windows.net",
<2> credential=MockAzureCredential(),
<3> container=os.environ["AZURE_STORAGE_CONTAINER"],
<4> account=os.environ["AZURE_STORAGE_ACCOUNT"],
<5> resourceGroup=os.environ["AZURE_STORAGE_RESOURCE_GROUP"],
<6> subscriptionId=os.environ["AZURE_SUBSCRIPTION_ID"],
<7> store_page_images=True,
<8> )
<9>
<10> with NamedTemporaryFile(suffix=".xlsx") as temp_file:
<11> f = File(temp_file.file)
<12> filename = os.path.basename(f.content.name)
<13>
<14> # Set up mocks used by upload_blob
<15> async def mock_exists(*args, **kwargs):
<16> return True
<17>
<18> monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.exists", mock_exists)
<19>
<20> async def mock_upload_blob(self, name, *args, **kwargs):
<21> assert name == filename
<22> return True
<23>
<24> monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.upload_blob", mock_upload_blob)
<25>
<26> with caplog.at_level("INFO"):
<27> await blob_manager.upload_blob(f)
<28> assert "skipping image upload" in caplog.text
<29>
|
===========unchanged ref 0===========
at: _pytest.mark.structures
MARK_GEN = MarkGenerator(_ispytest=True)
at: _pytest.mark.structures.MarkGenerator
skipif: _SkipifMarkDecorator
at: os
environ = _createenviron()
at: os.path
basename(p: _PathLike[AnyStr]) -> AnyStr
basename(p: AnyStr) -> AnyStr
at: sys
version_info: _version_info
at: sys._version_info
minor: int
at: tempfile
NamedTemporaryFile(mode: str=..., buffering: int=..., encoding: Optional[str]=..., newline: Optional[str]=..., suffix: Optional[AnyStr]=..., prefix: Optional[AnyStr]=..., dir: Optional[_DirT[AnyStr]]=..., delete: bool=..., *, errors: Optional[str]=...) -> IO[Any]
NamedTemporaryFile(mode: Literal["r", "w", "a", "x", "r+", "w+", "a+", "x+", "rt", "wt", "at", "xt", "r+t", "w+t", "a+t", "x+t"], buffering: int=..., encoding: Optional[str]=..., newline: Optional[str]=..., suffix: Optional[AnyStr]=..., prefix: Optional[AnyStr]=..., dir: Optional[_DirT[AnyStr]]=..., delete: bool=..., *, errors: Optional[str]=...) -> IO[str]
NamedTemporaryFile(mode: Literal["rb", "wb", "ab", "xb", "r+b", "w+b", "a+b", "x+b"]=..., buffering: int=..., encoding: Optional[str]=..., newline: Optional[str]=..., suffix: Optional[AnyStr]=..., prefix: Optional[AnyStr]=..., dir: Optional[_DirT[AnyStr]]=..., delete: bool=..., *, errors: Optional[str]=...) -> IO[bytes]
===========unchanged ref 1===========
at: tests.test_blob_manager.test_create_container_upon_upload
f = File(temp_file.file)
mock_upload_blob(self, name, *args, **kwargs)
===========changed ref 0===========
# module: tests.test_blob_manager
@pytest.mark.asyncio
@pytest.mark.skipif(sys.version_info.minor < 10, reason="requires Python 3.10 or higher")
async def test_create_container_upon_upload(monkeypatch, mock_env, blob_manager):
with NamedTemporaryFile(suffix=".pdf") as temp_file:
f = File(temp_file.file)
filename = os.path.basename(f.content.name)
# Set up mocks used by upload_blob
async def mock_exists(*args, **kwargs):
return False
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.exists", mock_exists)
async def mock_create_container(*args, **kwargs):
return
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.create_container", mock_create_container)
async def mock_upload_blob(self, name, *args, **kwargs):
assert name == filename
+ return azure.storage.blob.aio.BlobClient.from_blob_url(
+ "https://test.blob.core.windows.net/test/test.pdf", credential=MockAzureCredential()
+ )
- return True
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.upload_blob", mock_upload_blob)
await blob_manager.upload_blob(f)
+ assert f.url == "https://test.blob.core.windows.net/test/test.pdf"
===========changed ref 1===========
# module: tests.test_blob_manager
@pytest.mark.asyncio
@pytest.mark.skipif(sys.version_info.minor < 10, reason="requires Python 3.10 or higher")
async def test_upload_and_remove_all(monkeypatch, mock_env, blob_manager):
with NamedTemporaryFile(suffix=".pdf") as temp_file:
f = File(temp_file.file)
filename = os.path.basename(f.content.name)
# Set up mocks used by upload_blob
async def mock_exists(*args, **kwargs):
return True
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.exists", mock_exists)
async def mock_upload_blob(self, name, *args, **kwargs):
assert name == filename
+ return azure.storage.blob.aio.BlobClient.from_blob_url(
+ "https://test.blob.core.windows.net/test/test.pdf", credential=MockAzureCredential()
+ )
- return True
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.upload_blob", mock_upload_blob)
await blob_manager.upload_blob(f)
+ assert f.url == "https://test.blob.core.windows.net/test/test.pdf"
# Set up mocks used by remove_blob
def mock_list_blob_names(*args, **kwargs):
assert kwargs.get("name_starts_with") is None
class AsyncBlobItemsIterator:
def __init__(self, file):
self.files = [file]
def __aiter__(self):
return self
async def __anext__(self):
if self.files:
return self.files.pop()
raise StopAsyncIteration
return AsyncBlobItemsIterator(filename)
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.list_blob_names", mock_list_blob_names)
async def mock_delete_</s>
===========changed ref 2===========
# module: tests.test_blob_manager
@pytest.mark.asyncio
@pytest.mark.skipif(sys.version_info.minor < 10, reason="requires Python 3.10 or higher")
async def test_upload_and_remove_all(monkeypatch, mock_env, blob_manager):
# offset: 1
<s>.aio.ContainerClient.list_blob_names", mock_list_blob_names)
async def mock_delete_blob(self, name, *args, **kwargs):
assert name == filename
return True
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.delete_blob", mock_delete_blob)
await blob_manager.remove_blob()
|
app.backend.prepdocslib.blobmanager/BlobManager.upload_blob
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
0124725ad85726aa3f62450e16fb136a63154f69
|
Adds storageURL field to track file location (#1535)
|
<7>:<add> if file.url is None:
<add> with open(file.content.name, "rb") as reopened_file:
<del> with open(file.content.name, "rb") as reopened_file:
<8>:<add> blob_name = BlobManager.blob_name_from_file_name(file.content.name)
<del> blob_name = BlobManager.blob_name_from_file_name(file.content.name)
<9>:<add> logger.info("Uploading blob for whole file -> %s", blob_name)
<del> logger.info("Uploading blob for whole file -> %s", blob_name)
<10>:<add> blob_client = await container_client.upload_blob(blob_name, reopened_file, overwrite=True)
<del> await container_client.upload_blob(blob_name, reopened_file, overwrite=True)
<11>:<add> file.url = blob_client.url
|
# module: app.backend.prepdocslib.blobmanager
class BlobManager:
def upload_blob(self, file: File) -> Optional[List[str]]:
<0> async with BlobServiceClient(
<1> account_url=self.endpoint, credential=self.credential, max_single_put_size=4 * 1024 * 1024
<2> ) as service_client, service_client.get_container_client(self.container) as container_client:
<3> if not await container_client.exists():
<4> await container_client.create_container()
<5>
<6> # Re-open and upload the original file
<7> with open(file.content.name, "rb") as reopened_file:
<8> blob_name = BlobManager.blob_name_from_file_name(file.content.name)
<9> logger.info("Uploading blob for whole file -> %s", blob_name)
<10> await container_client.upload_blob(blob_name, reopened_file, overwrite=True)
<11>
<12> if self.store_page_images:
<13> if os.path.splitext(file.content.name)[1].lower() == ".pdf":
<14> return await self.upload_pdf_blob_images(service_client, container_client, file)
<15> else:
<16> logger.info("File %s is not a PDF, skipping image upload", file.content.name)
<17>
<18> return None
<19>
|
===========unchanged ref 0===========
at: app.backend.prepdocslib.blobmanager
logger = logging.getLogger("ingester")
BlobManager(endpoint: str, container: str, account: str, credential: Union[AsyncTokenCredential, str], resourceGroup: str, subscriptionId: str, store_page_images: bool=False)
at: app.backend.prepdocslib.blobmanager.BlobManager
blob_name_from_file_name(filename) -> str
at: app.backend.prepdocslib.blobmanager.BlobManager.__init__
self.endpoint = endpoint
self.credential = credential
self.container = container
at: logging.Logger
info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
at: os.path
splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]
splitext(p: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]
at: typing
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
# module: tests.test_blob_manager
@pytest.mark.asyncio
@pytest.mark.skipif(sys.version_info.minor < 10, reason="requires Python 3.10 or higher")
async def test_create_container_upon_upload(monkeypatch, mock_env, blob_manager):
with NamedTemporaryFile(suffix=".pdf") as temp_file:
f = File(temp_file.file)
filename = os.path.basename(f.content.name)
# Set up mocks used by upload_blob
async def mock_exists(*args, **kwargs):
return False
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.exists", mock_exists)
async def mock_create_container(*args, **kwargs):
return
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.create_container", mock_create_container)
async def mock_upload_blob(self, name, *args, **kwargs):
assert name == filename
+ return azure.storage.blob.aio.BlobClient.from_blob_url(
+ "https://test.blob.core.windows.net/test/test.pdf", credential=MockAzureCredential()
+ )
- return True
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.upload_blob", mock_upload_blob)
await blob_manager.upload_blob(f)
+ assert f.url == "https://test.blob.core.windows.net/test/test.pdf"
===========changed ref 1===========
# module: tests.test_blob_manager
@pytest.mark.asyncio
@pytest.mark.skipif(sys.version_info.minor < 10, reason="requires Python 3.10 or higher")
async def test_upload_blob_no_image(monkeypatch, mock_env, caplog):
blob_manager = BlobManager(
endpoint=f"https://{os.environ['AZURE_STORAGE_ACCOUNT']}.blob.core.windows.net",
credential=MockAzureCredential(),
container=os.environ["AZURE_STORAGE_CONTAINER"],
account=os.environ["AZURE_STORAGE_ACCOUNT"],
resourceGroup=os.environ["AZURE_STORAGE_RESOURCE_GROUP"],
subscriptionId=os.environ["AZURE_SUBSCRIPTION_ID"],
store_page_images=True,
)
with NamedTemporaryFile(suffix=".xlsx") as temp_file:
f = File(temp_file.file)
filename = os.path.basename(f.content.name)
# Set up mocks used by upload_blob
async def mock_exists(*args, **kwargs):
return True
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.exists", mock_exists)
async def mock_upload_blob(self, name, *args, **kwargs):
assert name == filename
+ return azure.storage.blob.aio.BlobClient.from_blob_url(
+ "https://test.blob.core.windows.net/test/test.xlsx", credential=MockAzureCredential()
+ )
- return True
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.upload_blob", mock_upload_blob)
with caplog.at_level("INFO"):
await blob_manager.upload_blob(f)
+ assert f.url == "https://test.blob.core.windows.net/test/test.xlsx"
assert "skipping image upload" in caplog.text
===========changed ref 2===========
# module: tests.test_blob_manager
@pytest.mark.asyncio
@pytest.mark.skipif(sys.version_info.minor < 10, reason="requires Python 3.10 or higher")
async def test_upload_and_remove_all(monkeypatch, mock_env, blob_manager):
with NamedTemporaryFile(suffix=".pdf") as temp_file:
f = File(temp_file.file)
filename = os.path.basename(f.content.name)
# Set up mocks used by upload_blob
async def mock_exists(*args, **kwargs):
return True
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.exists", mock_exists)
async def mock_upload_blob(self, name, *args, **kwargs):
assert name == filename
+ return azure.storage.blob.aio.BlobClient.from_blob_url(
+ "https://test.blob.core.windows.net/test/test.pdf", credential=MockAzureCredential()
+ )
- return True
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.upload_blob", mock_upload_blob)
await blob_manager.upload_blob(f)
+ assert f.url == "https://test.blob.core.windows.net/test/test.pdf"
# Set up mocks used by remove_blob
def mock_list_blob_names(*args, **kwargs):
assert kwargs.get("name_starts_with") is None
class AsyncBlobItemsIterator:
def __init__(self, file):
self.files = [file]
def __aiter__(self):
return self
async def __anext__(self):
if self.files:
return self.files.pop()
raise StopAsyncIteration
return AsyncBlobItemsIterator(filename)
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.list_blob_names", mock_list_blob_names)
async def mock_delete_</s>
===========changed ref 3===========
# module: tests.test_blob_manager
@pytest.mark.asyncio
@pytest.mark.skipif(sys.version_info.minor < 10, reason="requires Python 3.10 or higher")
async def test_upload_and_remove_all(monkeypatch, mock_env, blob_manager):
# offset: 1
<s>.aio.ContainerClient.list_blob_names", mock_list_blob_names)
async def mock_delete_blob(self, name, *args, **kwargs):
assert name == filename
return True
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.delete_blob", mock_delete_blob)
await blob_manager.remove_blob()
|
app.backend.prepdocslib.searchmanager/SearchManager.create_index
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
0124725ad85726aa3f62450e16fb136a63154f69
|
Adds storageURL field to track file location (#1535)
|
<45>:<add> ),
<add> SimpleField(
<add> name="storageUrl",
<add> type="Edm.String",
<add> filterable=True,
<add> facetable=False,
|
# module: app.backend.prepdocslib.searchmanager
class SearchManager:
def create_index(self, vectorizers: Optional[List[VectorSearchVectorizer]] = None):
<0> logger.info("Ensuring search index %s exists", self.search_info.index_name)
<1>
<2> async with self.search_info.create_search_index_client() as search_index_client:
<3> fields = [
<4> (
<5> SimpleField(name="id", type="Edm.String", key=True)
<6> if not self.use_int_vectorization
<7> else SearchField(
<8> name="id",
<9> type="Edm.String",
<10> key=True,
<11> sortable=True,
<12> filterable=True,
<13> facetable=True,
<14> analyzer_name="keyword",
<15> )
<16> ),
<17> SearchableField(
<18> name="content",
<19> type="Edm.String",
<20> analyzer_name=self.search_analyzer_name,
<21> ),
<22> SearchField(
<23> name="embedding",
<24> type=SearchFieldDataType.Collection(SearchFieldDataType.Single),
<25> hidden=False,
<26> searchable=True,
<27> filterable=False,
<28> sortable=False,
<29> facetable=False,
<30> vector_search_dimensions=self.embedding_dimensions,
<31> vector_search_profile_name="embedding_config",
<32> ),
<33> SimpleField(name="category", type="Edm.String", filterable=True, facetable=True),
<34> SimpleField(
<35> name="sourcepage",
<36> type="Edm.String",
<37> filterable=True,
<38> facetable=True,
<39> ),
<40> SimpleField(
<41> name="sourcefile",
<42> type="Edm.String",
<43> filterable=True,
<44> facetable=True,
<45> ),
<46> ]
<47> if self.use_acls:
<48> fields.append(
<49> SimpleField(
<50> name="oids",
<51> </s>
|
===========below chunk 0===========
# module: app.backend.prepdocslib.searchmanager
class SearchManager:
def create_index(self, vectorizers: Optional[List[VectorSearchVectorizer]] = None):
# offset: 1
filterable=True,
)
)
fields.append(
SimpleField(
name="groups",
type=SearchFieldDataType.Collection(SearchFieldDataType.String),
filterable=True,
)
)
if self.use_int_vectorization:
fields.append(SearchableField(name="parent_id", type="Edm.String", filterable=True))
if self.search_images:
fields.append(
SearchField(
name="imageEmbedding",
type=SearchFieldDataType.Collection(SearchFieldDataType.Single),
hidden=False,
searchable=True,
filterable=False,
sortable=False,
facetable=False,
vector_search_dimensions=1024,
vector_search_profile_name="embedding_config",
),
)
index = SearchIndex(
name=self.search_info.index_name,
fields=fields,
semantic_search=SemanticSearch(
configurations=[
SemanticConfiguration(
name="default",
prioritized_fields=SemanticPrioritizedFields(
title_field=None, content_fields=[SemanticField(field_name="content")]
),
)
]
),
vector_search=VectorSearch(
algorithms=[
HnswAlgorithmConfiguration(
name="hnsw_config",
parameters=HnswParameters(metric="cosine"),
)
],
profiles=[
VectorSearchProfile(
name="embedding_config",
algorithm_configuration_name="hnsw_config",
vectorizer=(
f"{self.search_info.index_name}-vectorizer" if self.use_int_vectorization else None
),
),
],
vectorizers=vectorizers,
),
)
if self.search_info.</s>
===========below chunk 1===========
# module: app.backend.prepdocslib.searchmanager
class SearchManager:
def create_index(self, vectorizers: Optional[List[VectorSearchVectorizer]] = None):
# offset: 2
<s> ),
],
vectorizers=vectorizers,
),
)
if self.search_info.index_name not in [name async for name in search_index_client.list_index_names()]:
logger.info("Creating %s search index", self.search_info.index_name)
await search_index_client.create_index(index)
else:
logger.info("Search index %s already exists", self.search_info.index_name)
===========unchanged ref 0===========
at: app.backend.prepdocslib.searchmanager
logger = logging.getLogger("ingester")
at: app.backend.prepdocslib.searchmanager.SearchManager.__init__
self.search_info = search_info
self.search_analyzer_name = search_analyzer_name
self.use_acls = use_acls
self.use_int_vectorization = use_int_vectorization
self.embedding_dimensions = self.embeddings.open_ai_dimensions if self.embeddings else 1536
self.search_images = search_images
at: logging.Logger
info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
at: prepdocslib.strategy.SearchInfo
create_search_index_client() -> SearchIndexClient
at: prepdocslib.strategy.SearchInfo.__init__
self.index_name = index_name
at: typing
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
# module: tests.test_blob_manager
@pytest.mark.asyncio
@pytest.mark.skipif(sys.version_info.minor < 10, reason="requires Python 3.10 or higher")
async def test_create_container_upon_upload(monkeypatch, mock_env, blob_manager):
with NamedTemporaryFile(suffix=".pdf") as temp_file:
f = File(temp_file.file)
filename = os.path.basename(f.content.name)
# Set up mocks used by upload_blob
async def mock_exists(*args, **kwargs):
return False
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.exists", mock_exists)
async def mock_create_container(*args, **kwargs):
return
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.create_container", mock_create_container)
async def mock_upload_blob(self, name, *args, **kwargs):
assert name == filename
+ return azure.storage.blob.aio.BlobClient.from_blob_url(
+ "https://test.blob.core.windows.net/test/test.pdf", credential=MockAzureCredential()
+ )
- return True
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.upload_blob", mock_upload_blob)
await blob_manager.upload_blob(f)
+ assert f.url == "https://test.blob.core.windows.net/test/test.pdf"
===========changed ref 1===========
# module: app.backend.prepdocslib.blobmanager
class BlobManager:
def upload_blob(self, file: File) -> Optional[List[str]]:
async with BlobServiceClient(
account_url=self.endpoint, credential=self.credential, max_single_put_size=4 * 1024 * 1024
) as service_client, service_client.get_container_client(self.container) as container_client:
if not await container_client.exists():
await container_client.create_container()
# Re-open and upload the original file
+ if file.url is None:
+ with open(file.content.name, "rb") as reopened_file:
- with open(file.content.name, "rb") as reopened_file:
+ blob_name = BlobManager.blob_name_from_file_name(file.content.name)
- blob_name = BlobManager.blob_name_from_file_name(file.content.name)
+ logger.info("Uploading blob for whole file -> %s", blob_name)
- logger.info("Uploading blob for whole file -> %s", blob_name)
+ blob_client = await container_client.upload_blob(blob_name, reopened_file, overwrite=True)
- await container_client.upload_blob(blob_name, reopened_file, overwrite=True)
+ file.url = blob_client.url
if self.store_page_images:
if os.path.splitext(file.content.name)[1].lower() == ".pdf":
return await self.upload_pdf_blob_images(service_client, container_client, file)
else:
logger.info("File %s is not a PDF, skipping image upload", file.content.name)
return None
|
app.backend.prepdocslib.searchmanager/SearchManager.update_content
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
0124725ad85726aa3f62450e16fb136a63154f69
|
Adds storageURL field to track file location (#1535)
|
<26>:<add> if url:
<add> for document in documents:
<add> document["storageUrl"] = url
|
# module: app.backend.prepdocslib.searchmanager
class SearchManager:
+ def update_content(
+ self, sections: List[Section], image_embeddings: Optional[List[List[float]]] = None, url: Optional[str] = None
- def update_content(self, sections: List[Section], image_embeddings: Optional[List[List[float]]] = None):
+ ):
<0> MAX_BATCH_SIZE = 1000
<1> section_batches = [sections[i : i + MAX_BATCH_SIZE] for i in range(0, len(sections), MAX_BATCH_SIZE)]
<2>
<3> async with self.search_info.create_search_client() as search_client:
<4> for batch_index, batch in enumerate(section_batches):
<5> documents = [
<6> {
<7> "id": f"{section.content.filename_to_id()}-page-{section_index + batch_index * MAX_BATCH_SIZE}",
<8> "content": section.split_page.text,
<9> "category": section.category,
<10> "sourcepage": (
<11> BlobManager.blob_image_name_from_file_page(
<12> filename=section.content.filename(),
<13> page=section.split_page.page_num,
<14> )
<15> if image_embeddings
<16> else BlobManager.sourcepage_from_file_page(
<17> filename=section.content.filename(),
<18> page=section.split_page.page_num,
<19> )
<20> ),
<21> "sourcefile": section.content.filename(),
<22> **section.content.acls,
<23> }
<24> for section_index, section in enumerate(batch)
<25> ]
<26> if self.embeddings:
<27> embeddings = await self.embeddings.create_embeddings(
<28> texts=[section.split_page.text for section in batch]
<29> )
<30> for i, document in enumerate(documents):
<31> document["embedding"] = embeddings[i]
<32> if image_embeddings:
<33> for i, (document, section) in enumerate(</s>
|
===========below chunk 0===========
# module: app.backend.prepdocslib.searchmanager
class SearchManager:
+ def update_content(
+ self, sections: List[Section], image_embeddings: Optional[List[List[float]]] = None, url: Optional[str] = None
- def update_content(self, sections: List[Section], image_embeddings: Optional[List[List[float]]] = None):
+ ):
# offset: 1
document["imageEmbedding"] = image_embeddings[section.split_page.page_num]
await search_client.upload_documents(documents)
===========unchanged ref 0===========
at: app.backend.prepdocslib.searchmanager
logger = logging.getLogger("ingester")
Section(split_page: SplitPage, content: File, category: Optional[str]=None)
at: app.backend.prepdocslib.searchmanager.SearchManager.__init__
self.search_info = search_info
at: app.backend.prepdocslib.searchmanager.SearchManager.create_index
index = SearchIndex(
name=self.search_info.index_name,
fields=fields,
semantic_search=SemanticSearch(
configurations=[
SemanticConfiguration(
name="default",
prioritized_fields=SemanticPrioritizedFields(
title_field=None, content_fields=[SemanticField(field_name="content")]
),
)
]
),
vector_search=VectorSearch(
algorithms=[
HnswAlgorithmConfiguration(
name="hnsw_config",
parameters=HnswParameters(metric="cosine"),
)
],
profiles=[
VectorSearchProfile(
name="embedding_config",
algorithm_configuration_name="hnsw_config",
vectorizer=(
f"{self.search_info.index_name}-vectorizer" if self.use_int_vectorization else None
),
),
],
vectorizers=vectorizers,
),
)
at: logging.Logger
info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
at: prepdocslib.strategy.SearchInfo.__init__
self.index_name = index_name
at: typing
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
# module: app.backend.prepdocslib.searchmanager
class SearchManager:
def create_index(self, vectorizers: Optional[List[VectorSearchVectorizer]] = None):
logger.info("Ensuring search index %s exists", self.search_info.index_name)
async with self.search_info.create_search_index_client() as search_index_client:
fields = [
(
SimpleField(name="id", type="Edm.String", key=True)
if not self.use_int_vectorization
else SearchField(
name="id",
type="Edm.String",
key=True,
sortable=True,
filterable=True,
facetable=True,
analyzer_name="keyword",
)
),
SearchableField(
name="content",
type="Edm.String",
analyzer_name=self.search_analyzer_name,
),
SearchField(
name="embedding",
type=SearchFieldDataType.Collection(SearchFieldDataType.Single),
hidden=False,
searchable=True,
filterable=False,
sortable=False,
facetable=False,
vector_search_dimensions=self.embedding_dimensions,
vector_search_profile_name="embedding_config",
),
SimpleField(name="category", type="Edm.String", filterable=True, facetable=True),
SimpleField(
name="sourcepage",
type="Edm.String",
filterable=True,
facetable=True,
),
SimpleField(
name="sourcefile",
type="Edm.String",
filterable=True,
facetable=True,
+ ),
+ SimpleField(
+ name="storageUrl",
+ type="Edm.String",
+ filterable=True,
+ facetable=False,
),
]
if self.use_acls:
fields.append(
SimpleField(
name="oids",
type=SearchFieldDataType.</s>
===========changed ref 1===========
# module: app.backend.prepdocslib.searchmanager
class SearchManager:
def create_index(self, vectorizers: Optional[List[VectorSearchVectorizer]] = None):
# offset: 1
<s>use_acls:
fields.append(
SimpleField(
name="oids",
type=SearchFieldDataType.Collection(SearchFieldDataType.String),
filterable=True,
)
)
fields.append(
SimpleField(
name="groups",
type=SearchFieldDataType.Collection(SearchFieldDataType.String),
filterable=True,
)
)
if self.use_int_vectorization:
fields.append(SearchableField(name="parent_id", type="Edm.String", filterable=True))
if self.search_images:
fields.append(
SearchField(
name="imageEmbedding",
type=SearchFieldDataType.Collection(SearchFieldDataType.Single),
hidden=False,
searchable=True,
filterable=False,
sortable=False,
facetable=False,
vector_search_dimensions=1024,
vector_search_profile_name="embedding_config",
),
)
index = SearchIndex(
name=self.search_info.index_name,
fields=fields,
semantic_search=SemanticSearch(
configurations=[
SemanticConfiguration(
name="default",
prioritized_fields=SemanticPrioritizedFields(
title_field=None, content_fields=[SemanticField(field_name="content")]
),
)
]
),
vector_search=VectorSearch(
algorithms=[
HnswAlgorithmConfiguration(
name="hnsw_config",
parameters=HnswParameters(metric="cosine"),
)
],
profiles=[
VectorSearchProfile(
name="embedding_config",
algorithm_configuration_name="hnsw</s>
===========changed ref 2===========
# module: app.backend.prepdocslib.searchmanager
class SearchManager:
def create_index(self, vectorizers: Optional[List[VectorSearchVectorizer]] = None):
# offset: 2
<s>",
vectorizer=(
f"{self.search_info.index_name}-vectorizer" if self.use_int_vectorization else None
),
),
],
vectorizers=vectorizers,
),
)
if self.search_info.index_name not in [name async for name in search_index_client.list_index_names()]:
logger.info("Creating %s search index", self.search_info.index_name)
await search_index_client.create_index(index)
else:
logger.info("Search index %s already exists", self.search_info.index_name)
|
scripts.manageacl/ManageAcl.__init__
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
0124725ad85726aa3f62450e16fb136a63154f69
|
Adds storageURL field to track file location (#1535)
|
<9>:<add> url
<del> document
<10>:<add> Full Blob storage URL of the document to manage acls for
<del> File path of the document to manage acls for
<23>:<add> self.url = url
<del> self.document = document
|
# module: scripts.manageacl
class ManageAcl:
def __init__(
self,
service_name: str,
index_name: str,
+ url: str,
- document: str,
acl_action: str,
acl_type: str,
acl: str,
credentials: Union[AsyncTokenCredential, AzureKeyCredential],
):
<0> """
<1> Initializes the command
<2>
<3> Parameters
<4> ----------
<5> service_name
<6> Name of the Azure Search service
<7> index_name
<8> Name of the Azure Search index
<9> document
<10> File path of the document to manage acls for
<11> acl_action
<12> Action to take regarding the index or document. Valid values include enable_acls (turn acls on for the entire index), view (print acls for the document), remove_all (remove all acls), remove (remove a specific acl), or add (add a specific acl)
<13> acl_type
<14> Type of acls to manage. Valid values include groups or oids.
<15> acl
<16> The actual value of the acl, if the acl action is add or remove
<17> credentials
<18> Credentials for the azure search service
<19> """
<20> self.service_name = service_name
<21> self.index_name = index_name
<22> self.credentials = credentials
<23> self.document = document
<24> self.acl_action = acl_action
<25> self.acl_type = acl_type
<26> self.acl = acl
<27>
|
===========changed ref 0===========
# module: tests.test_blob_manager
@pytest.mark.asyncio
@pytest.mark.skipif(sys.version_info.minor < 10, reason="requires Python 3.10 or higher")
async def test_create_container_upon_upload(monkeypatch, mock_env, blob_manager):
with NamedTemporaryFile(suffix=".pdf") as temp_file:
f = File(temp_file.file)
filename = os.path.basename(f.content.name)
# Set up mocks used by upload_blob
async def mock_exists(*args, **kwargs):
return False
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.exists", mock_exists)
async def mock_create_container(*args, **kwargs):
return
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.create_container", mock_create_container)
async def mock_upload_blob(self, name, *args, **kwargs):
assert name == filename
+ return azure.storage.blob.aio.BlobClient.from_blob_url(
+ "https://test.blob.core.windows.net/test/test.pdf", credential=MockAzureCredential()
+ )
- return True
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.upload_blob", mock_upload_blob)
await blob_manager.upload_blob(f)
+ assert f.url == "https://test.blob.core.windows.net/test/test.pdf"
===========changed ref 1===========
# module: app.backend.prepdocslib.blobmanager
class BlobManager:
def upload_blob(self, file: File) -> Optional[List[str]]:
async with BlobServiceClient(
account_url=self.endpoint, credential=self.credential, max_single_put_size=4 * 1024 * 1024
) as service_client, service_client.get_container_client(self.container) as container_client:
if not await container_client.exists():
await container_client.create_container()
# Re-open and upload the original file
+ if file.url is None:
+ with open(file.content.name, "rb") as reopened_file:
- with open(file.content.name, "rb") as reopened_file:
+ blob_name = BlobManager.blob_name_from_file_name(file.content.name)
- blob_name = BlobManager.blob_name_from_file_name(file.content.name)
+ logger.info("Uploading blob for whole file -> %s", blob_name)
- logger.info("Uploading blob for whole file -> %s", blob_name)
+ blob_client = await container_client.upload_blob(blob_name, reopened_file, overwrite=True)
- await container_client.upload_blob(blob_name, reopened_file, overwrite=True)
+ file.url = blob_client.url
if self.store_page_images:
if os.path.splitext(file.content.name)[1].lower() == ".pdf":
return await self.upload_pdf_blob_images(service_client, container_client, file)
else:
logger.info("File %s is not a PDF, skipping image upload", file.content.name)
return None
===========changed ref 2===========
# module: tests.test_blob_manager
@pytest.mark.asyncio
@pytest.mark.skipif(sys.version_info.minor < 10, reason="requires Python 3.10 or higher")
async def test_upload_blob_no_image(monkeypatch, mock_env, caplog):
blob_manager = BlobManager(
endpoint=f"https://{os.environ['AZURE_STORAGE_ACCOUNT']}.blob.core.windows.net",
credential=MockAzureCredential(),
container=os.environ["AZURE_STORAGE_CONTAINER"],
account=os.environ["AZURE_STORAGE_ACCOUNT"],
resourceGroup=os.environ["AZURE_STORAGE_RESOURCE_GROUP"],
subscriptionId=os.environ["AZURE_SUBSCRIPTION_ID"],
store_page_images=True,
)
with NamedTemporaryFile(suffix=".xlsx") as temp_file:
f = File(temp_file.file)
filename = os.path.basename(f.content.name)
# Set up mocks used by upload_blob
async def mock_exists(*args, **kwargs):
return True
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.exists", mock_exists)
async def mock_upload_blob(self, name, *args, **kwargs):
assert name == filename
+ return azure.storage.blob.aio.BlobClient.from_blob_url(
+ "https://test.blob.core.windows.net/test/test.xlsx", credential=MockAzureCredential()
+ )
- return True
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.upload_blob", mock_upload_blob)
with caplog.at_level("INFO"):
await blob_manager.upload_blob(f)
+ assert f.url == "https://test.blob.core.windows.net/test/test.xlsx"
assert "skipping image upload" in caplog.text
===========changed ref 3===========
# module: app.backend.prepdocslib.searchmanager
class SearchManager:
+ def update_content(
+ self, sections: List[Section], image_embeddings: Optional[List[List[float]]] = None, url: Optional[str] = None
- def update_content(self, sections: List[Section], image_embeddings: Optional[List[List[float]]] = None):
+ ):
MAX_BATCH_SIZE = 1000
section_batches = [sections[i : i + MAX_BATCH_SIZE] for i in range(0, len(sections), MAX_BATCH_SIZE)]
async with self.search_info.create_search_client() as search_client:
for batch_index, batch in enumerate(section_batches):
documents = [
{
"id": f"{section.content.filename_to_id()}-page-{section_index + batch_index * MAX_BATCH_SIZE}",
"content": section.split_page.text,
"category": section.category,
"sourcepage": (
BlobManager.blob_image_name_from_file_page(
filename=section.content.filename(),
page=section.split_page.page_num,
)
if image_embeddings
else BlobManager.sourcepage_from_file_page(
filename=section.content.filename(),
page=section.split_page.page_num,
)
),
"sourcefile": section.content.filename(),
**section.content.acls,
}
for section_index, section in enumerate(batch)
]
+ if url:
+ for document in documents:
+ document["storageUrl"] = url
if self.embeddings:
embeddings = await self.embeddings.create_embeddings(
texts=[section.split_page.text for section in batch]
)
for i, document in enumerate(documents):
document["embedding"] = embeddings[i]
if image_embeddings:
for i, (document, section) in enumerate(zip(documents, batch)):
document</s>
|
scripts.manageacl/ManageAcl.run
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
0124725ad85726aa3f62450e16fb136a63154f69
|
Adds storageURL field to track file location (#1535)
|
<16>:<add> elif self.acl_action == "update_storage_urls":
<add> await self.update_storage_urls(search_client)
<19>:<del> logging.info("ACLs updated")
<20>:<del>
|
# module: scripts.manageacl
class ManageAcl:
def run(self):
<0> endpoint = f"https://{self.service_name}.search.windows.net"
<1> if self.acl_action == "enable_acls":
<2> await self.enable_acls(endpoint)
<3> return
<4>
<5> async with SearchClient(
<6> endpoint=endpoint, index_name=self.index_name, credential=self.credentials
<7> ) as search_client:
<8> if self.acl_action == "view":
<9> await self.view_acl(search_client)
<10> elif self.acl_action == "remove":
<11> await self.remove_acl(search_client)
<12> elif self.acl_action == "remove_all":
<13> await self.remove_all_acls(search_client)
<14> elif self.acl_action == "add":
<15> await self.add_acl(search_client)
<16> else:
<17> raise Exception(f"Unknown action {self.acl_action}")
<18>
<19> logging.info("ACLs updated")
<20>
|
===========unchanged ref 0===========
at: scripts.manageacl.ManageAcl
view_acl(self, search_client: SearchClient)
view_acl(search_client: SearchClient)
remove_acl(self, search_client: SearchClient)
remove_acl(search_client: SearchClient)
remove_all_acls(self, search_client: SearchClient)
remove_all_acls(search_client: SearchClient)
add_acl(self, search_client: SearchClient)
add_acl(search_client: SearchClient)
enable_acls(endpoint: str)
enable_acls(self, endpoint: str)
at: scripts.manageacl.ManageAcl.__init__
self.service_name = service_name
self.index_name = index_name
self.credentials = credentials
self.acl_action = acl_action
===========changed ref 0===========
# module: scripts.manageacl
class ManageAcl:
def __init__(
self,
service_name: str,
index_name: str,
+ url: str,
- document: str,
acl_action: str,
acl_type: str,
acl: str,
credentials: Union[AsyncTokenCredential, AzureKeyCredential],
):
"""
Initializes the command
Parameters
----------
service_name
Name of the Azure Search service
index_name
Name of the Azure Search index
+ url
- document
+ Full Blob storage URL of the document to manage acls for
- File path of the document to manage acls for
acl_action
Action to take regarding the index or document. Valid values include enable_acls (turn acls on for the entire index), view (print acls for the document), remove_all (remove all acls), remove (remove a specific acl), or add (add a specific acl)
acl_type
Type of acls to manage. Valid values include groups or oids.
acl
The actual value of the acl, if the acl action is add or remove
credentials
Credentials for the azure search service
"""
self.service_name = service_name
self.index_name = index_name
self.credentials = credentials
+ self.url = url
- self.document = document
self.acl_action = acl_action
self.acl_type = acl_type
self.acl = acl
===========changed ref 1===========
# module: tests.test_blob_manager
@pytest.mark.asyncio
@pytest.mark.skipif(sys.version_info.minor < 10, reason="requires Python 3.10 or higher")
async def test_create_container_upon_upload(monkeypatch, mock_env, blob_manager):
with NamedTemporaryFile(suffix=".pdf") as temp_file:
f = File(temp_file.file)
filename = os.path.basename(f.content.name)
# Set up mocks used by upload_blob
async def mock_exists(*args, **kwargs):
return False
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.exists", mock_exists)
async def mock_create_container(*args, **kwargs):
return
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.create_container", mock_create_container)
async def mock_upload_blob(self, name, *args, **kwargs):
assert name == filename
+ return azure.storage.blob.aio.BlobClient.from_blob_url(
+ "https://test.blob.core.windows.net/test/test.pdf", credential=MockAzureCredential()
+ )
- return True
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.upload_blob", mock_upload_blob)
await blob_manager.upload_blob(f)
+ assert f.url == "https://test.blob.core.windows.net/test/test.pdf"
===========changed ref 2===========
# module: app.backend.prepdocslib.blobmanager
class BlobManager:
def upload_blob(self, file: File) -> Optional[List[str]]:
async with BlobServiceClient(
account_url=self.endpoint, credential=self.credential, max_single_put_size=4 * 1024 * 1024
) as service_client, service_client.get_container_client(self.container) as container_client:
if not await container_client.exists():
await container_client.create_container()
# Re-open and upload the original file
+ if file.url is None:
+ with open(file.content.name, "rb") as reopened_file:
- with open(file.content.name, "rb") as reopened_file:
+ blob_name = BlobManager.blob_name_from_file_name(file.content.name)
- blob_name = BlobManager.blob_name_from_file_name(file.content.name)
+ logger.info("Uploading blob for whole file -> %s", blob_name)
- logger.info("Uploading blob for whole file -> %s", blob_name)
+ blob_client = await container_client.upload_blob(blob_name, reopened_file, overwrite=True)
- await container_client.upload_blob(blob_name, reopened_file, overwrite=True)
+ file.url = blob_client.url
if self.store_page_images:
if os.path.splitext(file.content.name)[1].lower() == ".pdf":
return await self.upload_pdf_blob_images(service_client, container_client, file)
else:
logger.info("File %s is not a PDF, skipping image upload", file.content.name)
return None
===========changed ref 3===========
# module: tests.test_blob_manager
@pytest.mark.asyncio
@pytest.mark.skipif(sys.version_info.minor < 10, reason="requires Python 3.10 or higher")
async def test_upload_blob_no_image(monkeypatch, mock_env, caplog):
blob_manager = BlobManager(
endpoint=f"https://{os.environ['AZURE_STORAGE_ACCOUNT']}.blob.core.windows.net",
credential=MockAzureCredential(),
container=os.environ["AZURE_STORAGE_CONTAINER"],
account=os.environ["AZURE_STORAGE_ACCOUNT"],
resourceGroup=os.environ["AZURE_STORAGE_RESOURCE_GROUP"],
subscriptionId=os.environ["AZURE_SUBSCRIPTION_ID"],
store_page_images=True,
)
with NamedTemporaryFile(suffix=".xlsx") as temp_file:
f = File(temp_file.file)
filename = os.path.basename(f.content.name)
# Set up mocks used by upload_blob
async def mock_exists(*args, **kwargs):
return True
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.exists", mock_exists)
async def mock_upload_blob(self, name, *args, **kwargs):
assert name == filename
+ return azure.storage.blob.aio.BlobClient.from_blob_url(
+ "https://test.blob.core.windows.net/test/test.xlsx", credential=MockAzureCredential()
+ )
- return True
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.upload_blob", mock_upload_blob)
with caplog.at_level("INFO"):
await blob_manager.upload_blob(f)
+ assert f.url == "https://test.blob.core.windows.net/test/test.xlsx"
assert "skipping image upload" in caplog.text
|
scripts.manageacl/ManageAcl.view_acl
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
0124725ad85726aa3f62450e16fb136a63154f69
|
Adds storageURL field to track file location (#1535)
|
<0>:<add> for document in await self.get_documents(search_client):
<del> async for document in await self.get_documents(search_client):
|
# module: scripts.manageacl
class ManageAcl:
def view_acl(self, search_client: SearchClient):
<0> async for document in await self.get_documents(search_client):
<1> # Assumes the acls are consistent across all sections of the document
<2> print(json.dumps(document[self.acl_type]))
<3> return
<4>
|
===========unchanged ref 0===========
at: scripts.manageacl.ManageAcl
get_documents(search_client: SearchClient)
get_documents(self, search_client: SearchClient)
at: scripts.manageacl.ManageAcl.__init__
self.acl_action = acl_action
===========changed ref 0===========
# module: scripts.manageacl
class ManageAcl:
def run(self):
endpoint = f"https://{self.service_name}.search.windows.net"
if self.acl_action == "enable_acls":
await self.enable_acls(endpoint)
return
async with SearchClient(
endpoint=endpoint, index_name=self.index_name, credential=self.credentials
) as search_client:
if self.acl_action == "view":
await self.view_acl(search_client)
elif self.acl_action == "remove":
await self.remove_acl(search_client)
elif self.acl_action == "remove_all":
await self.remove_all_acls(search_client)
elif self.acl_action == "add":
await self.add_acl(search_client)
+ elif self.acl_action == "update_storage_urls":
+ await self.update_storage_urls(search_client)
else:
raise Exception(f"Unknown action {self.acl_action}")
- logging.info("ACLs updated")
-
===========changed ref 1===========
# module: scripts.manageacl
class ManageAcl:
def __init__(
self,
service_name: str,
index_name: str,
+ url: str,
- document: str,
acl_action: str,
acl_type: str,
acl: str,
credentials: Union[AsyncTokenCredential, AzureKeyCredential],
):
"""
Initializes the command
Parameters
----------
service_name
Name of the Azure Search service
index_name
Name of the Azure Search index
+ url
- document
+ Full Blob storage URL of the document to manage acls for
- File path of the document to manage acls for
acl_action
Action to take regarding the index or document. Valid values include enable_acls (turn acls on for the entire index), view (print acls for the document), remove_all (remove all acls), remove (remove a specific acl), or add (add a specific acl)
acl_type
Type of acls to manage. Valid values include groups or oids.
acl
The actual value of the acl, if the acl action is add or remove
credentials
Credentials for the azure search service
"""
self.service_name = service_name
self.index_name = index_name
self.credentials = credentials
+ self.url = url
- self.document = document
self.acl_action = acl_action
self.acl_type = acl_type
self.acl = acl
===========changed ref 2===========
# module: tests.test_blob_manager
@pytest.mark.asyncio
@pytest.mark.skipif(sys.version_info.minor < 10, reason="requires Python 3.10 or higher")
async def test_create_container_upon_upload(monkeypatch, mock_env, blob_manager):
with NamedTemporaryFile(suffix=".pdf") as temp_file:
f = File(temp_file.file)
filename = os.path.basename(f.content.name)
# Set up mocks used by upload_blob
async def mock_exists(*args, **kwargs):
return False
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.exists", mock_exists)
async def mock_create_container(*args, **kwargs):
return
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.create_container", mock_create_container)
async def mock_upload_blob(self, name, *args, **kwargs):
assert name == filename
+ return azure.storage.blob.aio.BlobClient.from_blob_url(
+ "https://test.blob.core.windows.net/test/test.pdf", credential=MockAzureCredential()
+ )
- return True
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.upload_blob", mock_upload_blob)
await blob_manager.upload_blob(f)
+ assert f.url == "https://test.blob.core.windows.net/test/test.pdf"
===========changed ref 3===========
# module: app.backend.prepdocslib.blobmanager
class BlobManager:
def upload_blob(self, file: File) -> Optional[List[str]]:
async with BlobServiceClient(
account_url=self.endpoint, credential=self.credential, max_single_put_size=4 * 1024 * 1024
) as service_client, service_client.get_container_client(self.container) as container_client:
if not await container_client.exists():
await container_client.create_container()
# Re-open and upload the original file
+ if file.url is None:
+ with open(file.content.name, "rb") as reopened_file:
- with open(file.content.name, "rb") as reopened_file:
+ blob_name = BlobManager.blob_name_from_file_name(file.content.name)
- blob_name = BlobManager.blob_name_from_file_name(file.content.name)
+ logger.info("Uploading blob for whole file -> %s", blob_name)
- logger.info("Uploading blob for whole file -> %s", blob_name)
+ blob_client = await container_client.upload_blob(blob_name, reopened_file, overwrite=True)
- await container_client.upload_blob(blob_name, reopened_file, overwrite=True)
+ file.url = blob_client.url
if self.store_page_images:
if os.path.splitext(file.content.name)[1].lower() == ".pdf":
return await self.upload_pdf_blob_images(service_client, container_client, file)
else:
logger.info("File %s is not a PDF, skipping image upload", file.content.name)
return None
|
scripts.manageacl/ManageAcl.remove_acl
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
0124725ad85726aa3f62450e16fb136a63154f69
|
Adds storageURL field to track file location (#1535)
|
<1>:<add> for document in await self.get_documents(search_client):
<del> async for document in await self.get_documents(search_client):
<2>:<add> new_acls = document[self.acl_type]
<add> if any(acl_value == self.acl for acl_value in new_acls):
<add> new_acls = [acl_value for acl_value in document[self.acl_type] if acl_value != self.acl]
<del> new_acls = [acl_value for acl_value in document[self.acl_type] if acl_value != self.acl]
<3>:<add> documents_to_merge.append({"id": document["id"], self.acl_type: new_acls})
<del> documents_to_merge.append({"id": document["id"], self.acl_type: new_acls})
<4>:<add> else:
<add> logger.info("Search document %s does not have %s acl %s", document["id"], self.acl_type, self.acl)
<6>:<add> logger.info("Removing acl %s from %d search documents", self.acl, len(documents_to_merge))
<7>:<add> else:
<add> logger.info("Not updating any search documents")
|
# module: scripts.manageacl
class ManageAcl:
def remove_acl(self, search_client: SearchClient):
<0> documents_to_merge = []
<1> async for document in await self.get_documents(search_client):
<2> new_acls = [acl_value for acl_value in document[self.acl_type] if acl_value != self.acl]
<3> documents_to_merge.append({"id": document["id"], self.acl_type: new_acls})
<4>
<5> if len(documents_to_merge) > 0:
<6> await search_client.merge_documents(documents=documents_to_merge)
<7>
|
===========unchanged ref 0===========
at: json
dumps(obj: Any, *, skipkeys: bool=..., ensure_ascii: bool=..., check_circular: bool=..., allow_nan: bool=..., cls: Optional[Type[JSONEncoder]]=..., indent: Union[None, int, str]=..., separators: Optional[Tuple[str, str]]=..., default: Optional[Callable[[Any], Any]]=..., sort_keys: bool=..., **kwds: Any) -> str
at: scripts.manageacl.ManageAcl
get_documents(search_client: SearchClient)
get_documents(self, search_client: SearchClient)
at: scripts.manageacl.ManageAcl.__init__
self.acl_type = acl_type
self.acl = acl
===========changed ref 0===========
# module: scripts.manageacl
class ManageAcl:
def view_acl(self, search_client: SearchClient):
+ for document in await self.get_documents(search_client):
- async for document in await self.get_documents(search_client):
# Assumes the acls are consistent across all sections of the document
print(json.dumps(document[self.acl_type]))
return
===========changed ref 1===========
# module: scripts.manageacl
class ManageAcl:
def run(self):
endpoint = f"https://{self.service_name}.search.windows.net"
if self.acl_action == "enable_acls":
await self.enable_acls(endpoint)
return
async with SearchClient(
endpoint=endpoint, index_name=self.index_name, credential=self.credentials
) as search_client:
if self.acl_action == "view":
await self.view_acl(search_client)
elif self.acl_action == "remove":
await self.remove_acl(search_client)
elif self.acl_action == "remove_all":
await self.remove_all_acls(search_client)
elif self.acl_action == "add":
await self.add_acl(search_client)
+ elif self.acl_action == "update_storage_urls":
+ await self.update_storage_urls(search_client)
else:
raise Exception(f"Unknown action {self.acl_action}")
- logging.info("ACLs updated")
-
===========changed ref 2===========
# module: scripts.manageacl
class ManageAcl:
def __init__(
self,
service_name: str,
index_name: str,
+ url: str,
- document: str,
acl_action: str,
acl_type: str,
acl: str,
credentials: Union[AsyncTokenCredential, AzureKeyCredential],
):
"""
Initializes the command
Parameters
----------
service_name
Name of the Azure Search service
index_name
Name of the Azure Search index
+ url
- document
+ Full Blob storage URL of the document to manage acls for
- File path of the document to manage acls for
acl_action
Action to take regarding the index or document. Valid values include enable_acls (turn acls on for the entire index), view (print acls for the document), remove_all (remove all acls), remove (remove a specific acl), or add (add a specific acl)
acl_type
Type of acls to manage. Valid values include groups or oids.
acl
The actual value of the acl, if the acl action is add or remove
credentials
Credentials for the azure search service
"""
self.service_name = service_name
self.index_name = index_name
self.credentials = credentials
+ self.url = url
- self.document = document
self.acl_action = acl_action
self.acl_type = acl_type
self.acl = acl
===========changed ref 3===========
# module: tests.test_blob_manager
@pytest.mark.asyncio
@pytest.mark.skipif(sys.version_info.minor < 10, reason="requires Python 3.10 or higher")
async def test_create_container_upon_upload(monkeypatch, mock_env, blob_manager):
with NamedTemporaryFile(suffix=".pdf") as temp_file:
f = File(temp_file.file)
filename = os.path.basename(f.content.name)
# Set up mocks used by upload_blob
async def mock_exists(*args, **kwargs):
return False
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.exists", mock_exists)
async def mock_create_container(*args, **kwargs):
return
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.create_container", mock_create_container)
async def mock_upload_blob(self, name, *args, **kwargs):
assert name == filename
+ return azure.storage.blob.aio.BlobClient.from_blob_url(
+ "https://test.blob.core.windows.net/test/test.pdf", credential=MockAzureCredential()
+ )
- return True
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.upload_blob", mock_upload_blob)
await blob_manager.upload_blob(f)
+ assert f.url == "https://test.blob.core.windows.net/test/test.pdf"
===========changed ref 4===========
# module: app.backend.prepdocslib.blobmanager
class BlobManager:
def upload_blob(self, file: File) -> Optional[List[str]]:
async with BlobServiceClient(
account_url=self.endpoint, credential=self.credential, max_single_put_size=4 * 1024 * 1024
) as service_client, service_client.get_container_client(self.container) as container_client:
if not await container_client.exists():
await container_client.create_container()
# Re-open and upload the original file
+ if file.url is None:
+ with open(file.content.name, "rb") as reopened_file:
- with open(file.content.name, "rb") as reopened_file:
+ blob_name = BlobManager.blob_name_from_file_name(file.content.name)
- blob_name = BlobManager.blob_name_from_file_name(file.content.name)
+ logger.info("Uploading blob for whole file -> %s", blob_name)
- logger.info("Uploading blob for whole file -> %s", blob_name)
+ blob_client = await container_client.upload_blob(blob_name, reopened_file, overwrite=True)
- await container_client.upload_blob(blob_name, reopened_file, overwrite=True)
+ file.url = blob_client.url
if self.store_page_images:
if os.path.splitext(file.content.name)[1].lower() == ".pdf":
return await self.upload_pdf_blob_images(service_client, container_client, file)
else:
logger.info("File %s is not a PDF, skipping image upload", file.content.name)
return None
|
scripts.manageacl/ManageAcl.remove_all_acls
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
0124725ad85726aa3f62450e16fb136a63154f69
|
Adds storageURL field to track file location (#1535)
|
<1>:<add> for document in await self.get_documents(search_client):
<del> async for document in await self.get_documents(search_client):
<2>:<add> if len(document[self.acl_type]) > 0:
<add> documents_to_merge.append({"id": document["id"], self.acl_type: []})
<del> documents_to_merge.append({"id": document["id"], self.acl_type: []})
<3>:<add> else:
<add> logger.info("Search document %s already has no %s acls", document["id"], self.acl_type)
<5>:<add> logger.info("Removing all %s acls from %d search documents", self.acl_type, len(documents_to_merge))
<6>:<add> else:
<add> logger.info("Not updating any search documents")
|
# module: scripts.manageacl
class ManageAcl:
def remove_all_acls(self, search_client: SearchClient):
<0> documents_to_merge = []
<1> async for document in await self.get_documents(search_client):
<2> documents_to_merge.append({"id": document["id"], self.acl_type: []})
<3>
<4> if len(documents_to_merge) > 0:
<5> await search_client.merge_documents(documents=documents_to_merge)
<6>
|
===========unchanged ref 0===========
at: logging.Logger
info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
at: scripts.manageacl
logger = logging.getLogger("manageacl")
at: scripts.manageacl.ManageAcl.__init__
self.acl_type = acl_type
self.acl = acl
at: scripts.manageacl.ManageAcl.remove_acl
documents_to_merge = []
new_acls = document[self.acl_type]
new_acls = [acl_value for acl_value in document[self.acl_type] if acl_value != self.acl]
===========changed ref 0===========
# module: scripts.manageacl
class ManageAcl:
def view_acl(self, search_client: SearchClient):
+ for document in await self.get_documents(search_client):
- async for document in await self.get_documents(search_client):
# Assumes the acls are consistent across all sections of the document
print(json.dumps(document[self.acl_type]))
return
===========changed ref 1===========
# module: scripts.manageacl
class ManageAcl:
def run(self):
endpoint = f"https://{self.service_name}.search.windows.net"
if self.acl_action == "enable_acls":
await self.enable_acls(endpoint)
return
async with SearchClient(
endpoint=endpoint, index_name=self.index_name, credential=self.credentials
) as search_client:
if self.acl_action == "view":
await self.view_acl(search_client)
elif self.acl_action == "remove":
await self.remove_acl(search_client)
elif self.acl_action == "remove_all":
await self.remove_all_acls(search_client)
elif self.acl_action == "add":
await self.add_acl(search_client)
+ elif self.acl_action == "update_storage_urls":
+ await self.update_storage_urls(search_client)
else:
raise Exception(f"Unknown action {self.acl_action}")
- logging.info("ACLs updated")
-
===========changed ref 2===========
# module: scripts.manageacl
class ManageAcl:
def __init__(
self,
service_name: str,
index_name: str,
+ url: str,
- document: str,
acl_action: str,
acl_type: str,
acl: str,
credentials: Union[AsyncTokenCredential, AzureKeyCredential],
):
"""
Initializes the command
Parameters
----------
service_name
Name of the Azure Search service
index_name
Name of the Azure Search index
+ url
- document
+ Full Blob storage URL of the document to manage acls for
- File path of the document to manage acls for
acl_action
Action to take regarding the index or document. Valid values include enable_acls (turn acls on for the entire index), view (print acls for the document), remove_all (remove all acls), remove (remove a specific acl), or add (add a specific acl)
acl_type
Type of acls to manage. Valid values include groups or oids.
acl
The actual value of the acl, if the acl action is add or remove
credentials
Credentials for the azure search service
"""
self.service_name = service_name
self.index_name = index_name
self.credentials = credentials
+ self.url = url
- self.document = document
self.acl_action = acl_action
self.acl_type = acl_type
self.acl = acl
===========changed ref 3===========
# module: scripts.manageacl
class ManageAcl:
def remove_acl(self, search_client: SearchClient):
documents_to_merge = []
+ for document in await self.get_documents(search_client):
- async for document in await self.get_documents(search_client):
+ new_acls = document[self.acl_type]
+ if any(acl_value == self.acl for acl_value in new_acls):
+ new_acls = [acl_value for acl_value in document[self.acl_type] if acl_value != self.acl]
- new_acls = [acl_value for acl_value in document[self.acl_type] if acl_value != self.acl]
+ documents_to_merge.append({"id": document["id"], self.acl_type: new_acls})
- documents_to_merge.append({"id": document["id"], self.acl_type: new_acls})
+ else:
+ logger.info("Search document %s does not have %s acl %s", document["id"], self.acl_type, self.acl)
if len(documents_to_merge) > 0:
+ logger.info("Removing acl %s from %d search documents", self.acl, len(documents_to_merge))
await search_client.merge_documents(documents=documents_to_merge)
+ else:
+ logger.info("Not updating any search documents")
===========changed ref 4===========
# module: tests.test_blob_manager
@pytest.mark.asyncio
@pytest.mark.skipif(sys.version_info.minor < 10, reason="requires Python 3.10 or higher")
async def test_create_container_upon_upload(monkeypatch, mock_env, blob_manager):
with NamedTemporaryFile(suffix=".pdf") as temp_file:
f = File(temp_file.file)
filename = os.path.basename(f.content.name)
# Set up mocks used by upload_blob
async def mock_exists(*args, **kwargs):
return False
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.exists", mock_exists)
async def mock_create_container(*args, **kwargs):
return
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.create_container", mock_create_container)
async def mock_upload_blob(self, name, *args, **kwargs):
assert name == filename
+ return azure.storage.blob.aio.BlobClient.from_blob_url(
+ "https://test.blob.core.windows.net/test/test.pdf", credential=MockAzureCredential()
+ )
- return True
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.upload_blob", mock_upload_blob)
await blob_manager.upload_blob(f)
+ assert f.url == "https://test.blob.core.windows.net/test/test.pdf"
|
scripts.manageacl/ManageAcl.add_acl
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
0124725ad85726aa3f62450e16fb136a63154f69
|
Adds storageURL field to track file location (#1535)
|
<1>:<add> for document in await self.get_documents(search_client):
<del> async for document in await self.get_documents(search_client):
<5>:<add> documents_to_merge.append({"id": document["id"], self.acl_type: new_acls})
<del> documents_to_merge.append({"id": document["id"], self.acl_type: new_acls})
<6>:<add> else:
<add> logger.info("Search document %s already has %s acl %s", document["id"], self.acl_type, self.acl)
<8>:<add> logger.info("Adding acl %s to %d search documents", self.acl, len(documents_to_merge))
<9>:<add> else:
<add> logger.info("Not updating any search documents")
|
# module: scripts.manageacl
class ManageAcl:
def add_acl(self, search_client: SearchClient):
<0> documents_to_merge = []
<1> async for document in await self.get_documents(search_client):
<2> new_acls = document[self.acl_type]
<3> if not any(acl_value == self.acl for acl_value in new_acls):
<4> new_acls.append(self.acl)
<5> documents_to_merge.append({"id": document["id"], self.acl_type: new_acls})
<6>
<7> if len(documents_to_merge) > 0:
<8> await search_client.merge_documents(documents=documents_to_merge)
<9>
|
===========unchanged ref 0===========
at: logging.Logger
info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
at: scripts.manageacl
logger = logging.getLogger("manageacl")
at: scripts.manageacl.ManageAcl
get_documents(search_client: SearchClient)
get_documents(self, search_client: SearchClient)
at: scripts.manageacl.ManageAcl.__init__
self.acl_type = acl_type
===========changed ref 0===========
# module: scripts.manageacl
class ManageAcl:
def view_acl(self, search_client: SearchClient):
+ for document in await self.get_documents(search_client):
- async for document in await self.get_documents(search_client):
# Assumes the acls are consistent across all sections of the document
print(json.dumps(document[self.acl_type]))
return
===========changed ref 1===========
# module: scripts.manageacl
class ManageAcl:
def remove_all_acls(self, search_client: SearchClient):
documents_to_merge = []
+ for document in await self.get_documents(search_client):
- async for document in await self.get_documents(search_client):
+ if len(document[self.acl_type]) > 0:
+ documents_to_merge.append({"id": document["id"], self.acl_type: []})
- documents_to_merge.append({"id": document["id"], self.acl_type: []})
+ else:
+ logger.info("Search document %s already has no %s acls", document["id"], self.acl_type)
if len(documents_to_merge) > 0:
+ logger.info("Removing all %s acls from %d search documents", self.acl_type, len(documents_to_merge))
await search_client.merge_documents(documents=documents_to_merge)
+ else:
+ logger.info("Not updating any search documents")
===========changed ref 2===========
# module: scripts.manageacl
class ManageAcl:
def run(self):
endpoint = f"https://{self.service_name}.search.windows.net"
if self.acl_action == "enable_acls":
await self.enable_acls(endpoint)
return
async with SearchClient(
endpoint=endpoint, index_name=self.index_name, credential=self.credentials
) as search_client:
if self.acl_action == "view":
await self.view_acl(search_client)
elif self.acl_action == "remove":
await self.remove_acl(search_client)
elif self.acl_action == "remove_all":
await self.remove_all_acls(search_client)
elif self.acl_action == "add":
await self.add_acl(search_client)
+ elif self.acl_action == "update_storage_urls":
+ await self.update_storage_urls(search_client)
else:
raise Exception(f"Unknown action {self.acl_action}")
- logging.info("ACLs updated")
-
===========changed ref 3===========
# module: scripts.manageacl
class ManageAcl:
def __init__(
self,
service_name: str,
index_name: str,
+ url: str,
- document: str,
acl_action: str,
acl_type: str,
acl: str,
credentials: Union[AsyncTokenCredential, AzureKeyCredential],
):
"""
Initializes the command
Parameters
----------
service_name
Name of the Azure Search service
index_name
Name of the Azure Search index
+ url
- document
+ Full Blob storage URL of the document to manage acls for
- File path of the document to manage acls for
acl_action
Action to take regarding the index or document. Valid values include enable_acls (turn acls on for the entire index), view (print acls for the document), remove_all (remove all acls), remove (remove a specific acl), or add (add a specific acl)
acl_type
Type of acls to manage. Valid values include groups or oids.
acl
The actual value of the acl, if the acl action is add or remove
credentials
Credentials for the azure search service
"""
self.service_name = service_name
self.index_name = index_name
self.credentials = credentials
+ self.url = url
- self.document = document
self.acl_action = acl_action
self.acl_type = acl_type
self.acl = acl
===========changed ref 4===========
# module: scripts.manageacl
class ManageAcl:
def remove_acl(self, search_client: SearchClient):
documents_to_merge = []
+ for document in await self.get_documents(search_client):
- async for document in await self.get_documents(search_client):
+ new_acls = document[self.acl_type]
+ if any(acl_value == self.acl for acl_value in new_acls):
+ new_acls = [acl_value for acl_value in document[self.acl_type] if acl_value != self.acl]
- new_acls = [acl_value for acl_value in document[self.acl_type] if acl_value != self.acl]
+ documents_to_merge.append({"id": document["id"], self.acl_type: new_acls})
- documents_to_merge.append({"id": document["id"], self.acl_type: new_acls})
+ else:
+ logger.info("Search document %s does not have %s acl %s", document["id"], self.acl_type, self.acl)
if len(documents_to_merge) > 0:
+ logger.info("Removing acl %s from %d search documents", self.acl, len(documents_to_merge))
await search_client.merge_documents(documents=documents_to_merge)
+ else:
+ logger.info("Not updating any search documents")
===========changed ref 5===========
# module: tests.test_blob_manager
@pytest.mark.asyncio
@pytest.mark.skipif(sys.version_info.minor < 10, reason="requires Python 3.10 or higher")
async def test_create_container_upon_upload(monkeypatch, mock_env, blob_manager):
with NamedTemporaryFile(suffix=".pdf") as temp_file:
f = File(temp_file.file)
filename = os.path.basename(f.content.name)
# Set up mocks used by upload_blob
async def mock_exists(*args, **kwargs):
return False
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.exists", mock_exists)
async def mock_create_container(*args, **kwargs):
return
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.create_container", mock_create_container)
async def mock_upload_blob(self, name, *args, **kwargs):
assert name == filename
+ return azure.storage.blob.aio.BlobClient.from_blob_url(
+ "https://test.blob.core.windows.net/test/test.pdf", credential=MockAzureCredential()
+ )
- return True
monkeypatch.setattr("azure.storage.blob.aio.ContainerClient.upload_blob", mock_upload_blob)
await blob_manager.upload_blob(f)
+ assert f.url == "https://test.blob.core.windows.net/test/test.pdf"
|
scripts.manageacl/ManageAcl.get_documents
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
0124725ad85726aa3f62450e16fb136a63154f69
|
Adds storageURL field to track file location (#1535)
|
<0>:<add> filter = f"storageUrl eq '{self.url}'"
<del> filter = f"sourcefile eq '{self.document}'"
<1>:<add> documents = await search_client.search("", filter=filter, select=["id", self.acl_type])
<del> result = await search_client.search("", filter=filter, select=["id", self.acl_type])
<2>:<add> found_documents = []
<add> async for document in documents:
<add> found_documents.append(document)
<add> logger.info("Found %d search documents with storageUrl %s", len(found_documents), self.url)
<add> return found_documents
<del> return result
|
# module: scripts.manageacl
class ManageAcl:
def get_documents(self, search_client: SearchClient):
<0> filter = f"sourcefile eq '{self.document}'"
<1> result = await search_client.search("", filter=filter, select=["id", self.acl_type])
<2> return result
<3>
|
===========unchanged ref 0===========
at: logging.Logger
info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
at: scripts.manageacl
logger = logging.getLogger("manageacl")
at: scripts.manageacl.ManageAcl.__init__
self.acl_type = acl_type
at: scripts.manageacl.ManageAcl.remove_all_acls
documents_to_merge = []
===========changed ref 0===========
# module: scripts.manageacl
class ManageAcl:
def view_acl(self, search_client: SearchClient):
+ for document in await self.get_documents(search_client):
- async for document in await self.get_documents(search_client):
# Assumes the acls are consistent across all sections of the document
print(json.dumps(document[self.acl_type]))
return
===========changed ref 1===========
# module: scripts.manageacl
class ManageAcl:
def remove_all_acls(self, search_client: SearchClient):
documents_to_merge = []
+ for document in await self.get_documents(search_client):
- async for document in await self.get_documents(search_client):
+ if len(document[self.acl_type]) > 0:
+ documents_to_merge.append({"id": document["id"], self.acl_type: []})
- documents_to_merge.append({"id": document["id"], self.acl_type: []})
+ else:
+ logger.info("Search document %s already has no %s acls", document["id"], self.acl_type)
if len(documents_to_merge) > 0:
+ logger.info("Removing all %s acls from %d search documents", self.acl_type, len(documents_to_merge))
await search_client.merge_documents(documents=documents_to_merge)
+ else:
+ logger.info("Not updating any search documents")
===========changed ref 2===========
# module: scripts.manageacl
class ManageAcl:
def add_acl(self, search_client: SearchClient):
documents_to_merge = []
+ for document in await self.get_documents(search_client):
- async for document in await self.get_documents(search_client):
new_acls = document[self.acl_type]
if not any(acl_value == self.acl for acl_value in new_acls):
new_acls.append(self.acl)
+ documents_to_merge.append({"id": document["id"], self.acl_type: new_acls})
- documents_to_merge.append({"id": document["id"], self.acl_type: new_acls})
+ else:
+ logger.info("Search document %s already has %s acl %s", document["id"], self.acl_type, self.acl)
if len(documents_to_merge) > 0:
+ logger.info("Adding acl %s to %d search documents", self.acl, len(documents_to_merge))
await search_client.merge_documents(documents=documents_to_merge)
+ else:
+ logger.info("Not updating any search documents")
===========changed ref 3===========
# module: scripts.manageacl
class ManageAcl:
def run(self):
endpoint = f"https://{self.service_name}.search.windows.net"
if self.acl_action == "enable_acls":
await self.enable_acls(endpoint)
return
async with SearchClient(
endpoint=endpoint, index_name=self.index_name, credential=self.credentials
) as search_client:
if self.acl_action == "view":
await self.view_acl(search_client)
elif self.acl_action == "remove":
await self.remove_acl(search_client)
elif self.acl_action == "remove_all":
await self.remove_all_acls(search_client)
elif self.acl_action == "add":
await self.add_acl(search_client)
+ elif self.acl_action == "update_storage_urls":
+ await self.update_storage_urls(search_client)
else:
raise Exception(f"Unknown action {self.acl_action}")
- logging.info("ACLs updated")
-
===========changed ref 4===========
# module: scripts.manageacl
class ManageAcl:
def __init__(
self,
service_name: str,
index_name: str,
+ url: str,
- document: str,
acl_action: str,
acl_type: str,
acl: str,
credentials: Union[AsyncTokenCredential, AzureKeyCredential],
):
"""
Initializes the command
Parameters
----------
service_name
Name of the Azure Search service
index_name
Name of the Azure Search index
+ url
- document
+ Full Blob storage URL of the document to manage acls for
- File path of the document to manage acls for
acl_action
Action to take regarding the index or document. Valid values include enable_acls (turn acls on for the entire index), view (print acls for the document), remove_all (remove all acls), remove (remove a specific acl), or add (add a specific acl)
acl_type
Type of acls to manage. Valid values include groups or oids.
acl
The actual value of the acl, if the acl action is add or remove
credentials
Credentials for the azure search service
"""
self.service_name = service_name
self.index_name = index_name
self.credentials = credentials
+ self.url = url
- self.document = document
self.acl_action = acl_action
self.acl_type = acl_type
self.acl = acl
===========changed ref 5===========
# module: scripts.manageacl
class ManageAcl:
def remove_acl(self, search_client: SearchClient):
documents_to_merge = []
+ for document in await self.get_documents(search_client):
- async for document in await self.get_documents(search_client):
+ new_acls = document[self.acl_type]
+ if any(acl_value == self.acl for acl_value in new_acls):
+ new_acls = [acl_value for acl_value in document[self.acl_type] if acl_value != self.acl]
- new_acls = [acl_value for acl_value in document[self.acl_type] if acl_value != self.acl]
+ documents_to_merge.append({"id": document["id"], self.acl_type: new_acls})
- documents_to_merge.append({"id": document["id"], self.acl_type: new_acls})
+ else:
+ logger.info("Search document %s does not have %s acl %s", document["id"], self.acl_type, self.acl)
if len(documents_to_merge) > 0:
+ logger.info("Removing acl %s from %d search documents", self.acl, len(documents_to_merge))
await search_client.merge_documents(documents=documents_to_merge)
+ else:
+ logger.info("Not updating any search documents")
|
scripts.manageacl/ManageAcl.enable_acls
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
0124725ad85726aa3f62450e16fb136a63154f69
|
Adds storageURL field to track file location (#1535)
|
<1>:<add> logger.info(f"Enabling acls for index {self.index_name}")
<del> logging.info(f"Enabling acls for index {self.index_name}")
<19>:<add> if not any(field.name == "storageUrl" for field in index_definition.fields):
<add> index_definition.fields.append(
<add> SimpleField(
<add> name="storageUrl",
<add> type="Edm.String",
<add> filterable=True,
<add> facetable=False,
<add> ),
<add> )
<del>
|
# module: scripts.manageacl
class ManageAcl:
def enable_acls(self, endpoint: str):
<0> async with SearchIndexClient(endpoint=endpoint, credential=self.credentials) as search_index_client:
<1> logging.info(f"Enabling acls for index {self.index_name}")
<2> index_definition = await search_index_client.get_index(self.index_name)
<3> if not any(field.name == "oids" for field in index_definition.fields):
<4> index_definition.fields.append(
<5> SimpleField(
<6> name="oids",
<7> type=SearchFieldDataType.Collection(SearchFieldDataType.String),
<8> filterable=True,
<9> )
<10> )
<11> if not any(field.name == "groups" for field in index_definition.fields):
<12> index_definition.fields.append(
<13> SimpleField(
<14> name="groups",
<15> type=SearchFieldDataType.Collection(SearchFieldDataType.String),
<16> filterable=True,
<17> )
<18> )
<19>
<20> await search_index_client.create_or_update_index(index_definition)
<21>
|
===========unchanged ref 0===========
at: logging.Logger
info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
at: scripts.manageacl
logger = logging.getLogger("manageacl")
at: scripts.manageacl.ManageAcl.__init__
self.url = url
self.acl_type = acl_type
self.acl = acl
===========changed ref 0===========
# module: scripts.manageacl
class ManageAcl:
def view_acl(self, search_client: SearchClient):
+ for document in await self.get_documents(search_client):
- async for document in await self.get_documents(search_client):
# Assumes the acls are consistent across all sections of the document
print(json.dumps(document[self.acl_type]))
return
===========changed ref 1===========
# module: scripts.manageacl
class ManageAcl:
def get_documents(self, search_client: SearchClient):
+ filter = f"storageUrl eq '{self.url}'"
- filter = f"sourcefile eq '{self.document}'"
+ documents = await search_client.search("", filter=filter, select=["id", self.acl_type])
- result = await search_client.search("", filter=filter, select=["id", self.acl_type])
+ found_documents = []
+ async for document in documents:
+ found_documents.append(document)
+ logger.info("Found %d search documents with storageUrl %s", len(found_documents), self.url)
+ return found_documents
- return result
===========changed ref 2===========
# module: scripts.manageacl
class ManageAcl:
def remove_all_acls(self, search_client: SearchClient):
documents_to_merge = []
+ for document in await self.get_documents(search_client):
- async for document in await self.get_documents(search_client):
+ if len(document[self.acl_type]) > 0:
+ documents_to_merge.append({"id": document["id"], self.acl_type: []})
- documents_to_merge.append({"id": document["id"], self.acl_type: []})
+ else:
+ logger.info("Search document %s already has no %s acls", document["id"], self.acl_type)
if len(documents_to_merge) > 0:
+ logger.info("Removing all %s acls from %d search documents", self.acl_type, len(documents_to_merge))
await search_client.merge_documents(documents=documents_to_merge)
+ else:
+ logger.info("Not updating any search documents")
===========changed ref 3===========
# module: scripts.manageacl
class ManageAcl:
def add_acl(self, search_client: SearchClient):
documents_to_merge = []
+ for document in await self.get_documents(search_client):
- async for document in await self.get_documents(search_client):
new_acls = document[self.acl_type]
if not any(acl_value == self.acl for acl_value in new_acls):
new_acls.append(self.acl)
+ documents_to_merge.append({"id": document["id"], self.acl_type: new_acls})
- documents_to_merge.append({"id": document["id"], self.acl_type: new_acls})
+ else:
+ logger.info("Search document %s already has %s acl %s", document["id"], self.acl_type, self.acl)
if len(documents_to_merge) > 0:
+ logger.info("Adding acl %s to %d search documents", self.acl, len(documents_to_merge))
await search_client.merge_documents(documents=documents_to_merge)
+ else:
+ logger.info("Not updating any search documents")
===========changed ref 4===========
# module: scripts.manageacl
class ManageAcl:
def run(self):
endpoint = f"https://{self.service_name}.search.windows.net"
if self.acl_action == "enable_acls":
await self.enable_acls(endpoint)
return
async with SearchClient(
endpoint=endpoint, index_name=self.index_name, credential=self.credentials
) as search_client:
if self.acl_action == "view":
await self.view_acl(search_client)
elif self.acl_action == "remove":
await self.remove_acl(search_client)
elif self.acl_action == "remove_all":
await self.remove_all_acls(search_client)
elif self.acl_action == "add":
await self.add_acl(search_client)
+ elif self.acl_action == "update_storage_urls":
+ await self.update_storage_urls(search_client)
else:
raise Exception(f"Unknown action {self.acl_action}")
- logging.info("ACLs updated")
-
===========changed ref 5===========
# module: scripts.manageacl
class ManageAcl:
def __init__(
self,
service_name: str,
index_name: str,
+ url: str,
- document: str,
acl_action: str,
acl_type: str,
acl: str,
credentials: Union[AsyncTokenCredential, AzureKeyCredential],
):
"""
Initializes the command
Parameters
----------
service_name
Name of the Azure Search service
index_name
Name of the Azure Search index
+ url
- document
+ Full Blob storage URL of the document to manage acls for
- File path of the document to manage acls for
acl_action
Action to take regarding the index or document. Valid values include enable_acls (turn acls on for the entire index), view (print acls for the document), remove_all (remove all acls), remove (remove a specific acl), or add (add a specific acl)
acl_type
Type of acls to manage. Valid values include groups or oids.
acl
The actual value of the acl, if the acl action is add or remove
credentials
Credentials for the azure search service
"""
self.service_name = service_name
self.index_name = index_name
self.credentials = credentials
+ self.url = url
- self.document = document
self.acl_action = acl_action
self.acl_type = acl_type
self.acl = acl
===========changed ref 6===========
# module: scripts.manageacl
class ManageAcl:
def remove_acl(self, search_client: SearchClient):
documents_to_merge = []
+ for document in await self.get_documents(search_client):
- async for document in await self.get_documents(search_client):
+ new_acls = document[self.acl_type]
+ if any(acl_value == self.acl for acl_value in new_acls):
+ new_acls = [acl_value for acl_value in document[self.acl_type] if acl_value != self.acl]
- new_acls = [acl_value for acl_value in document[self.acl_type] if acl_value != self.acl]
+ documents_to_merge.append({"id": document["id"], self.acl_type: new_acls})
- documents_to_merge.append({"id": document["id"], self.acl_type: new_acls})
+ else:
+ logger.info("Search document %s does not have %s acl %s", document["id"], self.acl_type, self.acl)
if len(documents_to_merge) > 0:
+ logger.info("Removing acl %s from %d search documents", self.acl, len(documents_to_merge))
await search_client.merge_documents(documents=documents_to_merge)
+ else:
+ logger.info("Not updating any search documents")
|
scripts.manageacl/main
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
0124725ad85726aa3f62450e16fb136a63154f69
|
Adds storageURL field to track file location (#1535)
|
<13>:<add> url=args.url,
<del> document=args.document,
|
# module: scripts.manageacl
def main(args: Any):
<0> # Use the current user identity to connect to Azure services unless a key is explicitly set for any of them
<1> azd_credential = (
<2> AzureDeveloperCliCredential()
<3> if args.tenant_id is None
<4> else AzureDeveloperCliCredential(tenant_id=args.tenant_id, process_timeout=60)
<5> )
<6> search_credential: Union[AsyncTokenCredential, AzureKeyCredential] = azd_credential
<7> if args.search_key is not None:
<8> search_credential = AzureKeyCredential(args.search_key)
<9>
<10> command = ManageAcl(
<11> service_name=args.search_service,
<12> index_name=args.index,
<13> document=args.document,
<14> acl_action=args.acl_action,
<15> acl_type=args.acl_type,
<16> acl=args.acl,
<17> credentials=search_credential,
<18> )
<19> await command.run()
<20>
|
===========unchanged ref 0===========
at: logging.Logger
info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
at: scripts.manageacl
logger = logging.getLogger("manageacl")
at: scripts.manageacl.ManageAcl.__init__
self.index_name = index_name
self.credentials = credentials
===========changed ref 0===========
# module: scripts.manageacl
class ManageAcl:
def view_acl(self, search_client: SearchClient):
+ for document in await self.get_documents(search_client):
- async for document in await self.get_documents(search_client):
# Assumes the acls are consistent across all sections of the document
print(json.dumps(document[self.acl_type]))
return
===========changed ref 1===========
# module: scripts.manageacl
class ManageAcl:
def get_documents(self, search_client: SearchClient):
+ filter = f"storageUrl eq '{self.url}'"
- filter = f"sourcefile eq '{self.document}'"
+ documents = await search_client.search("", filter=filter, select=["id", self.acl_type])
- result = await search_client.search("", filter=filter, select=["id", self.acl_type])
+ found_documents = []
+ async for document in documents:
+ found_documents.append(document)
+ logger.info("Found %d search documents with storageUrl %s", len(found_documents), self.url)
+ return found_documents
- return result
===========changed ref 2===========
# module: scripts.manageacl
class ManageAcl:
def remove_all_acls(self, search_client: SearchClient):
documents_to_merge = []
+ for document in await self.get_documents(search_client):
- async for document in await self.get_documents(search_client):
+ if len(document[self.acl_type]) > 0:
+ documents_to_merge.append({"id": document["id"], self.acl_type: []})
- documents_to_merge.append({"id": document["id"], self.acl_type: []})
+ else:
+ logger.info("Search document %s already has no %s acls", document["id"], self.acl_type)
if len(documents_to_merge) > 0:
+ logger.info("Removing all %s acls from %d search documents", self.acl_type, len(documents_to_merge))
await search_client.merge_documents(documents=documents_to_merge)
+ else:
+ logger.info("Not updating any search documents")
===========changed ref 3===========
# module: scripts.manageacl
class ManageAcl:
def add_acl(self, search_client: SearchClient):
documents_to_merge = []
+ for document in await self.get_documents(search_client):
- async for document in await self.get_documents(search_client):
new_acls = document[self.acl_type]
if not any(acl_value == self.acl for acl_value in new_acls):
new_acls.append(self.acl)
+ documents_to_merge.append({"id": document["id"], self.acl_type: new_acls})
- documents_to_merge.append({"id": document["id"], self.acl_type: new_acls})
+ else:
+ logger.info("Search document %s already has %s acl %s", document["id"], self.acl_type, self.acl)
if len(documents_to_merge) > 0:
+ logger.info("Adding acl %s to %d search documents", self.acl, len(documents_to_merge))
await search_client.merge_documents(documents=documents_to_merge)
+ else:
+ logger.info("Not updating any search documents")
===========changed ref 4===========
# module: scripts.manageacl
class ManageAcl:
def run(self):
endpoint = f"https://{self.service_name}.search.windows.net"
if self.acl_action == "enable_acls":
await self.enable_acls(endpoint)
return
async with SearchClient(
endpoint=endpoint, index_name=self.index_name, credential=self.credentials
) as search_client:
if self.acl_action == "view":
await self.view_acl(search_client)
elif self.acl_action == "remove":
await self.remove_acl(search_client)
elif self.acl_action == "remove_all":
await self.remove_all_acls(search_client)
elif self.acl_action == "add":
await self.add_acl(search_client)
+ elif self.acl_action == "update_storage_urls":
+ await self.update_storage_urls(search_client)
else:
raise Exception(f"Unknown action {self.acl_action}")
- logging.info("ACLs updated")
-
===========changed ref 5===========
# module: scripts.manageacl
class ManageAcl:
def enable_acls(self, endpoint: str):
async with SearchIndexClient(endpoint=endpoint, credential=self.credentials) as search_index_client:
+ logger.info(f"Enabling acls for index {self.index_name}")
- logging.info(f"Enabling acls for index {self.index_name}")
index_definition = await search_index_client.get_index(self.index_name)
if not any(field.name == "oids" for field in index_definition.fields):
index_definition.fields.append(
SimpleField(
name="oids",
type=SearchFieldDataType.Collection(SearchFieldDataType.String),
filterable=True,
)
)
if not any(field.name == "groups" for field in index_definition.fields):
index_definition.fields.append(
SimpleField(
name="groups",
type=SearchFieldDataType.Collection(SearchFieldDataType.String),
filterable=True,
)
)
+ if not any(field.name == "storageUrl" for field in index_definition.fields):
+ index_definition.fields.append(
+ SimpleField(
+ name="storageUrl",
+ type="Edm.String",
+ filterable=True,
+ facetable=False,
+ ),
+ )
-
await search_index_client.create_or_update_index(index_definition)
===========changed ref 6===========
# module: scripts.manageacl
class ManageAcl:
def __init__(
self,
service_name: str,
index_name: str,
+ url: str,
- document: str,
acl_action: str,
acl_type: str,
acl: str,
credentials: Union[AsyncTokenCredential, AzureKeyCredential],
):
"""
Initializes the command
Parameters
----------
service_name
Name of the Azure Search service
index_name
Name of the Azure Search index
+ url
- document
+ Full Blob storage URL of the document to manage acls for
- File path of the document to manage acls for
acl_action
Action to take regarding the index or document. Valid values include enable_acls (turn acls on for the entire index), view (print acls for the document), remove_all (remove all acls), remove (remove a specific acl), or add (add a specific acl)
acl_type
Type of acls to manage. Valid values include groups or oids.
acl
The actual value of the acl, if the acl action is add or remove
credentials
Credentials for the azure search service
"""
self.service_name = service_name
self.index_name = index_name
self.credentials = credentials
+ self.url = url
- self.document = document
self.acl_action = acl_action
self.acl_type = acl_type
self.acl = acl
|
app.backend.prepdocslib.listfilestrategy/File.__init__
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
0124725ad85726aa3f62450e16fb136a63154f69
|
Adds storageURL field to track file location (#1535)
|
<2>:<add> self.url = url
|
# module: app.backend.prepdocslib.listfilestrategy
class File:
+ def __init__(self, content: IO, acls: Optional[dict[str, list]] = None, url: Optional[str] = None):
- def __init__(self, content: IO, acls: Optional[dict[str, list]] = None):
<0> self.content = content
<1> self.acls = acls or {}
<2>
|
===========unchanged ref 0===========
at: typing
IO()
===========changed ref 0===========
# module: scripts.manageacl
class ManageAcl:
def view_acl(self, search_client: SearchClient):
+ for document in await self.get_documents(search_client):
- async for document in await self.get_documents(search_client):
# Assumes the acls are consistent across all sections of the document
print(json.dumps(document[self.acl_type]))
return
===========changed ref 1===========
# module: scripts.manageacl
class ManageAcl:
def get_documents(self, search_client: SearchClient):
+ filter = f"storageUrl eq '{self.url}'"
- filter = f"sourcefile eq '{self.document}'"
+ documents = await search_client.search("", filter=filter, select=["id", self.acl_type])
- result = await search_client.search("", filter=filter, select=["id", self.acl_type])
+ found_documents = []
+ async for document in documents:
+ found_documents.append(document)
+ logger.info("Found %d search documents with storageUrl %s", len(found_documents), self.url)
+ return found_documents
- return result
===========changed ref 2===========
# module: scripts.manageacl
def main(args: Any):
# Use the current user identity to connect to Azure services unless a key is explicitly set for any of them
azd_credential = (
AzureDeveloperCliCredential()
if args.tenant_id is None
else AzureDeveloperCliCredential(tenant_id=args.tenant_id, process_timeout=60)
)
search_credential: Union[AsyncTokenCredential, AzureKeyCredential] = azd_credential
if args.search_key is not None:
search_credential = AzureKeyCredential(args.search_key)
command = ManageAcl(
service_name=args.search_service,
index_name=args.index,
+ url=args.url,
- document=args.document,
acl_action=args.acl_action,
acl_type=args.acl_type,
acl=args.acl,
credentials=search_credential,
)
await command.run()
===========changed ref 3===========
# module: scripts.manageacl
class ManageAcl:
def remove_all_acls(self, search_client: SearchClient):
documents_to_merge = []
+ for document in await self.get_documents(search_client):
- async for document in await self.get_documents(search_client):
+ if len(document[self.acl_type]) > 0:
+ documents_to_merge.append({"id": document["id"], self.acl_type: []})
- documents_to_merge.append({"id": document["id"], self.acl_type: []})
+ else:
+ logger.info("Search document %s already has no %s acls", document["id"], self.acl_type)
if len(documents_to_merge) > 0:
+ logger.info("Removing all %s acls from %d search documents", self.acl_type, len(documents_to_merge))
await search_client.merge_documents(documents=documents_to_merge)
+ else:
+ logger.info("Not updating any search documents")
===========changed ref 4===========
# module: scripts.manageacl
class ManageAcl:
def run(self):
endpoint = f"https://{self.service_name}.search.windows.net"
if self.acl_action == "enable_acls":
await self.enable_acls(endpoint)
return
async with SearchClient(
endpoint=endpoint, index_name=self.index_name, credential=self.credentials
) as search_client:
if self.acl_action == "view":
await self.view_acl(search_client)
elif self.acl_action == "remove":
await self.remove_acl(search_client)
elif self.acl_action == "remove_all":
await self.remove_all_acls(search_client)
elif self.acl_action == "add":
await self.add_acl(search_client)
+ elif self.acl_action == "update_storage_urls":
+ await self.update_storage_urls(search_client)
else:
raise Exception(f"Unknown action {self.acl_action}")
- logging.info("ACLs updated")
-
===========changed ref 5===========
# module: scripts.manageacl
class ManageAcl:
def __init__(
self,
service_name: str,
index_name: str,
+ url: str,
- document: str,
acl_action: str,
acl_type: str,
acl: str,
credentials: Union[AsyncTokenCredential, AzureKeyCredential],
):
"""
Initializes the command
Parameters
----------
service_name
Name of the Azure Search service
index_name
Name of the Azure Search index
+ url
- document
+ Full Blob storage URL of the document to manage acls for
- File path of the document to manage acls for
acl_action
Action to take regarding the index or document. Valid values include enable_acls (turn acls on for the entire index), view (print acls for the document), remove_all (remove all acls), remove (remove a specific acl), or add (add a specific acl)
acl_type
Type of acls to manage. Valid values include groups or oids.
acl
The actual value of the acl, if the acl action is add or remove
credentials
Credentials for the azure search service
"""
self.service_name = service_name
self.index_name = index_name
self.credentials = credentials
+ self.url = url
- self.document = document
self.acl_action = acl_action
self.acl_type = acl_type
self.acl = acl
===========changed ref 6===========
# module: scripts.manageacl
class ManageAcl:
def add_acl(self, search_client: SearchClient):
documents_to_merge = []
+ for document in await self.get_documents(search_client):
- async for document in await self.get_documents(search_client):
new_acls = document[self.acl_type]
if not any(acl_value == self.acl for acl_value in new_acls):
new_acls.append(self.acl)
+ documents_to_merge.append({"id": document["id"], self.acl_type: new_acls})
- documents_to_merge.append({"id": document["id"], self.acl_type: new_acls})
+ else:
+ logger.info("Search document %s already has %s acl %s", document["id"], self.acl_type, self.acl)
if len(documents_to_merge) > 0:
+ logger.info("Adding acl %s to %d search documents", self.acl, len(documents_to_merge))
await search_client.merge_documents(documents=documents_to_merge)
+ else:
+ logger.info("Not updating any search documents")
|
app.backend.prepdocslib.listfilestrategy/ADLSGen2ListFileStrategy.list
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
0124725ad85726aa3f62450e16fb136a63154f69
|
Adds storageURL field to track file location (#1535)
|
# module: app.backend.prepdocslib.listfilestrategy
class ADLSGen2ListFileStrategy(ListFileStrategy):
def list(self) -> AsyncGenerator[File, None]:
<0> async with DataLakeServiceClient(
<1> account_url=f"https://{self.data_lake_storage_account}.dfs.core.windows.net", credential=self.credential
<2> ) as service_client, service_client.get_file_system_client(self.data_lake_filesystem) as filesystem_client:
<3> async for path in self.list_paths():
<4> temp_file_path = os.path.join(tempfile.gettempdir(), os.path.basename(path))
<5> try:
<6> async with filesystem_client.get_file_client(path) as file_client:
<7> with open(temp_file_path, "wb") as temp_file:
<8> downloader = await file_client.download_file()
<9> await downloader.readinto(temp_file)
<10> # Parse out user ids and group ids
<11> acls: Dict[str, List[str]] = {"oids": [], "groups": []}
<12> # https://learn.microsoft.com/python/api/azure-storage-file-datalake/azure.storage.filedatalake.datalakefileclient?view=azure-python#azure-storage-filedatalake-datalakefileclient-get-access-control
<13> # Request ACLs as GUIDs
<14> access_control = await file_client.get_access_control(upn=False)
<15> acl_list = access_control["acl"]
<16> # https://learn.microsoft.com/azure/storage/blobs/data-lake-storage-access-control
<17> # ACL Format: user::rwx,group::r-x,other::r--,user:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:r--
<18> acl_list = acl_list.split(",")
<19> for acl in acl_list:
<20> acl_parts: list = acl.split(":")
<21> if len(acl_parts) != 3:</s>
|
===========below chunk 0===========
# module: app.backend.prepdocslib.listfilestrategy
class ADLSGen2ListFileStrategy(ListFileStrategy):
def list(self) -> AsyncGenerator[File, None]:
# offset: 1
if len(acl_parts[1]) == 0:
continue
if acl_parts[0] == "user" and "r" in acl_parts[2]:
acls["oids"].append(acl_parts[1])
if acl_parts[0] == "group" and "r" in acl_parts[2]:
acls["groups"].append(acl_parts[1])
yield File(content=open(temp_file_path, "rb"), acls=acls)
except Exception as data_lake_exception:
logger.error(f"\tGot an error while reading {path} -> {data_lake_exception} --> skipping file")
try:
os.remove(temp_file_path)
except Exception as file_delete_exception:
logger.error(f"\tGot an error while deleting {temp_file_path} -> {file_delete_exception}")
===========unchanged ref 0===========
at: app.backend.prepdocslib.listfilestrategy
logger = logging.getLogger("ingester")
File(content: IO, acls: Optional[dict[str, list]]=None, url: Optional[str]=None)
at: app.backend.prepdocslib.listfilestrategy.ADLSGen2ListFileStrategy
list_paths() -> AsyncGenerator[str, None]
at: app.backend.prepdocslib.listfilestrategy.ADLSGen2ListFileStrategy.__init__
self.data_lake_storage_account = data_lake_storage_account
self.data_lake_filesystem = data_lake_filesystem
self.credential = credential
at: app.backend.prepdocslib.listfilestrategy.ListFileStrategy
list(self) -> AsyncGenerator[File, None]
at: logging.Logger
error(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
at: os
remove(path: AnyPath, *, dir_fd: Optional[int]=...) -> None
at: os.path
join(a: StrPath, *paths: StrPath) -> str
join(a: BytesPath, *paths: BytesPath) -> bytes
basename(p: _PathLike[AnyStr]) -> AnyStr
basename(p: AnyStr) -> AnyStr
at: tempfile
gettempdir() -> str
at: typing
List = _alias(list, 1, inst=False, name='List')
Dict = _alias(dict, 2, inst=False, name='Dict')
AsyncGenerator = _alias(collections.abc.AsyncGenerator, 2)
===========changed ref 0===========
# module: app.backend.prepdocslib.listfilestrategy
class File:
+ def __init__(self, content: IO, acls: Optional[dict[str, list]] = None, url: Optional[str] = None):
- def __init__(self, content: IO, acls: Optional[dict[str, list]] = None):
self.content = content
self.acls = acls or {}
+ self.url = url
===========changed ref 1===========
# module: scripts.manageacl
class ManageAcl:
def view_acl(self, search_client: SearchClient):
+ for document in await self.get_documents(search_client):
- async for document in await self.get_documents(search_client):
# Assumes the acls are consistent across all sections of the document
print(json.dumps(document[self.acl_type]))
return
===========changed ref 2===========
# module: scripts.manageacl
class ManageAcl:
def get_documents(self, search_client: SearchClient):
+ filter = f"storageUrl eq '{self.url}'"
- filter = f"sourcefile eq '{self.document}'"
+ documents = await search_client.search("", filter=filter, select=["id", self.acl_type])
- result = await search_client.search("", filter=filter, select=["id", self.acl_type])
+ found_documents = []
+ async for document in documents:
+ found_documents.append(document)
+ logger.info("Found %d search documents with storageUrl %s", len(found_documents), self.url)
+ return found_documents
- return result
===========changed ref 3===========
# module: scripts.manageacl
def main(args: Any):
# Use the current user identity to connect to Azure services unless a key is explicitly set for any of them
azd_credential = (
AzureDeveloperCliCredential()
if args.tenant_id is None
else AzureDeveloperCliCredential(tenant_id=args.tenant_id, process_timeout=60)
)
search_credential: Union[AsyncTokenCredential, AzureKeyCredential] = azd_credential
if args.search_key is not None:
search_credential = AzureKeyCredential(args.search_key)
command = ManageAcl(
service_name=args.search_service,
index_name=args.index,
+ url=args.url,
- document=args.document,
acl_action=args.acl_action,
acl_type=args.acl_type,
acl=args.acl,
credentials=search_credential,
)
await command.run()
===========changed ref 4===========
# module: scripts.manageacl
class ManageAcl:
def remove_all_acls(self, search_client: SearchClient):
documents_to_merge = []
+ for document in await self.get_documents(search_client):
- async for document in await self.get_documents(search_client):
+ if len(document[self.acl_type]) > 0:
+ documents_to_merge.append({"id": document["id"], self.acl_type: []})
- documents_to_merge.append({"id": document["id"], self.acl_type: []})
+ else:
+ logger.info("Search document %s already has no %s acls", document["id"], self.acl_type)
if len(documents_to_merge) > 0:
+ logger.info("Removing all %s acls from %d search documents", self.acl_type, len(documents_to_merge))
await search_client.merge_documents(documents=documents_to_merge)
+ else:
+ logger.info("Not updating any search documents")
===========changed ref 5===========
# module: scripts.manageacl
class ManageAcl:
def run(self):
endpoint = f"https://{self.service_name}.search.windows.net"
if self.acl_action == "enable_acls":
await self.enable_acls(endpoint)
return
async with SearchClient(
endpoint=endpoint, index_name=self.index_name, credential=self.credentials
) as search_client:
if self.acl_action == "view":
await self.view_acl(search_client)
elif self.acl_action == "remove":
await self.remove_acl(search_client)
elif self.acl_action == "remove_all":
await self.remove_all_acls(search_client)
elif self.acl_action == "add":
await self.add_acl(search_client)
+ elif self.acl_action == "update_storage_urls":
+ await self.update_storage_urls(search_client)
else:
raise Exception(f"Unknown action {self.acl_action}")
- logging.info("ACLs updated")
-
|
|
tests.test_searchmanager/test_create_index_doesnt_exist_yet
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
0124725ad85726aa3f62450e16fb136a63154f69
|
Adds storageURL field to track file location (#1535)
|
<16>:<add> assert len(indexes[0].fields) == 7
<del> assert len(indexes[0].fields) == 6
|
# module: tests.test_searchmanager
@pytest.mark.asyncio
async def test_create_index_doesnt_exist_yet(monkeypatch, search_info):
<0> indexes = []
<1>
<2> async def mock_create_index(self, index):
<3> indexes.append(index)
<4>
<5> async def mock_list_index_names(self):
<6> for index in []:
<7> yield index
<8>
<9> monkeypatch.setattr(SearchIndexClient, "create_index", mock_create_index)
<10> monkeypatch.setattr(SearchIndexClient, "list_index_names", mock_list_index_names)
<11>
<12> manager = SearchManager(search_info)
<13> await manager.create_index()
<14> assert len(indexes) == 1, "It should have created one index"
<15> assert indexes[0].name == "test"
<16> assert len(indexes[0].fields) == 6
<17>
|
===========unchanged ref 0===========
at: _pytest.mark.structures
MARK_GEN = MarkGenerator(_ispytest=True)
at: _pytest.monkeypatch
monkeypatch() -> Generator["MonkeyPatch", None, None]
===========changed ref 0===========
# module: tests.test_searchmanager
- @pytest.fixture
- def embeddings_service(monkeypatch):
- async def mock_create_client(*args, **kwargs):
- # From https://platform.openai.com/docs/api-reference/embeddings/create
- return MockClient(
- embeddings_client=MockEmbeddingsClient(
- create_embedding_response=openai.types.CreateEmbeddingResponse(
- object="list",
- data=[
- openai.types.Embedding(
- embedding=[
- 0.0023064255,
- -0.009327292,
- -0.0028842222,
- ],
- index=0,
- object="embedding",
- )
- ],
- model="text-embedding-ada-002",
- usage=Usage(prompt_tokens=8, total_tokens=8),
- )
- )
- )
-
- embeddings = AzureOpenAIEmbeddingService(
- open_ai_service="x",
- open_ai_deployment="x",
- open_ai_model_name=MOCK_EMBEDDING_MODEL_NAME,
- open_ai_dimensions=MOCK_EMBEDDING_DIMENSIONS,
- credential=AzureKeyCredential("test"),
- disable_batch=True,
- )
- monkeypatch.setattr(embeddings, "create_client", mock_create_client)
- return embeddings
-
===========changed ref 1===========
# module: app.backend.prepdocslib.listfilestrategy
class File:
+ def __init__(self, content: IO, acls: Optional[dict[str, list]] = None, url: Optional[str] = None):
- def __init__(self, content: IO, acls: Optional[dict[str, list]] = None):
self.content = content
self.acls = acls or {}
+ self.url = url
===========changed ref 2===========
# module: scripts.manageacl
class ManageAcl:
def view_acl(self, search_client: SearchClient):
+ for document in await self.get_documents(search_client):
- async for document in await self.get_documents(search_client):
# Assumes the acls are consistent across all sections of the document
print(json.dumps(document[self.acl_type]))
return
===========changed ref 3===========
# module: scripts.manageacl
class ManageAcl:
def get_documents(self, search_client: SearchClient):
+ filter = f"storageUrl eq '{self.url}'"
- filter = f"sourcefile eq '{self.document}'"
+ documents = await search_client.search("", filter=filter, select=["id", self.acl_type])
- result = await search_client.search("", filter=filter, select=["id", self.acl_type])
+ found_documents = []
+ async for document in documents:
+ found_documents.append(document)
+ logger.info("Found %d search documents with storageUrl %s", len(found_documents), self.url)
+ return found_documents
- return result
===========changed ref 4===========
# module: scripts.manageacl
def main(args: Any):
# Use the current user identity to connect to Azure services unless a key is explicitly set for any of them
azd_credential = (
AzureDeveloperCliCredential()
if args.tenant_id is None
else AzureDeveloperCliCredential(tenant_id=args.tenant_id, process_timeout=60)
)
search_credential: Union[AsyncTokenCredential, AzureKeyCredential] = azd_credential
if args.search_key is not None:
search_credential = AzureKeyCredential(args.search_key)
command = ManageAcl(
service_name=args.search_service,
index_name=args.index,
+ url=args.url,
- document=args.document,
acl_action=args.acl_action,
acl_type=args.acl_type,
acl=args.acl,
credentials=search_credential,
)
await command.run()
===========changed ref 5===========
# module: scripts.manageacl
class ManageAcl:
def remove_all_acls(self, search_client: SearchClient):
documents_to_merge = []
+ for document in await self.get_documents(search_client):
- async for document in await self.get_documents(search_client):
+ if len(document[self.acl_type]) > 0:
+ documents_to_merge.append({"id": document["id"], self.acl_type: []})
- documents_to_merge.append({"id": document["id"], self.acl_type: []})
+ else:
+ logger.info("Search document %s already has no %s acls", document["id"], self.acl_type)
if len(documents_to_merge) > 0:
+ logger.info("Removing all %s acls from %d search documents", self.acl_type, len(documents_to_merge))
await search_client.merge_documents(documents=documents_to_merge)
+ else:
+ logger.info("Not updating any search documents")
===========changed ref 6===========
# module: scripts.manageacl
class ManageAcl:
def run(self):
endpoint = f"https://{self.service_name}.search.windows.net"
if self.acl_action == "enable_acls":
await self.enable_acls(endpoint)
return
async with SearchClient(
endpoint=endpoint, index_name=self.index_name, credential=self.credentials
) as search_client:
if self.acl_action == "view":
await self.view_acl(search_client)
elif self.acl_action == "remove":
await self.remove_acl(search_client)
elif self.acl_action == "remove_all":
await self.remove_all_acls(search_client)
elif self.acl_action == "add":
await self.add_acl(search_client)
+ elif self.acl_action == "update_storage_urls":
+ await self.update_storage_urls(search_client)
else:
raise Exception(f"Unknown action {self.acl_action}")
- logging.info("ACLs updated")
-
===========changed ref 7===========
# module: scripts.manageacl
class ManageAcl:
def __init__(
self,
service_name: str,
index_name: str,
+ url: str,
- document: str,
acl_action: str,
acl_type: str,
acl: str,
credentials: Union[AsyncTokenCredential, AzureKeyCredential],
):
"""
Initializes the command
Parameters
----------
service_name
Name of the Azure Search service
index_name
Name of the Azure Search index
+ url
- document
+ Full Blob storage URL of the document to manage acls for
- File path of the document to manage acls for
acl_action
Action to take regarding the index or document. Valid values include enable_acls (turn acls on for the entire index), view (print acls for the document), remove_all (remove all acls), remove (remove a specific acl), or add (add a specific acl)
acl_type
Type of acls to manage. Valid values include groups or oids.
acl
The actual value of the acl, if the acl action is add or remove
credentials
Credentials for the azure search service
"""
self.service_name = service_name
self.index_name = index_name
self.credentials = credentials
+ self.url = url
- self.document = document
self.acl_action = acl_action
self.acl_type = acl_type
self.acl = acl
|
tests.test_searchmanager/test_create_index_using_int_vectorization
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
0124725ad85726aa3f62450e16fb136a63154f69
|
Adds storageURL field to track file location (#1535)
|
<16>:<add> assert len(indexes[0].fields) == 8
<del> assert len(indexes[0].fields) == 7
|
# module: tests.test_searchmanager
@pytest.mark.asyncio
async def test_create_index_using_int_vectorization(monkeypatch, search_info):
<0> indexes = []
<1>
<2> async def mock_create_index(self, index):
<3> indexes.append(index)
<4>
<5> async def mock_list_index_names(self):
<6> for index in []:
<7> yield index
<8>
<9> monkeypatch.setattr(SearchIndexClient, "create_index", mock_create_index)
<10> monkeypatch.setattr(SearchIndexClient, "list_index_names", mock_list_index_names)
<11>
<12> manager = SearchManager(search_info, use_int_vectorization=True)
<13> await manager.create_index()
<14> assert len(indexes) == 1, "It should have created one index"
<15> assert indexes[0].name == "test"
<16> assert len(indexes[0].fields) == 7
<17>
|
===========unchanged ref 0===========
at: _pytest.mark.structures
MARK_GEN = MarkGenerator(_ispytest=True)
===========changed ref 0===========
# module: tests.test_searchmanager
@pytest.mark.asyncio
async def test_create_index_doesnt_exist_yet(monkeypatch, search_info):
indexes = []
async def mock_create_index(self, index):
indexes.append(index)
async def mock_list_index_names(self):
for index in []:
yield index
monkeypatch.setattr(SearchIndexClient, "create_index", mock_create_index)
monkeypatch.setattr(SearchIndexClient, "list_index_names", mock_list_index_names)
manager = SearchManager(search_info)
await manager.create_index()
assert len(indexes) == 1, "It should have created one index"
assert indexes[0].name == "test"
+ assert len(indexes[0].fields) == 7
- assert len(indexes[0].fields) == 6
===========changed ref 1===========
# module: tests.test_searchmanager
- @pytest.fixture
- def embeddings_service(monkeypatch):
- async def mock_create_client(*args, **kwargs):
- # From https://platform.openai.com/docs/api-reference/embeddings/create
- return MockClient(
- embeddings_client=MockEmbeddingsClient(
- create_embedding_response=openai.types.CreateEmbeddingResponse(
- object="list",
- data=[
- openai.types.Embedding(
- embedding=[
- 0.0023064255,
- -0.009327292,
- -0.0028842222,
- ],
- index=0,
- object="embedding",
- )
- ],
- model="text-embedding-ada-002",
- usage=Usage(prompt_tokens=8, total_tokens=8),
- )
- )
- )
-
- embeddings = AzureOpenAIEmbeddingService(
- open_ai_service="x",
- open_ai_deployment="x",
- open_ai_model_name=MOCK_EMBEDDING_MODEL_NAME,
- open_ai_dimensions=MOCK_EMBEDDING_DIMENSIONS,
- credential=AzureKeyCredential("test"),
- disable_batch=True,
- )
- monkeypatch.setattr(embeddings, "create_client", mock_create_client)
- return embeddings
-
===========changed ref 2===========
# module: app.backend.prepdocslib.listfilestrategy
class File:
+ def __init__(self, content: IO, acls: Optional[dict[str, list]] = None, url: Optional[str] = None):
- def __init__(self, content: IO, acls: Optional[dict[str, list]] = None):
self.content = content
self.acls = acls or {}
+ self.url = url
===========changed ref 3===========
# module: scripts.manageacl
class ManageAcl:
def view_acl(self, search_client: SearchClient):
+ for document in await self.get_documents(search_client):
- async for document in await self.get_documents(search_client):
# Assumes the acls are consistent across all sections of the document
print(json.dumps(document[self.acl_type]))
return
===========changed ref 4===========
# module: scripts.manageacl
class ManageAcl:
def get_documents(self, search_client: SearchClient):
+ filter = f"storageUrl eq '{self.url}'"
- filter = f"sourcefile eq '{self.document}'"
+ documents = await search_client.search("", filter=filter, select=["id", self.acl_type])
- result = await search_client.search("", filter=filter, select=["id", self.acl_type])
+ found_documents = []
+ async for document in documents:
+ found_documents.append(document)
+ logger.info("Found %d search documents with storageUrl %s", len(found_documents), self.url)
+ return found_documents
- return result
===========changed ref 5===========
# module: scripts.manageacl
def main(args: Any):
# Use the current user identity to connect to Azure services unless a key is explicitly set for any of them
azd_credential = (
AzureDeveloperCliCredential()
if args.tenant_id is None
else AzureDeveloperCliCredential(tenant_id=args.tenant_id, process_timeout=60)
)
search_credential: Union[AsyncTokenCredential, AzureKeyCredential] = azd_credential
if args.search_key is not None:
search_credential = AzureKeyCredential(args.search_key)
command = ManageAcl(
service_name=args.search_service,
index_name=args.index,
+ url=args.url,
- document=args.document,
acl_action=args.acl_action,
acl_type=args.acl_type,
acl=args.acl,
credentials=search_credential,
)
await command.run()
===========changed ref 6===========
# module: scripts.manageacl
class ManageAcl:
def remove_all_acls(self, search_client: SearchClient):
documents_to_merge = []
+ for document in await self.get_documents(search_client):
- async for document in await self.get_documents(search_client):
+ if len(document[self.acl_type]) > 0:
+ documents_to_merge.append({"id": document["id"], self.acl_type: []})
- documents_to_merge.append({"id": document["id"], self.acl_type: []})
+ else:
+ logger.info("Search document %s already has no %s acls", document["id"], self.acl_type)
if len(documents_to_merge) > 0:
+ logger.info("Removing all %s acls from %d search documents", self.acl_type, len(documents_to_merge))
await search_client.merge_documents(documents=documents_to_merge)
+ else:
+ logger.info("Not updating any search documents")
===========changed ref 7===========
# module: scripts.manageacl
class ManageAcl:
def run(self):
endpoint = f"https://{self.service_name}.search.windows.net"
if self.acl_action == "enable_acls":
await self.enable_acls(endpoint)
return
async with SearchClient(
endpoint=endpoint, index_name=self.index_name, credential=self.credentials
) as search_client:
if self.acl_action == "view":
await self.view_acl(search_client)
elif self.acl_action == "remove":
await self.remove_acl(search_client)
elif self.acl_action == "remove_all":
await self.remove_all_acls(search_client)
elif self.acl_action == "add":
await self.add_acl(search_client)
+ elif self.acl_action == "update_storage_urls":
+ await self.update_storage_urls(search_client)
else:
raise Exception(f"Unknown action {self.acl_action}")
- logging.info("ACLs updated")
-
|
tests.test_searchmanager/test_create_index_acls
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
0124725ad85726aa3f62450e16fb136a63154f69
|
Adds storageURL field to track file location (#1535)
|
<19>:<add> assert len(indexes[0].fields) == 9
<del> assert len(indexes[0].fields) == 8
|
# module: tests.test_searchmanager
@pytest.mark.asyncio
async def test_create_index_acls(monkeypatch, search_info):
<0> indexes = []
<1>
<2> async def mock_create_index(self, index):
<3> indexes.append(index)
<4>
<5> async def mock_list_index_names(self):
<6> for index in []:
<7> yield index
<8>
<9> monkeypatch.setattr(SearchIndexClient, "create_index", mock_create_index)
<10> monkeypatch.setattr(SearchIndexClient, "list_index_names", mock_list_index_names)
<11>
<12> manager = SearchManager(
<13> search_info,
<14> use_acls=True,
<15> )
<16> await manager.create_index()
<17> assert len(indexes) == 1, "It should have created one index"
<18> assert indexes[0].name == "test"
<19> assert len(indexes[0].fields) == 8
<20>
|
===========unchanged ref 0===========
at: _pytest.mark.structures
MARK_GEN = MarkGenerator(_ispytest=True)
===========changed ref 0===========
# module: tests.test_searchmanager
@pytest.mark.asyncio
async def test_create_index_using_int_vectorization(monkeypatch, search_info):
indexes = []
async def mock_create_index(self, index):
indexes.append(index)
async def mock_list_index_names(self):
for index in []:
yield index
monkeypatch.setattr(SearchIndexClient, "create_index", mock_create_index)
monkeypatch.setattr(SearchIndexClient, "list_index_names", mock_list_index_names)
manager = SearchManager(search_info, use_int_vectorization=True)
await manager.create_index()
assert len(indexes) == 1, "It should have created one index"
assert indexes[0].name == "test"
+ assert len(indexes[0].fields) == 8
- assert len(indexes[0].fields) == 7
===========changed ref 1===========
# module: tests.test_searchmanager
@pytest.mark.asyncio
async def test_create_index_doesnt_exist_yet(monkeypatch, search_info):
indexes = []
async def mock_create_index(self, index):
indexes.append(index)
async def mock_list_index_names(self):
for index in []:
yield index
monkeypatch.setattr(SearchIndexClient, "create_index", mock_create_index)
monkeypatch.setattr(SearchIndexClient, "list_index_names", mock_list_index_names)
manager = SearchManager(search_info)
await manager.create_index()
assert len(indexes) == 1, "It should have created one index"
assert indexes[0].name == "test"
+ assert len(indexes[0].fields) == 7
- assert len(indexes[0].fields) == 6
===========changed ref 2===========
# module: tests.test_searchmanager
- @pytest.fixture
- def embeddings_service(monkeypatch):
- async def mock_create_client(*args, **kwargs):
- # From https://platform.openai.com/docs/api-reference/embeddings/create
- return MockClient(
- embeddings_client=MockEmbeddingsClient(
- create_embedding_response=openai.types.CreateEmbeddingResponse(
- object="list",
- data=[
- openai.types.Embedding(
- embedding=[
- 0.0023064255,
- -0.009327292,
- -0.0028842222,
- ],
- index=0,
- object="embedding",
- )
- ],
- model="text-embedding-ada-002",
- usage=Usage(prompt_tokens=8, total_tokens=8),
- )
- )
- )
-
- embeddings = AzureOpenAIEmbeddingService(
- open_ai_service="x",
- open_ai_deployment="x",
- open_ai_model_name=MOCK_EMBEDDING_MODEL_NAME,
- open_ai_dimensions=MOCK_EMBEDDING_DIMENSIONS,
- credential=AzureKeyCredential("test"),
- disable_batch=True,
- )
- monkeypatch.setattr(embeddings, "create_client", mock_create_client)
- return embeddings
-
===========changed ref 3===========
# module: app.backend.prepdocslib.listfilestrategy
class File:
+ def __init__(self, content: IO, acls: Optional[dict[str, list]] = None, url: Optional[str] = None):
- def __init__(self, content: IO, acls: Optional[dict[str, list]] = None):
self.content = content
self.acls = acls or {}
+ self.url = url
===========changed ref 4===========
# module: scripts.manageacl
class ManageAcl:
def view_acl(self, search_client: SearchClient):
+ for document in await self.get_documents(search_client):
- async for document in await self.get_documents(search_client):
# Assumes the acls are consistent across all sections of the document
print(json.dumps(document[self.acl_type]))
return
===========changed ref 5===========
# module: scripts.manageacl
class ManageAcl:
def get_documents(self, search_client: SearchClient):
+ filter = f"storageUrl eq '{self.url}'"
- filter = f"sourcefile eq '{self.document}'"
+ documents = await search_client.search("", filter=filter, select=["id", self.acl_type])
- result = await search_client.search("", filter=filter, select=["id", self.acl_type])
+ found_documents = []
+ async for document in documents:
+ found_documents.append(document)
+ logger.info("Found %d search documents with storageUrl %s", len(found_documents), self.url)
+ return found_documents
- return result
===========changed ref 6===========
# module: scripts.manageacl
def main(args: Any):
# Use the current user identity to connect to Azure services unless a key is explicitly set for any of them
azd_credential = (
AzureDeveloperCliCredential()
if args.tenant_id is None
else AzureDeveloperCliCredential(tenant_id=args.tenant_id, process_timeout=60)
)
search_credential: Union[AsyncTokenCredential, AzureKeyCredential] = azd_credential
if args.search_key is not None:
search_credential = AzureKeyCredential(args.search_key)
command = ManageAcl(
service_name=args.search_service,
index_name=args.index,
+ url=args.url,
- document=args.document,
acl_action=args.acl_action,
acl_type=args.acl_type,
acl=args.acl,
credentials=search_credential,
)
await command.run()
===========changed ref 7===========
# module: scripts.manageacl
class ManageAcl:
def remove_all_acls(self, search_client: SearchClient):
documents_to_merge = []
+ for document in await self.get_documents(search_client):
- async for document in await self.get_documents(search_client):
+ if len(document[self.acl_type]) > 0:
+ documents_to_merge.append({"id": document["id"], self.acl_type: []})
- documents_to_merge.append({"id": document["id"], self.acl_type: []})
+ else:
+ logger.info("Search document %s already has no %s acls", document["id"], self.acl_type)
if len(documents_to_merge) > 0:
+ logger.info("Removing all %s acls from %d search documents", self.acl_type, len(documents_to_merge))
await search_client.merge_documents(documents=documents_to_merge)
+ else:
+ logger.info("Not updating any search documents")
|
tests.test_manageacl/test_view_acl
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
0124725ad85726aa3f62450e16fb136a63154f69
|
Adds storageURL field to track file location (#1535)
|
<1>:<add> assert kwargs.get("filter") == "storageUrl eq 'https://test.blob.core.windows.net/content/a.txt'"
<del> assert kwargs.get("filter") == "sourcefile eq 'a.txt'"
<10>:<add> url="https://test.blob.core.windows.net/content/a.txt",
<del> document="a.txt",
|
# module: tests.test_manageacl
@pytest.mark.asyncio
async def test_view_acl(monkeypatch, capsys):
<0> async def mock_search(self, *args, **kwargs):
<1> assert kwargs.get("filter") == "sourcefile eq 'a.txt'"
<2> assert kwargs.get("select") == ["id", "oids"]
<3> return AsyncSearchResultsIterator([{"oids": ["OID_ACL"]}])
<4>
<5> monkeypatch.setattr(SearchClient, "search", mock_search)
<6>
<7> command = ManageAcl(
<8> service_name="SERVICE",
<9> index_name="INDEX",
<10> document="a.txt",
<11> acl_action="view",
<12> acl_type="oids",
<13> acl="",
<14> credentials=MockAzureCredential(),
<15> )
<16> await command.run()
<17> captured = capsys.readouterr()
<18> assert captured.out.strip() == '["OID_ACL"]'
<19>
|
===========unchanged ref 0===========
at: _pytest.capture
capsys(request: SubRequest) -> Generator[CaptureFixture[str], None, None]
at: _pytest.mark.structures
MARK_GEN = MarkGenerator(_ispytest=True)
at: _pytest.monkeypatch
monkeypatch() -> Generator["MonkeyPatch", None, None]
at: scripts.manageacl
ManageAcl(service_name: str, index_name: str, url: str, acl_action: str, acl_type: str, acl: str, credentials: Union[AsyncTokenCredential, AzureKeyCredential])
at: scripts.manageacl.ManageAcl
run()
at: tests.test_manageacl
AsyncSearchResultsIterator(results)
at: typing.Mapping
get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]
get(key: _KT) -> Optional[_VT_co]
===========changed ref 0===========
# module: scripts.manageacl
class ManageAcl:
def run(self):
endpoint = f"https://{self.service_name}.search.windows.net"
if self.acl_action == "enable_acls":
await self.enable_acls(endpoint)
return
async with SearchClient(
endpoint=endpoint, index_name=self.index_name, credential=self.credentials
) as search_client:
if self.acl_action == "view":
await self.view_acl(search_client)
elif self.acl_action == "remove":
await self.remove_acl(search_client)
elif self.acl_action == "remove_all":
await self.remove_all_acls(search_client)
elif self.acl_action == "add":
await self.add_acl(search_client)
+ elif self.acl_action == "update_storage_urls":
+ await self.update_storage_urls(search_client)
else:
raise Exception(f"Unknown action {self.acl_action}")
- logging.info("ACLs updated")
-
===========changed ref 1===========
# module: app.backend.prepdocslib.listfilestrategy
class File:
+ def __init__(self, content: IO, acls: Optional[dict[str, list]] = None, url: Optional[str] = None):
- def __init__(self, content: IO, acls: Optional[dict[str, list]] = None):
self.content = content
self.acls = acls or {}
+ self.url = url
===========changed ref 2===========
# module: scripts.manageacl
class ManageAcl:
def view_acl(self, search_client: SearchClient):
+ for document in await self.get_documents(search_client):
- async for document in await self.get_documents(search_client):
# Assumes the acls are consistent across all sections of the document
print(json.dumps(document[self.acl_type]))
return
===========changed ref 3===========
# module: scripts.manageacl
class ManageAcl:
def get_documents(self, search_client: SearchClient):
+ filter = f"storageUrl eq '{self.url}'"
- filter = f"sourcefile eq '{self.document}'"
+ documents = await search_client.search("", filter=filter, select=["id", self.acl_type])
- result = await search_client.search("", filter=filter, select=["id", self.acl_type])
+ found_documents = []
+ async for document in documents:
+ found_documents.append(document)
+ logger.info("Found %d search documents with storageUrl %s", len(found_documents), self.url)
+ return found_documents
- return result
===========changed ref 4===========
# module: tests.test_searchmanager
@pytest.mark.asyncio
async def test_create_index_doesnt_exist_yet(monkeypatch, search_info):
indexes = []
async def mock_create_index(self, index):
indexes.append(index)
async def mock_list_index_names(self):
for index in []:
yield index
monkeypatch.setattr(SearchIndexClient, "create_index", mock_create_index)
monkeypatch.setattr(SearchIndexClient, "list_index_names", mock_list_index_names)
manager = SearchManager(search_info)
await manager.create_index()
assert len(indexes) == 1, "It should have created one index"
assert indexes[0].name == "test"
+ assert len(indexes[0].fields) == 7
- assert len(indexes[0].fields) == 6
===========changed ref 5===========
# module: tests.test_searchmanager
@pytest.mark.asyncio
async def test_create_index_using_int_vectorization(monkeypatch, search_info):
indexes = []
async def mock_create_index(self, index):
indexes.append(index)
async def mock_list_index_names(self):
for index in []:
yield index
monkeypatch.setattr(SearchIndexClient, "create_index", mock_create_index)
monkeypatch.setattr(SearchIndexClient, "list_index_names", mock_list_index_names)
manager = SearchManager(search_info, use_int_vectorization=True)
await manager.create_index()
assert len(indexes) == 1, "It should have created one index"
assert indexes[0].name == "test"
+ assert len(indexes[0].fields) == 8
- assert len(indexes[0].fields) == 7
===========changed ref 6===========
# module: tests.test_searchmanager
@pytest.mark.asyncio
async def test_create_index_acls(monkeypatch, search_info):
indexes = []
async def mock_create_index(self, index):
indexes.append(index)
async def mock_list_index_names(self):
for index in []:
yield index
monkeypatch.setattr(SearchIndexClient, "create_index", mock_create_index)
monkeypatch.setattr(SearchIndexClient, "list_index_names", mock_list_index_names)
manager = SearchManager(
search_info,
use_acls=True,
)
await manager.create_index()
assert len(indexes) == 1, "It should have created one index"
assert indexes[0].name == "test"
+ assert len(indexes[0].fields) == 9
- assert len(indexes[0].fields) == 8
===========changed ref 7===========
# module: scripts.manageacl
def main(args: Any):
# Use the current user identity to connect to Azure services unless a key is explicitly set for any of them
azd_credential = (
AzureDeveloperCliCredential()
if args.tenant_id is None
else AzureDeveloperCliCredential(tenant_id=args.tenant_id, process_timeout=60)
)
search_credential: Union[AsyncTokenCredential, AzureKeyCredential] = azd_credential
if args.search_key is not None:
search_credential = AzureKeyCredential(args.search_key)
command = ManageAcl(
service_name=args.search_service,
index_name=args.index,
+ url=args.url,
- document=args.document,
acl_action=args.acl_action,
acl_type=args.acl_type,
acl=args.acl,
credentials=search_credential,
)
await command.run()
|
tests.test_manageacl/test_remove_acl
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
0124725ad85726aa3f62450e16fb136a63154f69
|
Adds storageURL field to track file location (#1535)
|
<1>:<add> assert kwargs.get("filter") == "storageUrl eq 'https://test.blob.core.windows.net/content/a.txt'"
<del> assert kwargs.get("filter") == "sourcefile eq 'a.txt'"
<22>:<add> url="https://test.blob.core.windows.net/content/a.txt",
<del> document="a.txt",
|
# module: tests.test_manageacl
@pytest.mark.asyncio
async def test_remove_acl(monkeypatch, capsys):
<0> async def mock_search(self, *args, **kwargs):
<1> assert kwargs.get("filter") == "sourcefile eq 'a.txt'"
<2> assert kwargs.get("select") == ["id", "oids"]
<3> return AsyncSearchResultsIterator(
<4> [
<5> {"id": 1, "oids": ["OID_ACL_TO_KEEP", "OID_ACL_TO_REMOVE"]},
<6> {"id": 2, "oids": ["OID_ACL_TO_KEEP", "OID_ACL_TO_REMOVE"]},
<7> ]
<8> )
<9>
<10> merged_documents = []
<11>
<12> async def mock_merge_documents(self, *args, **kwargs):
<13> for document in kwargs.get("documents"):
<14> merged_documents.append(document)
<15>
<16> monkeypatch.setattr(SearchClient, "search", mock_search)
<17> monkeypatch.setattr(SearchClient, "merge_documents", mock_merge_documents)
<18>
<19> command = ManageAcl(
<20> service_name="SERVICE",
<21> index_name="INDEX",
<22> document="a.txt",
<23> acl_action="remove",
<24> acl_type="oids",
<25> acl="OID_ACL_TO_REMOVE",
<26> credentials=MockAzureCredential(),
<27> )
<28> await command.run()
<29> assert merged_documents == [{"id": 2, "oids": ["OID_ACL_TO_KEEP"]}, {"id": 1, "oids": ["OID_ACL_TO_KEEP"]}]
<30>
|
===========unchanged ref 0===========
at: _pytest.mark.structures
MARK_GEN = MarkGenerator(_ispytest=True)
at: scripts.manageacl
ManageAcl(service_name: str, index_name: str, url: str, acl_action: str, acl_type: str, acl: str, credentials: Union[AsyncTokenCredential, AzureKeyCredential])
at: scripts.manageacl.ManageAcl
run()
at: tests.test_manageacl
AsyncSearchResultsIterator(results)
at: typing.Mapping
get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]
get(key: _KT) -> Optional[_VT_co]
===========changed ref 0===========
# module: scripts.manageacl
class ManageAcl:
def run(self):
endpoint = f"https://{self.service_name}.search.windows.net"
if self.acl_action == "enable_acls":
await self.enable_acls(endpoint)
return
async with SearchClient(
endpoint=endpoint, index_name=self.index_name, credential=self.credentials
) as search_client:
if self.acl_action == "view":
await self.view_acl(search_client)
elif self.acl_action == "remove":
await self.remove_acl(search_client)
elif self.acl_action == "remove_all":
await self.remove_all_acls(search_client)
elif self.acl_action == "add":
await self.add_acl(search_client)
+ elif self.acl_action == "update_storage_urls":
+ await self.update_storage_urls(search_client)
else:
raise Exception(f"Unknown action {self.acl_action}")
- logging.info("ACLs updated")
-
===========changed ref 1===========
# module: tests.test_manageacl
@pytest.mark.asyncio
async def test_view_acl(monkeypatch, capsys):
async def mock_search(self, *args, **kwargs):
+ assert kwargs.get("filter") == "storageUrl eq 'https://test.blob.core.windows.net/content/a.txt'"
- assert kwargs.get("filter") == "sourcefile eq 'a.txt'"
assert kwargs.get("select") == ["id", "oids"]
return AsyncSearchResultsIterator([{"oids": ["OID_ACL"]}])
monkeypatch.setattr(SearchClient, "search", mock_search)
command = ManageAcl(
service_name="SERVICE",
index_name="INDEX",
+ url="https://test.blob.core.windows.net/content/a.txt",
- document="a.txt",
acl_action="view",
acl_type="oids",
acl="",
credentials=MockAzureCredential(),
)
await command.run()
captured = capsys.readouterr()
assert captured.out.strip() == '["OID_ACL"]'
===========changed ref 2===========
# module: app.backend.prepdocslib.listfilestrategy
class File:
+ def __init__(self, content: IO, acls: Optional[dict[str, list]] = None, url: Optional[str] = None):
- def __init__(self, content: IO, acls: Optional[dict[str, list]] = None):
self.content = content
self.acls = acls or {}
+ self.url = url
===========changed ref 3===========
# module: scripts.manageacl
class ManageAcl:
def view_acl(self, search_client: SearchClient):
+ for document in await self.get_documents(search_client):
- async for document in await self.get_documents(search_client):
# Assumes the acls are consistent across all sections of the document
print(json.dumps(document[self.acl_type]))
return
===========changed ref 4===========
# module: scripts.manageacl
class ManageAcl:
def get_documents(self, search_client: SearchClient):
+ filter = f"storageUrl eq '{self.url}'"
- filter = f"sourcefile eq '{self.document}'"
+ documents = await search_client.search("", filter=filter, select=["id", self.acl_type])
- result = await search_client.search("", filter=filter, select=["id", self.acl_type])
+ found_documents = []
+ async for document in documents:
+ found_documents.append(document)
+ logger.info("Found %d search documents with storageUrl %s", len(found_documents), self.url)
+ return found_documents
- return result
===========changed ref 5===========
# module: tests.test_searchmanager
@pytest.mark.asyncio
async def test_create_index_doesnt_exist_yet(monkeypatch, search_info):
indexes = []
async def mock_create_index(self, index):
indexes.append(index)
async def mock_list_index_names(self):
for index in []:
yield index
monkeypatch.setattr(SearchIndexClient, "create_index", mock_create_index)
monkeypatch.setattr(SearchIndexClient, "list_index_names", mock_list_index_names)
manager = SearchManager(search_info)
await manager.create_index()
assert len(indexes) == 1, "It should have created one index"
assert indexes[0].name == "test"
+ assert len(indexes[0].fields) == 7
- assert len(indexes[0].fields) == 6
===========changed ref 6===========
# module: tests.test_searchmanager
@pytest.mark.asyncio
async def test_create_index_using_int_vectorization(monkeypatch, search_info):
indexes = []
async def mock_create_index(self, index):
indexes.append(index)
async def mock_list_index_names(self):
for index in []:
yield index
monkeypatch.setattr(SearchIndexClient, "create_index", mock_create_index)
monkeypatch.setattr(SearchIndexClient, "list_index_names", mock_list_index_names)
manager = SearchManager(search_info, use_int_vectorization=True)
await manager.create_index()
assert len(indexes) == 1, "It should have created one index"
assert indexes[0].name == "test"
+ assert len(indexes[0].fields) == 8
- assert len(indexes[0].fields) == 7
===========changed ref 7===========
# module: tests.test_searchmanager
@pytest.mark.asyncio
async def test_create_index_acls(monkeypatch, search_info):
indexes = []
async def mock_create_index(self, index):
indexes.append(index)
async def mock_list_index_names(self):
for index in []:
yield index
monkeypatch.setattr(SearchIndexClient, "create_index", mock_create_index)
monkeypatch.setattr(SearchIndexClient, "list_index_names", mock_list_index_names)
manager = SearchManager(
search_info,
use_acls=True,
)
await manager.create_index()
assert len(indexes) == 1, "It should have created one index"
assert indexes[0].name == "test"
+ assert len(indexes[0].fields) == 9
- assert len(indexes[0].fields) == 8
|
tests.test_manageacl/test_remove_all_acl
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
0124725ad85726aa3f62450e16fb136a63154f69
|
Adds storageURL field to track file location (#1535)
|
<1>:<add> assert kwargs.get("filter") == "storageUrl eq 'https://test.blob.core.windows.net/content/a.txt'"
<del> assert kwargs.get("filter") == "sourcefile eq 'a.txt'"
<22>:<add> url="https://test.blob.core.windows.net/content/a.txt",
<del> document="a.txt",
|
# module: tests.test_manageacl
@pytest.mark.asyncio
async def test_remove_all_acl(monkeypatch, capsys):
<0> async def mock_search(self, *args, **kwargs):
<1> assert kwargs.get("filter") == "sourcefile eq 'a.txt'"
<2> assert kwargs.get("select") == ["id", "oids"]
<3> return AsyncSearchResultsIterator(
<4> [
<5> {"id": 1, "oids": ["OID_ACL_TO_REMOVE", "OID_ACL_TO_REMOVE"]},
<6> {"id": 2, "oids": ["OID_ACL_TO_REMOVE", "OID_ACL_TO_REMOVE"]},
<7> ]
<8> )
<9>
<10> merged_documents = []
<11>
<12> async def mock_merge_documents(self, *args, **kwargs):
<13> for document in kwargs.get("documents"):
<14> merged_documents.append(document)
<15>
<16> monkeypatch.setattr(SearchClient, "search", mock_search)
<17> monkeypatch.setattr(SearchClient, "merge_documents", mock_merge_documents)
<18>
<19> command = ManageAcl(
<20> service_name="SERVICE",
<21> index_name="INDEX",
<22> document="a.txt",
<23> acl_action="remove_all",
<24> acl_type="oids",
<25> acl="",
<26> credentials=MockAzureCredential(),
<27> )
<28> await command.run()
<29> assert merged_documents == [{"id": 2, "oids": []}, {"id": 1, "oids": []}]
<30>
|
===========unchanged ref 0===========
at: _pytest.mark.structures
MARK_GEN = MarkGenerator(_ispytest=True)
at: scripts.manageacl
ManageAcl(service_name: str, index_name: str, url: str, acl_action: str, acl_type: str, acl: str, credentials: Union[AsyncTokenCredential, AzureKeyCredential])
at: scripts.manageacl.ManageAcl
run()
at: tests.test_manageacl
AsyncSearchResultsIterator(results)
at: typing.Mapping
get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]
get(key: _KT) -> Optional[_VT_co]
===========changed ref 0===========
# module: scripts.manageacl
class ManageAcl:
def run(self):
endpoint = f"https://{self.service_name}.search.windows.net"
if self.acl_action == "enable_acls":
await self.enable_acls(endpoint)
return
async with SearchClient(
endpoint=endpoint, index_name=self.index_name, credential=self.credentials
) as search_client:
if self.acl_action == "view":
await self.view_acl(search_client)
elif self.acl_action == "remove":
await self.remove_acl(search_client)
elif self.acl_action == "remove_all":
await self.remove_all_acls(search_client)
elif self.acl_action == "add":
await self.add_acl(search_client)
+ elif self.acl_action == "update_storage_urls":
+ await self.update_storage_urls(search_client)
else:
raise Exception(f"Unknown action {self.acl_action}")
- logging.info("ACLs updated")
-
===========changed ref 1===========
# module: tests.test_manageacl
@pytest.mark.asyncio
async def test_view_acl(monkeypatch, capsys):
async def mock_search(self, *args, **kwargs):
+ assert kwargs.get("filter") == "storageUrl eq 'https://test.blob.core.windows.net/content/a.txt'"
- assert kwargs.get("filter") == "sourcefile eq 'a.txt'"
assert kwargs.get("select") == ["id", "oids"]
return AsyncSearchResultsIterator([{"oids": ["OID_ACL"]}])
monkeypatch.setattr(SearchClient, "search", mock_search)
command = ManageAcl(
service_name="SERVICE",
index_name="INDEX",
+ url="https://test.blob.core.windows.net/content/a.txt",
- document="a.txt",
acl_action="view",
acl_type="oids",
acl="",
credentials=MockAzureCredential(),
)
await command.run()
captured = capsys.readouterr()
assert captured.out.strip() == '["OID_ACL"]'
===========changed ref 2===========
# module: tests.test_manageacl
@pytest.mark.asyncio
async def test_remove_acl(monkeypatch, capsys):
async def mock_search(self, *args, **kwargs):
+ assert kwargs.get("filter") == "storageUrl eq 'https://test.blob.core.windows.net/content/a.txt'"
- assert kwargs.get("filter") == "sourcefile eq 'a.txt'"
assert kwargs.get("select") == ["id", "oids"]
return AsyncSearchResultsIterator(
[
{"id": 1, "oids": ["OID_ACL_TO_KEEP", "OID_ACL_TO_REMOVE"]},
{"id": 2, "oids": ["OID_ACL_TO_KEEP", "OID_ACL_TO_REMOVE"]},
]
)
merged_documents = []
async def mock_merge_documents(self, *args, **kwargs):
for document in kwargs.get("documents"):
merged_documents.append(document)
monkeypatch.setattr(SearchClient, "search", mock_search)
monkeypatch.setattr(SearchClient, "merge_documents", mock_merge_documents)
command = ManageAcl(
service_name="SERVICE",
index_name="INDEX",
+ url="https://test.blob.core.windows.net/content/a.txt",
- document="a.txt",
acl_action="remove",
acl_type="oids",
acl="OID_ACL_TO_REMOVE",
credentials=MockAzureCredential(),
)
await command.run()
assert merged_documents == [{"id": 2, "oids": ["OID_ACL_TO_KEEP"]}, {"id": 1, "oids": ["OID_ACL_TO_KEEP"]}]
===========changed ref 3===========
# module: app.backend.prepdocslib.listfilestrategy
class File:
+ def __init__(self, content: IO, acls: Optional[dict[str, list]] = None, url: Optional[str] = None):
- def __init__(self, content: IO, acls: Optional[dict[str, list]] = None):
self.content = content
self.acls = acls or {}
+ self.url = url
===========changed ref 4===========
# module: scripts.manageacl
class ManageAcl:
def view_acl(self, search_client: SearchClient):
+ for document in await self.get_documents(search_client):
- async for document in await self.get_documents(search_client):
# Assumes the acls are consistent across all sections of the document
print(json.dumps(document[self.acl_type]))
return
===========changed ref 5===========
# module: scripts.manageacl
class ManageAcl:
def get_documents(self, search_client: SearchClient):
+ filter = f"storageUrl eq '{self.url}'"
- filter = f"sourcefile eq '{self.document}'"
+ documents = await search_client.search("", filter=filter, select=["id", self.acl_type])
- result = await search_client.search("", filter=filter, select=["id", self.acl_type])
+ found_documents = []
+ async for document in documents:
+ found_documents.append(document)
+ logger.info("Found %d search documents with storageUrl %s", len(found_documents), self.url)
+ return found_documents
- return result
===========changed ref 6===========
# module: tests.test_searchmanager
@pytest.mark.asyncio
async def test_create_index_doesnt_exist_yet(monkeypatch, search_info):
indexes = []
async def mock_create_index(self, index):
indexes.append(index)
async def mock_list_index_names(self):
for index in []:
yield index
monkeypatch.setattr(SearchIndexClient, "create_index", mock_create_index)
monkeypatch.setattr(SearchIndexClient, "list_index_names", mock_list_index_names)
manager = SearchManager(search_info)
await manager.create_index()
assert len(indexes) == 1, "It should have created one index"
assert indexes[0].name == "test"
+ assert len(indexes[0].fields) == 7
- assert len(indexes[0].fields) == 6
|
tests.test_manageacl/test_add_acl
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
0124725ad85726aa3f62450e16fb136a63154f69
|
Adds storageURL field to track file location (#1535)
|
<1>:<add> assert kwargs.get("filter") == "storageUrl eq 'https://test.blob.core.windows.net/content/a.txt'"
<del> assert kwargs.get("filter") == "sourcefile eq 'a.txt'"
<17>:<add> url="https://test.blob.core.windows.net/content/a.txt",
<del> document="a.txt",
<23>:<add> with caplog.at_level(logging.INFO):
<add> await command.run()
<del> await command.run()
<24>:<add> assert merged_documents == []
<add> assert "Search document 1 already has oids acl OID_EXISTS" in caplog.text
<add> assert "Search document 2 already has oids acl OID_EXISTS" in caplog.text
<add> assert "Not updating any search documents" in caplog.text
<del> assert merged_documents == [{"id": 2, "oids": ["OID_EXISTS"]}, {"id": 1, "oids": ["OID_EXISTS"]}]
<30>:<add> url="https://test.blob.core.windows.net/content/a.txt",
<del> document="a.txt",
<36>:<add> with caplog.at_level(logging.INFO):
<add> await command.run()
<del> await command.run()
<37>:<add> assert merged_documents == [
<del> assert merged_documents == [
<38>:<add> {"id": 2, "
|
# module: tests.test_manageacl
@pytest.mark.asyncio
+ async def test_add_acl(monkeypatch, caplog):
- async def test_add_acl(monkeypatch, capsys):
<0> async def mock_search(self, *args, **kwargs):
<1> assert kwargs.get("filter") == "sourcefile eq 'a.txt'"
<2> assert kwargs.get("select") == ["id", "oids"]
<3> return AsyncSearchResultsIterator([{"id": 1, "oids": ["OID_EXISTS"]}, {"id": 2, "oids": ["OID_EXISTS"]}])
<4>
<5> merged_documents = []
<6>
<7> async def mock_merge_documents(self, *args, **kwargs):
<8> for document in kwargs.get("documents"):
<9> merged_documents.append(document)
<10>
<11> monkeypatch.setattr(SearchClient, "search", mock_search)
<12> monkeypatch.setattr(SearchClient, "merge_documents", mock_merge_documents)
<13>
<14> command = ManageAcl(
<15> service_name="SERVICE",
<16> index_name="INDEX",
<17> document="a.txt",
<18> acl_action="add",
<19> acl_type="oids",
<20> acl="OID_EXISTS",
<21> credentials=MockAzureCredential(),
<22> )
<23> await command.run()
<24> assert merged_documents == [{"id": 2, "oids": ["OID_EXISTS"]}, {"id": 1, "oids": ["OID_EXISTS"]}]
<25>
<26> merged_documents.clear()
<27> command = ManageAcl(
<28> service_name="SERVICE",
<29> index_name="INDEX",
<30> document="a.txt",
<31> acl_action="add",
<32> acl_type="oids",
<33> acl="OID_ADD",
<34> credentials=MockAzureCredential(),
<35> )
<36> await command.run()
<37> assert merged_documents == [
<38> {"id": 2, "oids": ["OID_EXISTS", "OID_ADD"]},
<39> {"id": 1, "oids": ["OID_EXISTS", "</s>
|
===========below chunk 0===========
# module: tests.test_manageacl
@pytest.mark.asyncio
+ async def test_add_acl(monkeypatch, caplog):
- async def test_add_acl(monkeypatch, capsys):
# offset: 1
]
===========unchanged ref 0===========
at: _pytest.mark.structures
MARK_GEN = MarkGenerator(_ispytest=True)
at: scripts.manageacl
ManageAcl(service_name: str, index_name: str, url: str, acl_action: str, acl_type: str, acl: str, credentials: Union[AsyncTokenCredential, AzureKeyCredential])
at: scripts.manageacl.ManageAcl
run()
at: tests.test_manageacl
AsyncSearchResultsIterator(results)
at: typing.Mapping
get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]
get(key: _KT) -> Optional[_VT_co]
===========changed ref 0===========
# module: scripts.manageacl
class ManageAcl:
def run(self):
endpoint = f"https://{self.service_name}.search.windows.net"
if self.acl_action == "enable_acls":
await self.enable_acls(endpoint)
return
async with SearchClient(
endpoint=endpoint, index_name=self.index_name, credential=self.credentials
) as search_client:
if self.acl_action == "view":
await self.view_acl(search_client)
elif self.acl_action == "remove":
await self.remove_acl(search_client)
elif self.acl_action == "remove_all":
await self.remove_all_acls(search_client)
elif self.acl_action == "add":
await self.add_acl(search_client)
+ elif self.acl_action == "update_storage_urls":
+ await self.update_storage_urls(search_client)
else:
raise Exception(f"Unknown action {self.acl_action}")
- logging.info("ACLs updated")
-
===========changed ref 1===========
# module: tests.test_manageacl
@pytest.mark.asyncio
async def test_view_acl(monkeypatch, capsys):
async def mock_search(self, *args, **kwargs):
+ assert kwargs.get("filter") == "storageUrl eq 'https://test.blob.core.windows.net/content/a.txt'"
- assert kwargs.get("filter") == "sourcefile eq 'a.txt'"
assert kwargs.get("select") == ["id", "oids"]
return AsyncSearchResultsIterator([{"oids": ["OID_ACL"]}])
monkeypatch.setattr(SearchClient, "search", mock_search)
command = ManageAcl(
service_name="SERVICE",
index_name="INDEX",
+ url="https://test.blob.core.windows.net/content/a.txt",
- document="a.txt",
acl_action="view",
acl_type="oids",
acl="",
credentials=MockAzureCredential(),
)
await command.run()
captured = capsys.readouterr()
assert captured.out.strip() == '["OID_ACL"]'
===========changed ref 2===========
# module: tests.test_manageacl
@pytest.mark.asyncio
async def test_remove_all_acl(monkeypatch, capsys):
async def mock_search(self, *args, **kwargs):
+ assert kwargs.get("filter") == "storageUrl eq 'https://test.blob.core.windows.net/content/a.txt'"
- assert kwargs.get("filter") == "sourcefile eq 'a.txt'"
assert kwargs.get("select") == ["id", "oids"]
return AsyncSearchResultsIterator(
[
{"id": 1, "oids": ["OID_ACL_TO_REMOVE", "OID_ACL_TO_REMOVE"]},
{"id": 2, "oids": ["OID_ACL_TO_REMOVE", "OID_ACL_TO_REMOVE"]},
]
)
merged_documents = []
async def mock_merge_documents(self, *args, **kwargs):
for document in kwargs.get("documents"):
merged_documents.append(document)
monkeypatch.setattr(SearchClient, "search", mock_search)
monkeypatch.setattr(SearchClient, "merge_documents", mock_merge_documents)
command = ManageAcl(
service_name="SERVICE",
index_name="INDEX",
+ url="https://test.blob.core.windows.net/content/a.txt",
- document="a.txt",
acl_action="remove_all",
acl_type="oids",
acl="",
credentials=MockAzureCredential(),
)
await command.run()
assert merged_documents == [{"id": 2, "oids": []}, {"id": 1, "oids": []}]
===========changed ref 3===========
# module: tests.test_manageacl
@pytest.mark.asyncio
async def test_remove_acl(monkeypatch, capsys):
async def mock_search(self, *args, **kwargs):
+ assert kwargs.get("filter") == "storageUrl eq 'https://test.blob.core.windows.net/content/a.txt'"
- assert kwargs.get("filter") == "sourcefile eq 'a.txt'"
assert kwargs.get("select") == ["id", "oids"]
return AsyncSearchResultsIterator(
[
{"id": 1, "oids": ["OID_ACL_TO_KEEP", "OID_ACL_TO_REMOVE"]},
{"id": 2, "oids": ["OID_ACL_TO_KEEP", "OID_ACL_TO_REMOVE"]},
]
)
merged_documents = []
async def mock_merge_documents(self, *args, **kwargs):
for document in kwargs.get("documents"):
merged_documents.append(document)
monkeypatch.setattr(SearchClient, "search", mock_search)
monkeypatch.setattr(SearchClient, "merge_documents", mock_merge_documents)
command = ManageAcl(
service_name="SERVICE",
index_name="INDEX",
+ url="https://test.blob.core.windows.net/content/a.txt",
- document="a.txt",
acl_action="remove",
acl_type="oids",
acl="OID_ACL_TO_REMOVE",
credentials=MockAzureCredential(),
)
await command.run()
assert merged_documents == [{"id": 2, "oids": ["OID_ACL_TO_KEEP"]}, {"id": 1, "oids": ["OID_ACL_TO_KEEP"]}]
===========changed ref 4===========
# module: app.backend.prepdocslib.listfilestrategy
class File:
+ def __init__(self, content: IO, acls: Optional[dict[str, list]] = None, url: Optional[str] = None):
- def __init__(self, content: IO, acls: Optional[dict[str, list]] = None):
self.content = content
self.acls = acls or {}
+ self.url = url
===========changed ref 5===========
# module: scripts.manageacl
class ManageAcl:
def view_acl(self, search_client: SearchClient):
+ for document in await self.get_documents(search_client):
- async for document in await self.get_documents(search_client):
# Assumes the acls are consistent across all sections of the document
print(json.dumps(document[self.acl_type]))
return
|
tests.test_manageacl/test_enable_acls_with_missing_fields
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
0124725ad85726aa3f62450e16fb136a63154f69
|
Adds storageURL field to track file location (#1535)
|
<14>:<add> url="",
<del> document="",
|
# module: tests.test_manageacl
@pytest.mark.asyncio
async def test_enable_acls_with_missing_fields(monkeypatch, capsys):
<0> async def mock_get_index(self, *args, **kwargs):
<1> return SearchIndex(name="INDEX", fields=[])
<2>
<3> updated_index = []
<4>
<5> async def mock_create_or_update_index(self, index, *args, **kwargs):
<6> updated_index.append(index)
<7>
<8> monkeypatch.setattr(SearchIndexClient, "get_index", mock_get_index)
<9> monkeypatch.setattr(SearchIndexClient, "create_or_update_index", mock_create_or_update_index)
<10>
<11> command = ManageAcl(
<12> service_name="SERVICE",
<13> index_name="INDEX",
<14> document="",
<15> acl_action="enable_acls",
<16> acl_type="",
<17> acl="",
<18> credentials=MockAzureCredential(),
<19> )
<20> await command.run()
<21> assert len(updated_index) == 1
<22> index = updated_index[0]
<23> validate_index(index)
<24>
|
===========unchanged ref 0===========
at: _pytest.mark.structures
MARK_GEN = MarkGenerator(_ispytest=True)
at: scripts.manageacl
ManageAcl(service_name: str, index_name: str, url: str, acl_action: str, acl_type: str, acl: str, credentials: Union[AsyncTokenCredential, AzureKeyCredential])
at: scripts.manageacl.ManageAcl
run()
at: tests.test_manageacl
validate_index(index)
===========changed ref 0===========
# module: scripts.manageacl
class ManageAcl:
def run(self):
endpoint = f"https://{self.service_name}.search.windows.net"
if self.acl_action == "enable_acls":
await self.enable_acls(endpoint)
return
async with SearchClient(
endpoint=endpoint, index_name=self.index_name, credential=self.credentials
) as search_client:
if self.acl_action == "view":
await self.view_acl(search_client)
elif self.acl_action == "remove":
await self.remove_acl(search_client)
elif self.acl_action == "remove_all":
await self.remove_all_acls(search_client)
elif self.acl_action == "add":
await self.add_acl(search_client)
+ elif self.acl_action == "update_storage_urls":
+ await self.update_storage_urls(search_client)
else:
raise Exception(f"Unknown action {self.acl_action}")
- logging.info("ACLs updated")
-
===========changed ref 1===========
# module: tests.test_manageacl
@pytest.mark.asyncio
async def test_view_acl(monkeypatch, capsys):
async def mock_search(self, *args, **kwargs):
+ assert kwargs.get("filter") == "storageUrl eq 'https://test.blob.core.windows.net/content/a.txt'"
- assert kwargs.get("filter") == "sourcefile eq 'a.txt'"
assert kwargs.get("select") == ["id", "oids"]
return AsyncSearchResultsIterator([{"oids": ["OID_ACL"]}])
monkeypatch.setattr(SearchClient, "search", mock_search)
command = ManageAcl(
service_name="SERVICE",
index_name="INDEX",
+ url="https://test.blob.core.windows.net/content/a.txt",
- document="a.txt",
acl_action="view",
acl_type="oids",
acl="",
credentials=MockAzureCredential(),
)
await command.run()
captured = capsys.readouterr()
assert captured.out.strip() == '["OID_ACL"]'
===========changed ref 2===========
# module: tests.test_manageacl
+ @pytest.mark.asyncio
+ async def test_update_storage_urls(monkeypatch, caplog):
+ async def mock_search(self, *args, **kwargs):
+ assert kwargs.get("filter") == "storageUrl eq ''"
+ assert kwargs.get("select") == ["id", "storageUrl", "oids", "sourcefile"]
+ return AsyncSearchResultsIterator(
+ [
+ {"id": 1, "oids": ["OID_EXISTS"], "storageUrl": "", "sourcefile": "a.txt"},
+ {"id": 2, "oids": [], "storageUrl": "", "sourcefile": "ab.txt"},
+ ]
+ )
+
+ merged_documents = []
+
+ async def mock_merge_documents(self, *args, **kwargs):
+ for document in kwargs.get("documents"):
+ merged_documents.append(document)
+
+ monkeypatch.setattr(SearchClient, "search", mock_search)
+ monkeypatch.setattr(SearchClient, "merge_documents", mock_merge_documents)
+
+ command = ManageAcl(
+ service_name="SERVICE",
+ index_name="INDEX",
+ url="https://test.blob.core.windows.net/content/",
+ acl_action="update_storage_urls",
+ acl_type="",
+ acl="",
+ credentials=MockAzureCredential(),
+ )
+ with caplog.at_level(logging.INFO):
+ await command.run()
+ assert merged_documents == [{"id": 2, "storageUrl": "https://test.blob.core.windows.net/content/ab.txt"}]
+ assert "Not updating storage URL of document 1 as it has only one oid and may be user uploaded" in caplog.text
+ assert "Adding storage URL https://test.blob.core.windows.net/content/ab.txt for document 2" in caplog.text
+ assert "Updating storage URL for 1 search documents" in caplog.text
+
===========changed ref 3===========
# module: tests.test_manageacl
@pytest.mark.asyncio
async def test_remove_all_acl(monkeypatch, capsys):
async def mock_search(self, *args, **kwargs):
+ assert kwargs.get("filter") == "storageUrl eq 'https://test.blob.core.windows.net/content/a.txt'"
- assert kwargs.get("filter") == "sourcefile eq 'a.txt'"
assert kwargs.get("select") == ["id", "oids"]
return AsyncSearchResultsIterator(
[
{"id": 1, "oids": ["OID_ACL_TO_REMOVE", "OID_ACL_TO_REMOVE"]},
{"id": 2, "oids": ["OID_ACL_TO_REMOVE", "OID_ACL_TO_REMOVE"]},
]
)
merged_documents = []
async def mock_merge_documents(self, *args, **kwargs):
for document in kwargs.get("documents"):
merged_documents.append(document)
monkeypatch.setattr(SearchClient, "search", mock_search)
monkeypatch.setattr(SearchClient, "merge_documents", mock_merge_documents)
command = ManageAcl(
service_name="SERVICE",
index_name="INDEX",
+ url="https://test.blob.core.windows.net/content/a.txt",
- document="a.txt",
acl_action="remove_all",
acl_type="oids",
acl="",
credentials=MockAzureCredential(),
)
await command.run()
assert merged_documents == [{"id": 2, "oids": []}, {"id": 1, "oids": []}]
|
tests.test_manageacl/test_enable_acls_without_missing_fields
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
0124725ad85726aa3f62450e16fb136a63154f69
|
Adds storageURL field to track file location (#1535)
|
<28>:<add> url="",
<del> document="",
|
# module: tests.test_manageacl
@pytest.mark.asyncio
async def test_enable_acls_without_missing_fields(monkeypatch, capsys):
<0> async def mock_get_index(self, *args, **kwargs):
<1> return SearchIndex(
<2> name="INDEX",
<3> fields=[
<4> SimpleField(
<5> name="oids",
<6> type=SearchFieldDataType.Collection(SearchFieldDataType.String),
<7> filterable=True,
<8> ),
<9> SimpleField(
<10> name="groups",
<11> type=SearchFieldDataType.Collection(SearchFieldDataType.String),
<12> filterable=True,
<13> ),
<14> ],
<15> )
<16>
<17> updated_index = []
<18>
<19> async def mock_create_or_update_index(self, index, *args, **kwargs):
<20> updated_index.append(index)
<21>
<22> monkeypatch.setattr(SearchIndexClient, "get_index", mock_get_index)
<23> monkeypatch.setattr(SearchIndexClient, "create_or_update_index", mock_create_or_update_index)
<24>
<25> command = ManageAcl(
<26> service_name="SERVICE",
<27> index_name="INDEX",
<28> document="",
<29> acl_action="enable_acls",
<30> acl_type="",
<31> acl="",
<32> credentials=MockAzureCredential(),
<33> )
<34> await command.run()
<35> assert len(updated_index) == 1
<36> index = updated_index[0]
<37> validate_index(index)
<38>
|
===========unchanged ref 0===========
at: _pytest.mark.structures
MARK_GEN = MarkGenerator(_ispytest=True)
at: scripts.manageacl
ManageAcl(service_name: str, index_name: str, url: str, acl_action: str, acl_type: str, acl: str, credentials: Union[AsyncTokenCredential, AzureKeyCredential])
at: scripts.manageacl.ManageAcl
run()
at: tests.test_manageacl
validate_index(index)
===========changed ref 0===========
# module: scripts.manageacl
class ManageAcl:
def run(self):
endpoint = f"https://{self.service_name}.search.windows.net"
if self.acl_action == "enable_acls":
await self.enable_acls(endpoint)
return
async with SearchClient(
endpoint=endpoint, index_name=self.index_name, credential=self.credentials
) as search_client:
if self.acl_action == "view":
await self.view_acl(search_client)
elif self.acl_action == "remove":
await self.remove_acl(search_client)
elif self.acl_action == "remove_all":
await self.remove_all_acls(search_client)
elif self.acl_action == "add":
await self.add_acl(search_client)
+ elif self.acl_action == "update_storage_urls":
+ await self.update_storage_urls(search_client)
else:
raise Exception(f"Unknown action {self.acl_action}")
- logging.info("ACLs updated")
-
===========changed ref 1===========
# module: tests.test_manageacl
@pytest.mark.asyncio
async def test_enable_acls_with_missing_fields(monkeypatch, capsys):
async def mock_get_index(self, *args, **kwargs):
return SearchIndex(name="INDEX", fields=[])
updated_index = []
async def mock_create_or_update_index(self, index, *args, **kwargs):
updated_index.append(index)
monkeypatch.setattr(SearchIndexClient, "get_index", mock_get_index)
monkeypatch.setattr(SearchIndexClient, "create_or_update_index", mock_create_or_update_index)
command = ManageAcl(
service_name="SERVICE",
index_name="INDEX",
+ url="",
- document="",
acl_action="enable_acls",
acl_type="",
acl="",
credentials=MockAzureCredential(),
)
await command.run()
assert len(updated_index) == 1
index = updated_index[0]
validate_index(index)
===========changed ref 2===========
# module: tests.test_manageacl
@pytest.mark.asyncio
async def test_view_acl(monkeypatch, capsys):
async def mock_search(self, *args, **kwargs):
+ assert kwargs.get("filter") == "storageUrl eq 'https://test.blob.core.windows.net/content/a.txt'"
- assert kwargs.get("filter") == "sourcefile eq 'a.txt'"
assert kwargs.get("select") == ["id", "oids"]
return AsyncSearchResultsIterator([{"oids": ["OID_ACL"]}])
monkeypatch.setattr(SearchClient, "search", mock_search)
command = ManageAcl(
service_name="SERVICE",
index_name="INDEX",
+ url="https://test.blob.core.windows.net/content/a.txt",
- document="a.txt",
acl_action="view",
acl_type="oids",
acl="",
credentials=MockAzureCredential(),
)
await command.run()
captured = capsys.readouterr()
assert captured.out.strip() == '["OID_ACL"]'
===========changed ref 3===========
# module: tests.test_manageacl
+ @pytest.mark.asyncio
+ async def test_update_storage_urls(monkeypatch, caplog):
+ async def mock_search(self, *args, **kwargs):
+ assert kwargs.get("filter") == "storageUrl eq ''"
+ assert kwargs.get("select") == ["id", "storageUrl", "oids", "sourcefile"]
+ return AsyncSearchResultsIterator(
+ [
+ {"id": 1, "oids": ["OID_EXISTS"], "storageUrl": "", "sourcefile": "a.txt"},
+ {"id": 2, "oids": [], "storageUrl": "", "sourcefile": "ab.txt"},
+ ]
+ )
+
+ merged_documents = []
+
+ async def mock_merge_documents(self, *args, **kwargs):
+ for document in kwargs.get("documents"):
+ merged_documents.append(document)
+
+ monkeypatch.setattr(SearchClient, "search", mock_search)
+ monkeypatch.setattr(SearchClient, "merge_documents", mock_merge_documents)
+
+ command = ManageAcl(
+ service_name="SERVICE",
+ index_name="INDEX",
+ url="https://test.blob.core.windows.net/content/",
+ acl_action="update_storage_urls",
+ acl_type="",
+ acl="",
+ credentials=MockAzureCredential(),
+ )
+ with caplog.at_level(logging.INFO):
+ await command.run()
+ assert merged_documents == [{"id": 2, "storageUrl": "https://test.blob.core.windows.net/content/ab.txt"}]
+ assert "Not updating storage URL of document 1 as it has only one oid and may be user uploaded" in caplog.text
+ assert "Adding storage URL https://test.blob.core.windows.net/content/ab.txt for document 2" in caplog.text
+ assert "Updating storage URL for 1 search documents" in caplog.text
+
===========changed ref 4===========
# module: tests.test_manageacl
@pytest.mark.asyncio
async def test_remove_all_acl(monkeypatch, capsys):
async def mock_search(self, *args, **kwargs):
+ assert kwargs.get("filter") == "storageUrl eq 'https://test.blob.core.windows.net/content/a.txt'"
- assert kwargs.get("filter") == "sourcefile eq 'a.txt'"
assert kwargs.get("select") == ["id", "oids"]
return AsyncSearchResultsIterator(
[
{"id": 1, "oids": ["OID_ACL_TO_REMOVE", "OID_ACL_TO_REMOVE"]},
{"id": 2, "oids": ["OID_ACL_TO_REMOVE", "OID_ACL_TO_REMOVE"]},
]
)
merged_documents = []
async def mock_merge_documents(self, *args, **kwargs):
for document in kwargs.get("documents"):
merged_documents.append(document)
monkeypatch.setattr(SearchClient, "search", mock_search)
monkeypatch.setattr(SearchClient, "merge_documents", mock_merge_documents)
command = ManageAcl(
service_name="SERVICE",
index_name="INDEX",
+ url="https://test.blob.core.windows.net/content/a.txt",
- document="a.txt",
acl_action="remove_all",
acl_type="oids",
acl="",
credentials=MockAzureCredential(),
)
await command.run()
assert merged_documents == [{"id": 2, "oids": []}, {"id": 1, "oids": []}]
|
tests.test_manageacl/validate_index
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
0124725ad85726aa3f62450e16fb136a63154f69
|
Adds storageURL field to track file location (#1535)
|
<0>:<add> assert len(index.fields) == 3
<del> assert len(index.fields) == 2
<3>:<add> storageurl_field = None
<10>:<add> elif field.name == "storageUrl":
<add> storageurl_field = field
<add>
<add> assert oids_field and groups_field and storageurl_field
<del> assert oids_field and groups_field
<14>:<add> assert storageurl_field.type == SearchFieldDataType.String
<add> assert oids_field.filterable and groups_field.filterable and storageurl_field.filterable
<del> assert oids_field.filterable and groups_field.filterable
|
# module: tests.test_manageacl
def validate_index(index):
<0> assert len(index.fields) == 2
<1> oids_field = None
<2> groups_field = None
<3> for field in index.fields:
<4> if field.name == "oids":
<5> assert not oids_field
<6> oids_field = field
<7> elif field.name == "groups":
<8> assert not groups_field
<9> groups_field = field
<10> assert oids_field and groups_field
<11> assert oids_field.type == SearchFieldDataType.Collection(
<12> SearchFieldDataType.String
<13> ) and groups_field.type == SearchFieldDataType.Collection(SearchFieldDataType.String)
<14> assert oids_field.filterable and groups_field.filterable
<15>
|
===========changed ref 0===========
# module: tests.test_manageacl
@pytest.mark.asyncio
async def test_enable_acls_with_missing_fields(monkeypatch, capsys):
async def mock_get_index(self, *args, **kwargs):
return SearchIndex(name="INDEX", fields=[])
updated_index = []
async def mock_create_or_update_index(self, index, *args, **kwargs):
updated_index.append(index)
monkeypatch.setattr(SearchIndexClient, "get_index", mock_get_index)
monkeypatch.setattr(SearchIndexClient, "create_or_update_index", mock_create_or_update_index)
command = ManageAcl(
service_name="SERVICE",
index_name="INDEX",
+ url="",
- document="",
acl_action="enable_acls",
acl_type="",
acl="",
credentials=MockAzureCredential(),
)
await command.run()
assert len(updated_index) == 1
index = updated_index[0]
validate_index(index)
===========changed ref 1===========
# module: tests.test_manageacl
@pytest.mark.asyncio
async def test_enable_acls_without_missing_fields(monkeypatch, capsys):
async def mock_get_index(self, *args, **kwargs):
return SearchIndex(
name="INDEX",
fields=[
SimpleField(
name="oids",
type=SearchFieldDataType.Collection(SearchFieldDataType.String),
filterable=True,
),
SimpleField(
name="groups",
type=SearchFieldDataType.Collection(SearchFieldDataType.String),
filterable=True,
),
],
)
updated_index = []
async def mock_create_or_update_index(self, index, *args, **kwargs):
updated_index.append(index)
monkeypatch.setattr(SearchIndexClient, "get_index", mock_get_index)
monkeypatch.setattr(SearchIndexClient, "create_or_update_index", mock_create_or_update_index)
command = ManageAcl(
service_name="SERVICE",
index_name="INDEX",
+ url="",
- document="",
acl_action="enable_acls",
acl_type="",
acl="",
credentials=MockAzureCredential(),
)
await command.run()
assert len(updated_index) == 1
index = updated_index[0]
validate_index(index)
===========changed ref 2===========
# module: tests.test_manageacl
@pytest.mark.asyncio
async def test_view_acl(monkeypatch, capsys):
async def mock_search(self, *args, **kwargs):
+ assert kwargs.get("filter") == "storageUrl eq 'https://test.blob.core.windows.net/content/a.txt'"
- assert kwargs.get("filter") == "sourcefile eq 'a.txt'"
assert kwargs.get("select") == ["id", "oids"]
return AsyncSearchResultsIterator([{"oids": ["OID_ACL"]}])
monkeypatch.setattr(SearchClient, "search", mock_search)
command = ManageAcl(
service_name="SERVICE",
index_name="INDEX",
+ url="https://test.blob.core.windows.net/content/a.txt",
- document="a.txt",
acl_action="view",
acl_type="oids",
acl="",
credentials=MockAzureCredential(),
)
await command.run()
captured = capsys.readouterr()
assert captured.out.strip() == '["OID_ACL"]'
===========changed ref 3===========
# module: tests.test_manageacl
+ @pytest.mark.asyncio
+ async def test_update_storage_urls(monkeypatch, caplog):
+ async def mock_search(self, *args, **kwargs):
+ assert kwargs.get("filter") == "storageUrl eq ''"
+ assert kwargs.get("select") == ["id", "storageUrl", "oids", "sourcefile"]
+ return AsyncSearchResultsIterator(
+ [
+ {"id": 1, "oids": ["OID_EXISTS"], "storageUrl": "", "sourcefile": "a.txt"},
+ {"id": 2, "oids": [], "storageUrl": "", "sourcefile": "ab.txt"},
+ ]
+ )
+
+ merged_documents = []
+
+ async def mock_merge_documents(self, *args, **kwargs):
+ for document in kwargs.get("documents"):
+ merged_documents.append(document)
+
+ monkeypatch.setattr(SearchClient, "search", mock_search)
+ monkeypatch.setattr(SearchClient, "merge_documents", mock_merge_documents)
+
+ command = ManageAcl(
+ service_name="SERVICE",
+ index_name="INDEX",
+ url="https://test.blob.core.windows.net/content/",
+ acl_action="update_storage_urls",
+ acl_type="",
+ acl="",
+ credentials=MockAzureCredential(),
+ )
+ with caplog.at_level(logging.INFO):
+ await command.run()
+ assert merged_documents == [{"id": 2, "storageUrl": "https://test.blob.core.windows.net/content/ab.txt"}]
+ assert "Not updating storage URL of document 1 as it has only one oid and may be user uploaded" in caplog.text
+ assert "Adding storage URL https://test.blob.core.windows.net/content/ab.txt for document 2" in caplog.text
+ assert "Updating storage URL for 1 search documents" in caplog.text
+
===========changed ref 4===========
# module: tests.test_manageacl
@pytest.mark.asyncio
async def test_remove_all_acl(monkeypatch, capsys):
async def mock_search(self, *args, **kwargs):
+ assert kwargs.get("filter") == "storageUrl eq 'https://test.blob.core.windows.net/content/a.txt'"
- assert kwargs.get("filter") == "sourcefile eq 'a.txt'"
assert kwargs.get("select") == ["id", "oids"]
return AsyncSearchResultsIterator(
[
{"id": 1, "oids": ["OID_ACL_TO_REMOVE", "OID_ACL_TO_REMOVE"]},
{"id": 2, "oids": ["OID_ACL_TO_REMOVE", "OID_ACL_TO_REMOVE"]},
]
)
merged_documents = []
async def mock_merge_documents(self, *args, **kwargs):
for document in kwargs.get("documents"):
merged_documents.append(document)
monkeypatch.setattr(SearchClient, "search", mock_search)
monkeypatch.setattr(SearchClient, "merge_documents", mock_merge_documents)
command = ManageAcl(
service_name="SERVICE",
index_name="INDEX",
+ url="https://test.blob.core.windows.net/content/a.txt",
- document="a.txt",
acl_action="remove_all",
acl_type="oids",
acl="",
credentials=MockAzureCredential(),
)
await command.run()
assert merged_documents == [{"id": 2, "oids": []}, {"id": 1, "oids": []}]
|
app.backend.prepdocslib.filestrategy/FileStrategy.run
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
0124725ad85726aa3f62450e16fb136a63154f69
|
Adds storageURL field to track file location (#1535)
|
<13>:<add> await search_manager.update_content(sections, blob_image_embeddings, url=file.url)
<del> await search_manager.update_content(sections, blob_image_embeddings)
|
# module: app.backend.prepdocslib.filestrategy
class FileStrategy(Strategy):
def run(self):
<0> search_manager = SearchManager(
<1> self.search_info, self.search_analyzer_name, self.use_acls, False, self.embeddings
<2> )
<3> if self.document_action == DocumentAction.Add:
<4> files = self.list_file_strategy.list()
<5> async for file in files:
<6> try:
<7> sections = await parse_file(file, self.file_processors, self.category, self.image_embeddings)
<8> if sections:
<9> blob_sas_uris = await self.blob_manager.upload_blob(file)
<10> blob_image_embeddings: Optional[List[List[float]]] = None
<11> if self.image_embeddings and blob_sas_uris:
<12> blob_image_embeddings = await self.image_embeddings.create_embeddings(blob_sas_uris)
<13> await search_manager.update_content(sections, blob_image_embeddings)
<14> finally:
<15> if file:
<16> file.close()
<17> elif self.document_action == DocumentAction.Remove:
<18> paths = self.list_file_strategy.list_paths()
<19> async for path in paths:
<20> await self.blob_manager.remove_blob(path)
<21> await search_manager.remove_content(path)
<22> elif self.document_action == DocumentAction.RemoveAll:
<23> await self.blob_manager.remove_blob()
<24> await search_manager.remove_content()
<25>
|
===========unchanged ref 0===========
at: app.backend.prepdocslib.filestrategy
parse_file(file: File, file_processors: dict[str, FileProcessor], category: Optional[str]=None, image_embeddings: Optional[ImageEmbeddings]=None) -> List[Section]
at: app.backend.prepdocslib.filestrategy.FileStrategy.__init__
self.list_file_strategy = list_file_strategy
self.blob_manager = blob_manager
self.file_processors = file_processors
self.document_action = document_action
self.embeddings = embeddings
self.image_embeddings = image_embeddings
self.search_analyzer_name = search_analyzer_name
self.search_info = search_info
self.use_acls = use_acls
self.category = category
at: prepdocslib.blobmanager.BlobManager
upload_blob(file: File) -> Optional[List[str]]
remove_blob(path: Optional[str]=None)
at: prepdocslib.embeddings.ImageEmbeddings
create_embeddings(blob_urls: List[str]) -> List[List[float]]
at: prepdocslib.listfilestrategy.ListFileStrategy
list() -> AsyncGenerator[File, None]
list_paths() -> AsyncGenerator[str, None]
at: typing
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
# module: app.backend.prepdocslib.listfilestrategy
class File:
+ def __init__(self, content: IO, acls: Optional[dict[str, list]] = None, url: Optional[str] = None):
- def __init__(self, content: IO, acls: Optional[dict[str, list]] = None):
self.content = content
self.acls = acls or {}
+ self.url = url
===========changed ref 1===========
# module: scripts.manageacl
class ManageAcl:
def view_acl(self, search_client: SearchClient):
+ for document in await self.get_documents(search_client):
- async for document in await self.get_documents(search_client):
# Assumes the acls are consistent across all sections of the document
print(json.dumps(document[self.acl_type]))
return
===========changed ref 2===========
# module: scripts.manageacl
class ManageAcl:
def get_documents(self, search_client: SearchClient):
+ filter = f"storageUrl eq '{self.url}'"
- filter = f"sourcefile eq '{self.document}'"
+ documents = await search_client.search("", filter=filter, select=["id", self.acl_type])
- result = await search_client.search("", filter=filter, select=["id", self.acl_type])
+ found_documents = []
+ async for document in documents:
+ found_documents.append(document)
+ logger.info("Found %d search documents with storageUrl %s", len(found_documents), self.url)
+ return found_documents
- return result
===========changed ref 3===========
# module: tests.test_searchmanager
@pytest.mark.asyncio
async def test_create_index_doesnt_exist_yet(monkeypatch, search_info):
indexes = []
async def mock_create_index(self, index):
indexes.append(index)
async def mock_list_index_names(self):
for index in []:
yield index
monkeypatch.setattr(SearchIndexClient, "create_index", mock_create_index)
monkeypatch.setattr(SearchIndexClient, "list_index_names", mock_list_index_names)
manager = SearchManager(search_info)
await manager.create_index()
assert len(indexes) == 1, "It should have created one index"
assert indexes[0].name == "test"
+ assert len(indexes[0].fields) == 7
- assert len(indexes[0].fields) == 6
===========changed ref 4===========
# module: tests.test_searchmanager
@pytest.mark.asyncio
async def test_create_index_using_int_vectorization(monkeypatch, search_info):
indexes = []
async def mock_create_index(self, index):
indexes.append(index)
async def mock_list_index_names(self):
for index in []:
yield index
monkeypatch.setattr(SearchIndexClient, "create_index", mock_create_index)
monkeypatch.setattr(SearchIndexClient, "list_index_names", mock_list_index_names)
manager = SearchManager(search_info, use_int_vectorization=True)
await manager.create_index()
assert len(indexes) == 1, "It should have created one index"
assert indexes[0].name == "test"
+ assert len(indexes[0].fields) == 8
- assert len(indexes[0].fields) == 7
===========changed ref 5===========
# module: tests.test_searchmanager
@pytest.mark.asyncio
async def test_create_index_acls(monkeypatch, search_info):
indexes = []
async def mock_create_index(self, index):
indexes.append(index)
async def mock_list_index_names(self):
for index in []:
yield index
monkeypatch.setattr(SearchIndexClient, "create_index", mock_create_index)
monkeypatch.setattr(SearchIndexClient, "list_index_names", mock_list_index_names)
manager = SearchManager(
search_info,
use_acls=True,
)
await manager.create_index()
assert len(indexes) == 1, "It should have created one index"
assert indexes[0].name == "test"
+ assert len(indexes[0].fields) == 9
- assert len(indexes[0].fields) == 8
===========changed ref 6===========
# module: scripts.manageacl
def main(args: Any):
# Use the current user identity to connect to Azure services unless a key is explicitly set for any of them
azd_credential = (
AzureDeveloperCliCredential()
if args.tenant_id is None
else AzureDeveloperCliCredential(tenant_id=args.tenant_id, process_timeout=60)
)
search_credential: Union[AsyncTokenCredential, AzureKeyCredential] = azd_credential
if args.search_key is not None:
search_credential = AzureKeyCredential(args.search_key)
command = ManageAcl(
service_name=args.search_service,
index_name=args.index,
+ url=args.url,
- document=args.document,
acl_action=args.acl_action,
acl_type=args.acl_type,
acl=args.acl,
credentials=search_credential,
)
await command.run()
===========changed ref 7===========
# module: scripts.manageacl
class ManageAcl:
def remove_all_acls(self, search_client: SearchClient):
documents_to_merge = []
+ for document in await self.get_documents(search_client):
- async for document in await self.get_documents(search_client):
+ if len(document[self.acl_type]) > 0:
+ documents_to_merge.append({"id": document["id"], self.acl_type: []})
- documents_to_merge.append({"id": document["id"], self.acl_type: []})
+ else:
+ logger.info("Search document %s already has no %s acls", document["id"], self.acl_type)
if len(documents_to_merge) > 0:
+ logger.info("Removing all %s acls from %d search documents", self.acl_type, len(documents_to_merge))
await search_client.merge_documents(documents=documents_to_merge)
+ else:
+ logger.info("Not updating any search documents")
|
app.backend.prepdocslib.filestrategy/UploadUserFileStrategy.add_file
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
0124725ad85726aa3f62450e16fb136a63154f69
|
Adds storageURL field to track file location (#1535)
|
<4>:<add> await self.search_manager.update_content(sections, url=file.url)
<del> await self.search_manager.update_content(sections)
|
# module: app.backend.prepdocslib.filestrategy
class UploadUserFileStrategy:
def add_file(self, file: File):
<0> if self.image_embeddings:
<1> logging.warning("Image embeddings are not currently supported for the user upload feature")
<2> sections = await parse_file(file, self.file_processors)
<3> if sections:
<4> await self.search_manager.update_content(sections)
<5>
|
===========unchanged ref 0===========
at: app.backend.prepdocslib.filestrategy
parse_file(file: File, file_processors: dict[str, FileProcessor], category: Optional[str]=None, image_embeddings: Optional[ImageEmbeddings]=None) -> List[Section]
at: app.backend.prepdocslib.filestrategy.UploadUserFileStrategy.__init__
self.file_processors = file_processors
self.image_embeddings = image_embeddings
self.search_manager = SearchManager(self.search_info, None, True, False, self.embeddings)
at: logging
warning(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
===========changed ref 0===========
# module: app.backend.prepdocslib.filestrategy
class FileStrategy(Strategy):
def run(self):
search_manager = SearchManager(
self.search_info, self.search_analyzer_name, self.use_acls, False, self.embeddings
)
if self.document_action == DocumentAction.Add:
files = self.list_file_strategy.list()
async for file in files:
try:
sections = await parse_file(file, self.file_processors, self.category, self.image_embeddings)
if sections:
blob_sas_uris = await self.blob_manager.upload_blob(file)
blob_image_embeddings: Optional[List[List[float]]] = None
if self.image_embeddings and blob_sas_uris:
blob_image_embeddings = await self.image_embeddings.create_embeddings(blob_sas_uris)
+ await search_manager.update_content(sections, blob_image_embeddings, url=file.url)
- await search_manager.update_content(sections, blob_image_embeddings)
finally:
if file:
file.close()
elif self.document_action == DocumentAction.Remove:
paths = self.list_file_strategy.list_paths()
async for path in paths:
await self.blob_manager.remove_blob(path)
await search_manager.remove_content(path)
elif self.document_action == DocumentAction.RemoveAll:
await self.blob_manager.remove_blob()
await search_manager.remove_content()
===========changed ref 1===========
# module: app.backend.prepdocslib.listfilestrategy
class File:
+ def __init__(self, content: IO, acls: Optional[dict[str, list]] = None, url: Optional[str] = None):
- def __init__(self, content: IO, acls: Optional[dict[str, list]] = None):
self.content = content
self.acls = acls or {}
+ self.url = url
===========changed ref 2===========
# module: scripts.manageacl
class ManageAcl:
def view_acl(self, search_client: SearchClient):
+ for document in await self.get_documents(search_client):
- async for document in await self.get_documents(search_client):
# Assumes the acls are consistent across all sections of the document
print(json.dumps(document[self.acl_type]))
return
===========changed ref 3===========
# module: scripts.manageacl
class ManageAcl:
def get_documents(self, search_client: SearchClient):
+ filter = f"storageUrl eq '{self.url}'"
- filter = f"sourcefile eq '{self.document}'"
+ documents = await search_client.search("", filter=filter, select=["id", self.acl_type])
- result = await search_client.search("", filter=filter, select=["id", self.acl_type])
+ found_documents = []
+ async for document in documents:
+ found_documents.append(document)
+ logger.info("Found %d search documents with storageUrl %s", len(found_documents), self.url)
+ return found_documents
- return result
===========changed ref 4===========
# module: tests.test_searchmanager
@pytest.mark.asyncio
async def test_create_index_doesnt_exist_yet(monkeypatch, search_info):
indexes = []
async def mock_create_index(self, index):
indexes.append(index)
async def mock_list_index_names(self):
for index in []:
yield index
monkeypatch.setattr(SearchIndexClient, "create_index", mock_create_index)
monkeypatch.setattr(SearchIndexClient, "list_index_names", mock_list_index_names)
manager = SearchManager(search_info)
await manager.create_index()
assert len(indexes) == 1, "It should have created one index"
assert indexes[0].name == "test"
+ assert len(indexes[0].fields) == 7
- assert len(indexes[0].fields) == 6
===========changed ref 5===========
# module: tests.test_searchmanager
@pytest.mark.asyncio
async def test_create_index_using_int_vectorization(monkeypatch, search_info):
indexes = []
async def mock_create_index(self, index):
indexes.append(index)
async def mock_list_index_names(self):
for index in []:
yield index
monkeypatch.setattr(SearchIndexClient, "create_index", mock_create_index)
monkeypatch.setattr(SearchIndexClient, "list_index_names", mock_list_index_names)
manager = SearchManager(search_info, use_int_vectorization=True)
await manager.create_index()
assert len(indexes) == 1, "It should have created one index"
assert indexes[0].name == "test"
+ assert len(indexes[0].fields) == 8
- assert len(indexes[0].fields) == 7
===========changed ref 6===========
# module: tests.test_searchmanager
@pytest.mark.asyncio
async def test_create_index_acls(monkeypatch, search_info):
indexes = []
async def mock_create_index(self, index):
indexes.append(index)
async def mock_list_index_names(self):
for index in []:
yield index
monkeypatch.setattr(SearchIndexClient, "create_index", mock_create_index)
monkeypatch.setattr(SearchIndexClient, "list_index_names", mock_list_index_names)
manager = SearchManager(
search_info,
use_acls=True,
)
await manager.create_index()
assert len(indexes) == 1, "It should have created one index"
assert indexes[0].name == "test"
+ assert len(indexes[0].fields) == 9
- assert len(indexes[0].fields) == 8
===========changed ref 7===========
# module: scripts.manageacl
def main(args: Any):
# Use the current user identity to connect to Azure services unless a key is explicitly set for any of them
azd_credential = (
AzureDeveloperCliCredential()
if args.tenant_id is None
else AzureDeveloperCliCredential(tenant_id=args.tenant_id, process_timeout=60)
)
search_credential: Union[AsyncTokenCredential, AzureKeyCredential] = azd_credential
if args.search_key is not None:
search_credential = AzureKeyCredential(args.search_key)
command = ManageAcl(
service_name=args.search_service,
index_name=args.index,
+ url=args.url,
- document=args.document,
acl_action=args.acl_action,
acl_type=args.acl_type,
acl=args.acl,
credentials=search_credential,
)
await command.run()
|
app.backend.app/upload
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
0124725ad85726aa3f62450e16fb136a63154f69
|
Adds storageURL field to track file location (#1535)
|
<21>:<add> ingester: UploadUserFileStrategy = current_app.config[CONFIG_INGESTER]
<del> ingester = current_app.config[CONFIG_INGESTER]
<22>:<add> await ingester.add_file(File(content=file_io, acls={"oids": [user_oid]}, url=file_client.url))
<del> await ingester.add_file(File(content=file_io, acls={"oids": [user_oid]}))
|
# module: app.backend.app
@bp.post("/upload")
@authenticated
async def upload(auth_claims: dict[str, Any]):
<0> request_files = await request.files
<1> if "file" not in request_files:
<2> # If no files were included in the request, return an error response
<3> return jsonify({"message": "No file part in the request", "status": "failed"}), 400
<4>
<5> user_oid = auth_claims["oid"]
<6> file = request_files.getlist("file")[0]
<7> user_blob_container_client: FileSystemClient = current_app.config[CONFIG_USER_BLOB_CONTAINER_CLIENT]
<8> user_directory_client = user_blob_container_client.get_directory_client(user_oid)
<9> try:
<10> await user_directory_client.get_directory_properties()
<11> except ResourceNotFoundError:
<12> current_app.logger.info("Creating directory for user %s", user_oid)
<13> await user_directory_client.create_directory()
<14> await user_directory_client.set_access_control(owner=user_oid)
<15> file_client = user_directory_client.get_file_client(file.filename)
<16> file_io = file
<17> file_io.name = file.filename
<18> file_io = io.BufferedReader(file_io)
<19> await file_client.upload_data(file_io, overwrite=True, metadata={"UploadedBy": user_oid})
<20> file_io.seek(0)
<21> ingester = current_app.config[CONFIG_INGESTER]
<22> await ingester.add_file(File(content=file_io, acls={"oids": [user_oid]}))
<23> return jsonify({"message": "File uploaded successfully"}), 200
<24>
|
===========unchanged ref 0===========
at: app.backend.app
bp = Blueprint("routes", __name__, static_folder="static")
at: config
CONFIG_USER_BLOB_CONTAINER_CLIENT = "user_blob_container_client"
CONFIG_INGESTER = "ingester"
at: decorators
authenticated(route_fn: Callable[[Dict[str, Any]], Any])
at: io
BufferedReader(raw: RawIOBase, buffer_size: int=...)
at: io.BufferedReader
seek(self, offset: int, whence: int=..., /) -> int
at: prepdocslib.filestrategy
UploadUserFileStrategy(search_info: SearchInfo, file_processors: dict[str, FileProcessor], embeddings: Optional[OpenAIEmbeddings]=None, image_embeddings: Optional[ImageEmbeddings]=None)
at: prepdocslib.filestrategy.UploadUserFileStrategy
add_file(file: File)
at: prepdocslib.listfilestrategy
File(content: IO, acls: Optional[dict[str, list]]=None)
===========changed ref 0===========
# module: app.backend.prepdocslib.listfilestrategy
class File:
+ def __init__(self, content: IO, acls: Optional[dict[str, list]] = None, url: Optional[str] = None):
- def __init__(self, content: IO, acls: Optional[dict[str, list]] = None):
self.content = content
self.acls = acls or {}
+ self.url = url
===========changed ref 1===========
# module: scripts.manageacl
class ManageAcl:
def view_acl(self, search_client: SearchClient):
+ for document in await self.get_documents(search_client):
- async for document in await self.get_documents(search_client):
# Assumes the acls are consistent across all sections of the document
print(json.dumps(document[self.acl_type]))
return
===========changed ref 2===========
# module: app.backend.prepdocslib.filestrategy
class UploadUserFileStrategy:
def add_file(self, file: File):
if self.image_embeddings:
logging.warning("Image embeddings are not currently supported for the user upload feature")
sections = await parse_file(file, self.file_processors)
if sections:
+ await self.search_manager.update_content(sections, url=file.url)
- await self.search_manager.update_content(sections)
===========changed ref 3===========
# module: scripts.manageacl
class ManageAcl:
def get_documents(self, search_client: SearchClient):
+ filter = f"storageUrl eq '{self.url}'"
- filter = f"sourcefile eq '{self.document}'"
+ documents = await search_client.search("", filter=filter, select=["id", self.acl_type])
- result = await search_client.search("", filter=filter, select=["id", self.acl_type])
+ found_documents = []
+ async for document in documents:
+ found_documents.append(document)
+ logger.info("Found %d search documents with storageUrl %s", len(found_documents), self.url)
+ return found_documents
- return result
===========changed ref 4===========
# module: tests.test_searchmanager
@pytest.mark.asyncio
async def test_create_index_doesnt_exist_yet(monkeypatch, search_info):
indexes = []
async def mock_create_index(self, index):
indexes.append(index)
async def mock_list_index_names(self):
for index in []:
yield index
monkeypatch.setattr(SearchIndexClient, "create_index", mock_create_index)
monkeypatch.setattr(SearchIndexClient, "list_index_names", mock_list_index_names)
manager = SearchManager(search_info)
await manager.create_index()
assert len(indexes) == 1, "It should have created one index"
assert indexes[0].name == "test"
+ assert len(indexes[0].fields) == 7
- assert len(indexes[0].fields) == 6
===========changed ref 5===========
# module: tests.test_searchmanager
@pytest.mark.asyncio
async def test_create_index_using_int_vectorization(monkeypatch, search_info):
indexes = []
async def mock_create_index(self, index):
indexes.append(index)
async def mock_list_index_names(self):
for index in []:
yield index
monkeypatch.setattr(SearchIndexClient, "create_index", mock_create_index)
monkeypatch.setattr(SearchIndexClient, "list_index_names", mock_list_index_names)
manager = SearchManager(search_info, use_int_vectorization=True)
await manager.create_index()
assert len(indexes) == 1, "It should have created one index"
assert indexes[0].name == "test"
+ assert len(indexes[0].fields) == 8
- assert len(indexes[0].fields) == 7
===========changed ref 6===========
# module: tests.test_searchmanager
@pytest.mark.asyncio
async def test_create_index_acls(monkeypatch, search_info):
indexes = []
async def mock_create_index(self, index):
indexes.append(index)
async def mock_list_index_names(self):
for index in []:
yield index
monkeypatch.setattr(SearchIndexClient, "create_index", mock_create_index)
monkeypatch.setattr(SearchIndexClient, "list_index_names", mock_list_index_names)
manager = SearchManager(
search_info,
use_acls=True,
)
await manager.create_index()
assert len(indexes) == 1, "It should have created one index"
assert indexes[0].name == "test"
+ assert len(indexes[0].fields) == 9
- assert len(indexes[0].fields) == 8
===========changed ref 7===========
# module: scripts.manageacl
def main(args: Any):
# Use the current user identity to connect to Azure services unless a key is explicitly set for any of them
azd_credential = (
AzureDeveloperCliCredential()
if args.tenant_id is None
else AzureDeveloperCliCredential(tenant_id=args.tenant_id, process_timeout=60)
)
search_credential: Union[AsyncTokenCredential, AzureKeyCredential] = azd_credential
if args.search_key is not None:
search_credential = AzureKeyCredential(args.search_key)
command = ManageAcl(
service_name=args.search_service,
index_name=args.index,
+ url=args.url,
- document=args.document,
acl_action=args.acl_action,
acl_type=args.acl_type,
acl=args.acl,
credentials=search_credential,
)
await command.run()
===========changed ref 8===========
# module: scripts.manageacl
class ManageAcl:
def remove_all_acls(self, search_client: SearchClient):
documents_to_merge = []
+ for document in await self.get_documents(search_client):
- async for document in await self.get_documents(search_client):
+ if len(document[self.acl_type]) > 0:
+ documents_to_merge.append({"id": document["id"], self.acl_type: []})
- documents_to_merge.append({"id": document["id"], self.acl_type: []})
+ else:
+ logger.info("Search document %s already has no %s acls", document["id"], self.acl_type)
if len(documents_to_merge) > 0:
+ logger.info("Removing all %s acls from %d search documents", self.acl_type, len(documents_to_merge))
await search_client.merge_documents(documents=documents_to_merge)
+ else:
+ logger.info("Not updating any search documents")
|
app.backend.prepdocslib.searchmanager/SearchManager.create_index
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
96ec028281da79f40b3b87e776e7447f70d79660
|
Add storageurl field if missing in index (#1556)
|
# module: app.backend.prepdocslib.searchmanager
class SearchManager:
def create_index(self, vectorizers: Optional[List[VectorSearchVectorizer]] = None):
<0> logger.info("Ensuring search index %s exists", self.search_info.index_name)
<1>
<2> async with self.search_info.create_search_index_client() as search_index_client:
<3> fields = [
<4> (
<5> SimpleField(name="id", type="Edm.String", key=True)
<6> if not self.use_int_vectorization
<7> else SearchField(
<8> name="id",
<9> type="Edm.String",
<10> key=True,
<11> sortable=True,
<12> filterable=True,
<13> facetable=True,
<14> analyzer_name="keyword",
<15> )
<16> ),
<17> SearchableField(
<18> name="content",
<19> type="Edm.String",
<20> analyzer_name=self.search_analyzer_name,
<21> ),
<22> SearchField(
<23> name="embedding",
<24> type=SearchFieldDataType.Collection(SearchFieldDataType.Single),
<25> hidden=False,
<26> searchable=True,
<27> filterable=False,
<28> sortable=False,
<29> facetable=False,
<30> vector_search_dimensions=self.embedding_dimensions,
<31> vector_search_profile_name="embedding_config",
<32> ),
<33> SimpleField(name="category", type="Edm.String", filterable=True, facetable=True),
<34> SimpleField(
<35> name="sourcepage",
<36> type="Edm.String",
<37> filterable=True,
<38> facetable=True,
<39> ),
<40> SimpleField(
<41> name="sourcefile",
<42> type="Edm.String",
<43> filterable=True,
<44> facetable=True,
<45> ),
<46> SimpleField(
<47> name="storageUrl",
<48> type="Edm.String",
<49> filterable=True,
<50> facetable</s>
|
===========below chunk 0===========
# module: app.backend.prepdocslib.searchmanager
class SearchManager:
def create_index(self, vectorizers: Optional[List[VectorSearchVectorizer]] = None):
# offset: 1
),
]
if self.use_acls:
fields.append(
SimpleField(
name="oids",
type=SearchFieldDataType.Collection(SearchFieldDataType.String),
filterable=True,
)
)
fields.append(
SimpleField(
name="groups",
type=SearchFieldDataType.Collection(SearchFieldDataType.String),
filterable=True,
)
)
if self.use_int_vectorization:
fields.append(SearchableField(name="parent_id", type="Edm.String", filterable=True))
if self.search_images:
fields.append(
SearchField(
name="imageEmbedding",
type=SearchFieldDataType.Collection(SearchFieldDataType.Single),
hidden=False,
searchable=True,
filterable=False,
sortable=False,
facetable=False,
vector_search_dimensions=1024,
vector_search_profile_name="embedding_config",
),
)
index = SearchIndex(
name=self.search_info.index_name,
fields=fields,
semantic_search=SemanticSearch(
configurations=[
SemanticConfiguration(
name="default",
prioritized_fields=SemanticPrioritizedFields(
title_field=None, content_fields=[SemanticField(field_name="content")]
),
)
]
),
vector_search=VectorSearch(
algorithms=[
HnswAlgorithmConfiguration(
name="hnsw_config",
parameters=HnswParameters(metric="cosine"),
)
],
profiles=[
VectorSearchProfile(
name="embedding_config",
algorithm_configuration_name="hnsw_config",
vectorizer=(
f"{self.search_info.index_name}-</s>
===========below chunk 1===========
# module: app.backend.prepdocslib.searchmanager
class SearchManager:
def create_index(self, vectorizers: Optional[List[VectorSearchVectorizer]] = None):
# offset: 2
<s>_configuration_name="hnsw_config",
vectorizer=(
f"{self.search_info.index_name}-vectorizer" if self.use_int_vectorization else None
),
),
],
vectorizers=vectorizers,
),
)
if self.search_info.index_name not in [name async for name in search_index_client.list_index_names()]:
logger.info("Creating %s search index", self.search_info.index_name)
await search_index_client.create_index(index)
else:
logger.info("Search index %s already exists", self.search_info.index_name)
===========unchanged ref 0===========
at: app.backend.prepdocslib.searchmanager
logger = logging.getLogger("ingester")
at: app.backend.prepdocslib.searchmanager.SearchManager.__init__
self.search_info = search_info
self.search_analyzer_name = search_analyzer_name
self.use_acls = use_acls
self.use_int_vectorization = use_int_vectorization
self.embedding_dimensions = self.embeddings.open_ai_dimensions if self.embeddings else 1536
self.search_images = search_images
at: logging.Logger
info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
at: prepdocslib.strategy.SearchInfo
create_search_index_client() -> SearchIndexClient
at: prepdocslib.strategy.SearchInfo.__init__
self.index_name = index_name
at: typing
List = _alias(list, 1, inst=False, name='List')
|
|
tests.test_searchmanager/test_create_index_does_exist
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
96ec028281da79f40b3b87e776e7447f70d79660
|
Add storageurl field if missing in index (#1556)
|
<0>:<add> created_indexes = []
<del> indexes = []
<1>:<add> updated_indexes = []
<3>:<add> created_indexes.append(index)
<del> indexes.append(index)
<8>:<add> async def mock_get_index(self, *args, **kwargs):
<add> return SearchIndex(
<add> name="test",
<add> fields=[
<add> SimpleField(
<add> name="storageUrl",
<add> type=SearchFieldDataType.String,
<add> filterable=True,
<add> )
<add> ],
<add> )
<add>
<add> async def mock_create_or_update_index(self, index, *args, **kwargs):
<add> updated_indexes.append(index)
<add>
<10>:<add> monkeypatch.setattr(SearchIndexClient, "get_index", mock_get_index)
<add> monkeypatch.setattr(SearchIndexClient, "create_or_update_index", mock_create_or_update_index)
<13>:<add> assert len(created_indexes) == 0, "It should not have created a new index"
<del> assert len(indexes) == 0, "It should not have created a new index"
<14>:<add> assert len(updated
|
# module: tests.test_searchmanager
@pytest.mark.asyncio
async def test_create_index_does_exist(monkeypatch, search_info):
<0> indexes = []
<1>
<2> async def mock_create_index(self, index):
<3> indexes.append(index)
<4>
<5> async def mock_list_index_names(self):
<6> yield "test"
<7>
<8> monkeypatch.setattr(SearchIndexClient, "create_index", mock_create_index)
<9> monkeypatch.setattr(SearchIndexClient, "list_index_names", mock_list_index_names)
<10>
<11> manager = SearchManager(search_info)
<12> await manager.create_index()
<13> assert len(indexes) == 0, "It should not have created a new index"
<14>
|
===========unchanged ref 0===========
at: _pytest.mark.structures
MARK_GEN = MarkGenerator(_ispytest=True)
at: _pytest.monkeypatch
monkeypatch() -> Generator["MonkeyPatch", None, None]
at: tests.test_searchmanager.test_create_index_using_int_vectorization
indexes = []
===========changed ref 0===========
# module: app.backend.prepdocslib.searchmanager
class SearchManager:
def create_index(self, vectorizers: Optional[List[VectorSearchVectorizer]] = None):
logger.info("Ensuring search index %s exists", self.search_info.index_name)
async with self.search_info.create_search_index_client() as search_index_client:
fields = [
(
SimpleField(name="id", type="Edm.String", key=True)
if not self.use_int_vectorization
else SearchField(
name="id",
type="Edm.String",
key=True,
sortable=True,
filterable=True,
facetable=True,
analyzer_name="keyword",
)
),
SearchableField(
name="content",
type="Edm.String",
analyzer_name=self.search_analyzer_name,
),
SearchField(
name="embedding",
type=SearchFieldDataType.Collection(SearchFieldDataType.Single),
hidden=False,
searchable=True,
filterable=False,
sortable=False,
facetable=False,
vector_search_dimensions=self.embedding_dimensions,
vector_search_profile_name="embedding_config",
),
SimpleField(name="category", type="Edm.String", filterable=True, facetable=True),
SimpleField(
name="sourcepage",
type="Edm.String",
filterable=True,
facetable=True,
),
SimpleField(
name="sourcefile",
type="Edm.String",
filterable=True,
facetable=True,
),
SimpleField(
name="storageUrl",
type="Edm.String",
filterable=True,
facetable=False,
),
]
if self.use_acls:
fields.append(
SimpleField(
name="oids",
type=SearchFieldDataType.Collection(SearchFieldDataType.</s>
===========changed ref 1===========
# module: app.backend.prepdocslib.searchmanager
class SearchManager:
def create_index(self, vectorizers: Optional[List[VectorSearchVectorizer]] = None):
# offset: 1
<s> fields.append(
SimpleField(
name="oids",
type=SearchFieldDataType.Collection(SearchFieldDataType.String),
filterable=True,
)
)
fields.append(
SimpleField(
name="groups",
type=SearchFieldDataType.Collection(SearchFieldDataType.String),
filterable=True,
)
)
if self.use_int_vectorization:
fields.append(SearchableField(name="parent_id", type="Edm.String", filterable=True))
if self.search_images:
fields.append(
SearchField(
name="imageEmbedding",
type=SearchFieldDataType.Collection(SearchFieldDataType.Single),
hidden=False,
searchable=True,
filterable=False,
sortable=False,
facetable=False,
vector_search_dimensions=1024,
vector_search_profile_name="embedding_config",
),
)
index = SearchIndex(
name=self.search_info.index_name,
fields=fields,
semantic_search=SemanticSearch(
configurations=[
SemanticConfiguration(
name="default",
prioritized_fields=SemanticPrioritizedFields(
title_field=None, content_fields=[SemanticField(field_name="content")]
),
)
]
),
vector_search=VectorSearch(
algorithms=[
HnswAlgorithmConfiguration(
name="hnsw_config",
parameters=HnswParameters(metric="cosine"),
)
],
profiles=[
VectorSearchProfile(
name="embedding_config",
algorithm_configuration_name="hnsw_config",
vector</s>
===========changed ref 2===========
# module: app.backend.prepdocslib.searchmanager
class SearchManager:
def create_index(self, vectorizers: Optional[List[VectorSearchVectorizer]] = None):
# offset: 2
<s>
f"{self.search_info.index_name}-vectorizer" if self.use_int_vectorization else None
),
),
],
vectorizers=vectorizers,
),
)
if self.search_info.index_name not in [name async for name in search_index_client.list_index_names()]:
logger.info("Creating %s search index", self.search_info.index_name)
await search_index_client.create_index(index)
else:
logger.info("Search index %s already exists", self.search_info.index_name)
+ index_definition = await search_index_client.get_index(self.search_info.index_name)
+ if not any(field.name == "storageUrl" for field in index_definition.fields):
+ logger.info("Adding storageUrl field to index %s", self.search_info.index_name)
+ index_definition.fields.append(
+ SimpleField(
+ name="storageUrl",
+ type="Edm.String",
+ filterable=True,
+ facetable=False,
+ ),
+ )
+ await search_index_client.create_or_update_index(index_definition)
|
tests.test_upload/test_delete_uploaded
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
0c4c55c8a2ef344518f3c55cd1f947a626eef205
|
Escape single quote marks for search filters (#1599)
|
<16>:<add> "sourcepage": "a's doc.txt",
<del> "sourcepage": "a.txt",
<17>:<add> "sourcefile": "a's doc.txt",
<del> "sourcefile": "a.txt",
<27>:<add> "sourcepage": "a's doc.txt",
<del> "sourcepage": "a.txt",
<28>:<add> "sourcefile": "a's doc.txt",
<del> "sourcefile": "a.txt",
|
# module: tests.test_upload
@pytest.mark.asyncio
async def test_delete_uploaded(auth_client, monkeypatch, mock_data_lake_service_client):
<0> async def mock_delete_file(self):
<1> return None
<2>
<3> monkeypatch.setattr(DataLakeFileClient, "delete_file", mock_delete_file)
<4>
<5> def mock_directory_get_file_client(self, *args, **kwargs):
<6> return azure.storage.filedatalake.aio.DataLakeFileClient(
<7> account_url="https://test.blob.core.windows.net/", file_system_name="user-content", file_path=args[0]
<8> )
<9>
<10> monkeypatch.setattr(DataLakeDirectoryClient, "get_file_client", mock_directory_get_file_client)
<11>
<12> class AsyncSearchResultsIterator:
<13> def __init__(self):
<14> self.results = [
<15> {
<16> "sourcepage": "a.txt",
<17> "sourcefile": "a.txt",
<18> "content": "This is a test document.",
<19> "embedding": [],
<20> "category": None,
<21> "id": "file-a_txt-7465737420646F63756D656E742E706466",
<22> "oids": ["OID_X"],
<23> "@search.score": 0.03279569745063782,
<24> "@search.reranker_score": 3.4577205181121826,
<25> },
<26> {
<27> "sourcepage": "a.txt",
<28> "sourcefile": "a.txt",
<29> "content": "This is a test document.",
<30> "embedding": [],
<31> "category": None,
<32> "id": "file-a_txt-7465737420646F63756D656E742E706422",
<33> "oids": [],
<34> "@search.score": 0.0327956974</s>
|
===========below chunk 0===========
# module: tests.test_upload
@pytest.mark.asyncio
async def test_delete_uploaded(auth_client, monkeypatch, mock_data_lake_service_client):
# offset: 1
"@search.reranker_score": 3.4577205181121826,
},
{
"sourcepage": "a.txt",
"sourcefile": "a.txt",
"content": "This is a test document.",
"embedding": [],
"category": None,
"id": "file-a_txt-7465737420646F63756D656E742E706433",
"oids": ["OID_X", "OID_Y"],
"@search.score": 0.03279569745063782,
"@search.reranker_score": 3.4577205181121826,
},
]
def __aiter__(self):
return self
async def __anext__(self):
if len(self.results) == 0:
raise StopAsyncIteration
return self.results.pop()
async def get_count(self):
return len(self.results)
search_results = AsyncSearchResultsIterator()
searched_filters = []
async def mock_search(self, *args, **kwargs):
self.filter = kwargs.get("filter")
searched_filters.append(self.filter)
return search_results
monkeypatch.setattr(SearchClient, "search", mock_search)
deleted_documents = []
async def mock_delete_documents(self, documents):
deleted_documents.extend(documents)
return documents
monkeypatch.setattr(SearchClient, "delete_documents", mock_delete_documents)
response = await auth_client.post(
"/delete_uploaded", headers={"Authorization": "Bearer test"}, json={"filename": "a.txt"}
)
assert response.status_code == 200
assert len(searched_filters) ==</s>
===========below chunk 1===========
# module: tests.test_upload
@pytest.mark.asyncio
async def test_delete_uploaded(auth_client, monkeypatch, mock_data_lake_service_client):
# offset: 2
<s> "a.txt"}
)
assert response.status_code == 200
assert len(searched_filters) == 2, "It should have searched twice (with no results on second try)"
assert searched_filters[0] == "sourcefile eq 'a.txt'"
assert len(deleted_documents) == 1, "It should have only deleted the document solely owned by OID_X"
assert deleted_documents[0]["id"] == "file-a_txt-7465737420646F63756D656E742E706466"
===========unchanged ref 0===========
at: _pytest.mark.structures
MARK_GEN = MarkGenerator(_ispytest=True)
at: typing.Mapping
get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]
get(key: _KT) -> Optional[_VT_co]
|
app.backend.prepdocslib.searchmanager/SearchManager.remove_content
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
0c4c55c8a2ef344518f3c55cd1f947a626eef205
|
Escape single quote marks for search filters (#1599)
|
<5>:<add> filter = None
<add> if path is not None:
<add> # Replace ' with '' to escape the single quote for the filter
<add> # https://learn.microsoft.com/azure/search/query-odata-filter-orderby-syntax#escaping-special-characters-in-string-constants
<add> path_for_filter = os.path.basename(path).replace("'", "''")
<add> filter = f"sourcefile eq '{path_for_filter}'"
<del> filter = None if path is None else f"sourcefile eq '{os.path.basename(path)}'"
|
# module: app.backend.prepdocslib.searchmanager
class SearchManager:
def remove_content(self, path: Optional[str] = None, only_oid: Optional[str] = None):
<0> logger.info(
<1> "Removing sections from '{%s or '<all>'}' from search index '%s'", path, self.search_info.index_name
<2> )
<3> async with self.search_info.create_search_client() as search_client:
<4> while True:
<5> filter = None if path is None else f"sourcefile eq '{os.path.basename(path)}'"
<6> max_results = 1000
<7> result = await search_client.search(
<8> search_text="", filter=filter, top=max_results, include_total_count=True
<9> )
<10> result_count = await result.get_count()
<11> if result_count == 0:
<12> break
<13> documents_to_remove = []
<14> async for document in result:
<15> # If only_oid is set, only remove documents that have only this oid
<16> if not only_oid or document.get("oids") == [only_oid]:
<17> documents_to_remove.append({"id": document["id"]})
<18> if len(documents_to_remove) == 0:
<19> if result_count < max_results:
<20> break
<21> else:
<22> continue
<23> removed_docs = await search_client.delete_documents(documents_to_remove)
<24> logger.info("Removed %d sections from index", len(removed_docs))
<25> # It can take a few seconds for search results to reflect changes, so wait a bit
<26> await asyncio.sleep(2)
<27>
|
===========unchanged ref 0===========
at: app.backend.prepdocslib.searchmanager
logger = logging.getLogger("ingester")
at: app.backend.prepdocslib.searchmanager.SearchManager.__init__
self.search_info = search_info
at: logging.Logger
info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
at: os.path
basename(p: _PathLike[AnyStr]) -> AnyStr
basename(p: AnyStr) -> AnyStr
at: prepdocslib.strategy.SearchInfo
create_search_client() -> SearchClient
at: prepdocslib.strategy.SearchInfo.__init__
self.index_name = index_name
===========changed ref 0===========
# module: tests.test_upload
@pytest.mark.asyncio
async def test_delete_uploaded(auth_client, monkeypatch, mock_data_lake_service_client):
async def mock_delete_file(self):
return None
monkeypatch.setattr(DataLakeFileClient, "delete_file", mock_delete_file)
def mock_directory_get_file_client(self, *args, **kwargs):
return azure.storage.filedatalake.aio.DataLakeFileClient(
account_url="https://test.blob.core.windows.net/", file_system_name="user-content", file_path=args[0]
)
monkeypatch.setattr(DataLakeDirectoryClient, "get_file_client", mock_directory_get_file_client)
class AsyncSearchResultsIterator:
def __init__(self):
self.results = [
{
+ "sourcepage": "a's doc.txt",
- "sourcepage": "a.txt",
+ "sourcefile": "a's doc.txt",
- "sourcefile": "a.txt",
"content": "This is a test document.",
"embedding": [],
"category": None,
"id": "file-a_txt-7465737420646F63756D656E742E706466",
"oids": ["OID_X"],
"@search.score": 0.03279569745063782,
"@search.reranker_score": 3.4577205181121826,
},
{
+ "sourcepage": "a's doc.txt",
- "sourcepage": "a.txt",
+ "sourcefile": "a's doc.txt",
- "sourcefile": "a.txt",
"content": "This is a test document.",
"embedding": [],
"category": None,
"id": "file-a_txt-7465737420646F63756D656E742E70</s>
===========changed ref 1===========
# module: tests.test_upload
@pytest.mark.asyncio
async def test_delete_uploaded(auth_client, monkeypatch, mock_data_lake_service_client):
# offset: 1
<s> "id": "file-a_txt-7465737420646F63756D656E742E706422",
"oids": [],
"@search.score": 0.03279569745063782,
"@search.reranker_score": 3.4577205181121826,
},
{
+ "sourcepage": "a's doc.txt",
- "sourcepage": "a.txt",
+ "sourcefile": "a's doc.txt",
- "sourcefile": "a.txt",
"content": "This is a test document.",
"embedding": [],
"category": None,
"id": "file-a_txt-7465737420646F63756D656E742E706433",
"oids": ["OID_X", "OID_Y"],
"@search.score": 0.03279569745063782,
"@search.reranker_score": 3.4577205181121826,
},
]
def __aiter__(self):
return self
async def __anext__(self):
if len(self.results) == 0:
raise StopAsyncIteration
return self.results.pop()
async def get_count(self):
return len(self.results)
search_results = AsyncSearchResultsIterator()
searched_filters = []
async def mock_search(self, *args, **kwargs):
self.filter = kwargs.get("filter")
searched_filters.append(self.filter)
return search_results
monkeypatch.setattr(SearchClient, "search", mock_search)
</s>
===========changed ref 2===========
# module: tests.test_upload
@pytest.mark.asyncio
async def test_delete_uploaded(auth_client, monkeypatch, mock_data_lake_service_client):
# offset: 2
<s> deleted_documents = []
async def mock_delete_documents(self, documents):
deleted_documents.extend(documents)
return documents
monkeypatch.setattr(SearchClient, "delete_documents", mock_delete_documents)
response = await auth_client.post(
+ "/delete_uploaded", headers={"Authorization": "Bearer test"}, json={"filename": "a's doc.txt"}
- "/delete_uploaded", headers={"Authorization": "Bearer test"}, json={"filename": "a.txt"}
)
assert response.status_code == 200
assert len(searched_filters) == 2, "It should have searched twice (with no results on second try)"
+ assert searched_filters[0] == "sourcefile eq 'a''s doc.txt'"
- assert searched_filters[0] == "sourcefile eq 'a.txt'"
assert len(deleted_documents) == 1, "It should have only deleted the document solely owned by OID_X"
assert deleted_documents[0]["id"] == "file-a_txt-7465737420646F63756D656E742E706466"
|
tests.test_authenticationhelper/test_check_path_auth_allowed_sourcepage
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
0c4c55c8a2ef344518f3c55cd1f947a626eef205
|
Escape single quote marks for search filters (#1599)
|
<12>:<add> path="Benefit_Options-2's complement.pdf",
<del> path="Benefit_Options-2.pdf",
<20>:<add> == "(oids/any(g:search.in(g, 'OID_X')) or groups/any(g:search.in(g, 'GROUP_Y, GROUP_Z'))) and ((sourcefile eq 'Benefit_Options-2''s complement.pdf') or (sourcepage eq 'Benefit_Options-2''s complement.pdf'))"
<del> == "(oids/any(g:search.in(g, 'OID_X')) or groups/any(g:search.in(g, 'GROUP_Y, GROUP_Z'))) and ((sourcefile eq 'Benefit_Options-2.pdf') or (sourcepage eq 'Benefit_Options-2.pdf'))"
|
# module: tests.test_authenticationhelper
@pytest.mark.asyncio
async def test_check_path_auth_allowed_sourcepage(
monkeypatch, mock_confidential_client_success, mock_validate_token_success
):
<0> auth_helper_require_access_control = create_authentication_helper(require_access_control=True)
<1> filter = None
<2>
<3> async def mock_search(self, *args, **kwargs):
<4> nonlocal filter
<5> filter = kwargs.get("filter")
<6> return MockAsyncPageIterator(data=[{"sourcepage": "Benefit_Options-2.pdf"}])
<7>
<8> monkeypatch.setattr(SearchClient, "search", mock_search)
<9>
<10> assert (
<11> await auth_helper_require_access_control.check_path_auth(
<12> path="Benefit_Options-2.pdf",
<13> auth_claims={"oid": "OID_X", "groups": ["GROUP_Y", "GROUP_Z"]},
<14> search_client=create_search_client(),
<15> )
<16> is True
<17> )
<18> assert (
<19> filter
<20> == "(oids/any(g:search.in(g, 'OID_X')) or groups/any(g:search.in(g, 'GROUP_Y, GROUP_Z'))) and ((sourcefile eq 'Benefit_Options-2.pdf') or (sourcepage eq 'Benefit_Options-2.pdf'))"
<21> )
<22>
|
===========unchanged ref 0===========
at: _pytest.mark.structures
MARK_GEN = MarkGenerator(_ispytest=True)
at: _pytest.monkeypatch
monkeypatch() -> Generator["MonkeyPatch", None, None]
at: tests.mocks
MockAsyncPageIterator(data)
at: tests.test_authenticationhelper
create_authentication_helper(require_access_control: bool=False)
create_search_client()
at: typing.Mapping
get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]
get(key: _KT) -> Optional[_VT_co]
===========changed ref 0===========
# module: app.backend.prepdocslib.searchmanager
class SearchManager:
def remove_content(self, path: Optional[str] = None, only_oid: Optional[str] = None):
logger.info(
"Removing sections from '{%s or '<all>'}' from search index '%s'", path, self.search_info.index_name
)
async with self.search_info.create_search_client() as search_client:
while True:
+ filter = None
+ if path is not None:
+ # Replace ' with '' to escape the single quote for the filter
+ # https://learn.microsoft.com/azure/search/query-odata-filter-orderby-syntax#escaping-special-characters-in-string-constants
+ path_for_filter = os.path.basename(path).replace("'", "''")
+ filter = f"sourcefile eq '{path_for_filter}'"
- filter = None if path is None else f"sourcefile eq '{os.path.basename(path)}'"
max_results = 1000
result = await search_client.search(
search_text="", filter=filter, top=max_results, include_total_count=True
)
result_count = await result.get_count()
if result_count == 0:
break
documents_to_remove = []
async for document in result:
# If only_oid is set, only remove documents that have only this oid
if not only_oid or document.get("oids") == [only_oid]:
documents_to_remove.append({"id": document["id"]})
if len(documents_to_remove) == 0:
if result_count < max_results:
break
else:
continue
removed_docs = await search_client.delete_documents(documents_to_remove)
logger.info("Removed %d sections from index", len(removed_docs))
# It can take a few seconds for search results to reflect changes, so wait a bit
await asyncio.sleep(2)
===========changed ref 1===========
# module: tests.test_upload
@pytest.mark.asyncio
async def test_delete_uploaded(auth_client, monkeypatch, mock_data_lake_service_client):
async def mock_delete_file(self):
return None
monkeypatch.setattr(DataLakeFileClient, "delete_file", mock_delete_file)
def mock_directory_get_file_client(self, *args, **kwargs):
return azure.storage.filedatalake.aio.DataLakeFileClient(
account_url="https://test.blob.core.windows.net/", file_system_name="user-content", file_path=args[0]
)
monkeypatch.setattr(DataLakeDirectoryClient, "get_file_client", mock_directory_get_file_client)
class AsyncSearchResultsIterator:
def __init__(self):
self.results = [
{
+ "sourcepage": "a's doc.txt",
- "sourcepage": "a.txt",
+ "sourcefile": "a's doc.txt",
- "sourcefile": "a.txt",
"content": "This is a test document.",
"embedding": [],
"category": None,
"id": "file-a_txt-7465737420646F63756D656E742E706466",
"oids": ["OID_X"],
"@search.score": 0.03279569745063782,
"@search.reranker_score": 3.4577205181121826,
},
{
+ "sourcepage": "a's doc.txt",
- "sourcepage": "a.txt",
+ "sourcefile": "a's doc.txt",
- "sourcefile": "a.txt",
"content": "This is a test document.",
"embedding": [],
"category": None,
"id": "file-a_txt-7465737420646F63756D656E742E70</s>
===========changed ref 2===========
# module: tests.test_upload
@pytest.mark.asyncio
async def test_delete_uploaded(auth_client, monkeypatch, mock_data_lake_service_client):
# offset: 1
<s> "id": "file-a_txt-7465737420646F63756D656E742E706422",
"oids": [],
"@search.score": 0.03279569745063782,
"@search.reranker_score": 3.4577205181121826,
},
{
+ "sourcepage": "a's doc.txt",
- "sourcepage": "a.txt",
+ "sourcefile": "a's doc.txt",
- "sourcefile": "a.txt",
"content": "This is a test document.",
"embedding": [],
"category": None,
"id": "file-a_txt-7465737420646F63756D656E742E706433",
"oids": ["OID_X", "OID_Y"],
"@search.score": 0.03279569745063782,
"@search.reranker_score": 3.4577205181121826,
},
]
def __aiter__(self):
return self
async def __anext__(self):
if len(self.results) == 0:
raise StopAsyncIteration
return self.results.pop()
async def get_count(self):
return len(self.results)
search_results = AsyncSearchResultsIterator()
searched_filters = []
async def mock_search(self, *args, **kwargs):
self.filter = kwargs.get("filter")
searched_filters.append(self.filter)
return search_results
monkeypatch.setattr(SearchClient, "search", mock_search)
</s>
===========changed ref 3===========
# module: tests.test_upload
@pytest.mark.asyncio
async def test_delete_uploaded(auth_client, monkeypatch, mock_data_lake_service_client):
# offset: 2
<s> deleted_documents = []
async def mock_delete_documents(self, documents):
deleted_documents.extend(documents)
return documents
monkeypatch.setattr(SearchClient, "delete_documents", mock_delete_documents)
response = await auth_client.post(
+ "/delete_uploaded", headers={"Authorization": "Bearer test"}, json={"filename": "a's doc.txt"}
- "/delete_uploaded", headers={"Authorization": "Bearer test"}, json={"filename": "a.txt"}
)
assert response.status_code == 200
assert len(searched_filters) == 2, "It should have searched twice (with no results on second try)"
+ assert searched_filters[0] == "sourcefile eq 'a''s doc.txt'"
- assert searched_filters[0] == "sourcefile eq 'a.txt'"
assert len(deleted_documents) == 1, "It should have only deleted the document solely owned by OID_X"
assert deleted_documents[0]["id"] == "file-a_txt-7465737420646F63756D656E742E706466"
|
tests.test_searchmanager/test_remove_content
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
0c4c55c8a2ef344518f3c55cd1f947a626eef205
|
Escape single quote marks for search filters (#1599)
|
<7>:<add> "sourcepage": "foo's bar.pdf#page=1",
<del> "sourcepage": "foo.pdf#page=1",
<8>:<add> "sourcefile": "foo's bar.pdf",
<del> "sourcefile": "foo.pdf",
<32>:<add> await manager.remove_content("foo's bar.pdf")
<del> await manager.remove_content("foo.pdf")
<35>:<add> assert searched_filters[0] == "sourcefile eq 'foo''s bar.pdf'"
<del> assert searched_filters[0] == "sourcefile eq 'foo.pdf'"
|
# module: tests.test_searchmanager
@pytest.mark.asyncio
async def test_remove_content(monkeypatch, search_info):
<0> search_results = AsyncSearchResultsIterator(
<1> [
<2> {
<3> "@search.score": 1,
<4> "id": "file-foo_pdf-666F6F2E706466-page-0",
<5> "content": "test content",
<6> "category": "test",
<7> "sourcepage": "foo.pdf#page=1",
<8> "sourcefile": "foo.pdf",
<9> }
<10> ]
<11> )
<12>
<13> searched_filters = []
<14>
<15> async def mock_search(self, *args, **kwargs):
<16> self.filter = kwargs.get("filter")
<17> searched_filters.append(self.filter)
<18> return search_results
<19>
<20> monkeypatch.setattr(SearchClient, "search", mock_search)
<21>
<22> deleted_documents = []
<23>
<24> async def mock_delete_documents(self, documents):
<25> deleted_documents.extend(documents)
<26> return documents
<27>
<28> monkeypatch.setattr(SearchClient, "delete_documents", mock_delete_documents)
<29>
<30> manager = SearchManager(search_info)
<31>
<32> await manager.remove_content("foo.pdf")
<33>
<34> assert len(searched_filters) == 2, "It should have searched twice (with no results on second try)"
<35> assert searched_filters[0] == "sourcefile eq 'foo.pdf'"
<36> assert len(deleted_documents) == 1, "It should have deleted one document"
<37> assert deleted_documents[0]["id"] == "file-foo_pdf-666F6F2E706466-page-0"
<38>
|
===========unchanged ref 0===========
at: _pytest.mark.structures
MARK_GEN = MarkGenerator(_ispytest=True)
at: _pytest.monkeypatch
monkeypatch() -> Generator["MonkeyPatch", None, None]
at: tests.test_searchmanager
AsyncSearchResultsIterator(results)
at: typing.Mapping
get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]
get(key: _KT) -> Optional[_VT_co]
===========changed ref 0===========
# module: tests.test_authenticationhelper
@pytest.mark.asyncio
async def test_check_path_auth_allowed_sourcepage(
monkeypatch, mock_confidential_client_success, mock_validate_token_success
):
auth_helper_require_access_control = create_authentication_helper(require_access_control=True)
filter = None
async def mock_search(self, *args, **kwargs):
nonlocal filter
filter = kwargs.get("filter")
return MockAsyncPageIterator(data=[{"sourcepage": "Benefit_Options-2.pdf"}])
monkeypatch.setattr(SearchClient, "search", mock_search)
assert (
await auth_helper_require_access_control.check_path_auth(
+ path="Benefit_Options-2's complement.pdf",
- path="Benefit_Options-2.pdf",
auth_claims={"oid": "OID_X", "groups": ["GROUP_Y", "GROUP_Z"]},
search_client=create_search_client(),
)
is True
)
assert (
filter
+ == "(oids/any(g:search.in(g, 'OID_X')) or groups/any(g:search.in(g, 'GROUP_Y, GROUP_Z'))) and ((sourcefile eq 'Benefit_Options-2''s complement.pdf') or (sourcepage eq 'Benefit_Options-2''s complement.pdf'))"
- == "(oids/any(g:search.in(g, 'OID_X')) or groups/any(g:search.in(g, 'GROUP_Y, GROUP_Z'))) and ((sourcefile eq 'Benefit_Options-2.pdf') or (sourcepage eq 'Benefit_Options-2.pdf'))"
)
===========changed ref 1===========
# module: app.backend.prepdocslib.searchmanager
class SearchManager:
def remove_content(self, path: Optional[str] = None, only_oid: Optional[str] = None):
logger.info(
"Removing sections from '{%s or '<all>'}' from search index '%s'", path, self.search_info.index_name
)
async with self.search_info.create_search_client() as search_client:
while True:
+ filter = None
+ if path is not None:
+ # Replace ' with '' to escape the single quote for the filter
+ # https://learn.microsoft.com/azure/search/query-odata-filter-orderby-syntax#escaping-special-characters-in-string-constants
+ path_for_filter = os.path.basename(path).replace("'", "''")
+ filter = f"sourcefile eq '{path_for_filter}'"
- filter = None if path is None else f"sourcefile eq '{os.path.basename(path)}'"
max_results = 1000
result = await search_client.search(
search_text="", filter=filter, top=max_results, include_total_count=True
)
result_count = await result.get_count()
if result_count == 0:
break
documents_to_remove = []
async for document in result:
# If only_oid is set, only remove documents that have only this oid
if not only_oid or document.get("oids") == [only_oid]:
documents_to_remove.append({"id": document["id"]})
if len(documents_to_remove) == 0:
if result_count < max_results:
break
else:
continue
removed_docs = await search_client.delete_documents(documents_to_remove)
logger.info("Removed %d sections from index", len(removed_docs))
# It can take a few seconds for search results to reflect changes, so wait a bit
await asyncio.sleep(2)
===========changed ref 2===========
# module: tests.test_upload
@pytest.mark.asyncio
async def test_delete_uploaded(auth_client, monkeypatch, mock_data_lake_service_client):
async def mock_delete_file(self):
return None
monkeypatch.setattr(DataLakeFileClient, "delete_file", mock_delete_file)
def mock_directory_get_file_client(self, *args, **kwargs):
return azure.storage.filedatalake.aio.DataLakeFileClient(
account_url="https://test.blob.core.windows.net/", file_system_name="user-content", file_path=args[0]
)
monkeypatch.setattr(DataLakeDirectoryClient, "get_file_client", mock_directory_get_file_client)
class AsyncSearchResultsIterator:
def __init__(self):
self.results = [
{
+ "sourcepage": "a's doc.txt",
- "sourcepage": "a.txt",
+ "sourcefile": "a's doc.txt",
- "sourcefile": "a.txt",
"content": "This is a test document.",
"embedding": [],
"category": None,
"id": "file-a_txt-7465737420646F63756D656E742E706466",
"oids": ["OID_X"],
"@search.score": 0.03279569745063782,
"@search.reranker_score": 3.4577205181121826,
},
{
+ "sourcepage": "a's doc.txt",
- "sourcepage": "a.txt",
+ "sourcefile": "a's doc.txt",
- "sourcefile": "a.txt",
"content": "This is a test document.",
"embedding": [],
"category": None,
"id": "file-a_txt-7465737420646F63756D656E742E70</s>
|
app.backend.core.authentication/AuthenticationHelper.check_path_auth
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
0c4c55c8a2ef344518f3c55cd1f947a626eef205
|
Escape single quote marks for search filters (#1599)
|
<13>:<add> # Replace ' with '' to escape the single quote for the filter
<add> # https://learn.microsoft.com/azure/search/query-odata-filter-orderby-syntax#escaping-special-characters-in-string-constants
<add> path_for_filter = path.replace("'", "''")
<add> filter = f"{security_filter} and ((sourcefile eq '{path_for_filter}') or (sourcepage eq '{path_for_filter}'))"
<del> filter = f"{security_filter} and ((sourcefile eq '{path}') or (sourcepage eq '{path}'))"
|
# module: app.backend.core.authentication
class AuthenticationHelper:
def check_path_auth(self, path: str, auth_claims: dict[str, Any], search_client: SearchClient) -> bool:
<0> # Start with the standard security filter for all queries
<1> security_filter = self.build_security_filters(overrides={}, auth_claims=auth_claims)
<2> # If there was no security filter or no path, then the path is allowed
<3> if not security_filter or len(path) == 0:
<4> return True
<5>
<6> # Remove any fragment string from the path before checking
<7> fragment_index = path.find("#")
<8> if fragment_index != -1:
<9> path = path[:fragment_index]
<10>
<11> # Filter down to only chunks that are from the specific source file
<12> # Sourcepage is used for GPT-4V
<13> filter = f"{security_filter} and ((sourcefile eq '{path}') or (sourcepage eq '{path}'))"
<14>
<15> # If the filter returns any results, the user is allowed to access the document
<16> # Otherwise, access is denied
<17> results = await search_client.search(search_text="*", top=1, filter=filter)
<18> allowed = False
<19> async for _ in results:
<20> allowed = True
<21> break
<22>
<23> return allowed
<24>
|
===========unchanged ref 0===========
at: app.backend.core.authentication.AuthenticationHelper
scope: str = "https://graph.microsoft.com/.default"
build_security_filters(overrides: dict[str, Any], auth_claims: dict[str, Any])
===========changed ref 0===========
# module: tests.test_authenticationhelper
@pytest.mark.asyncio
async def test_check_path_auth_allowed_sourcepage(
monkeypatch, mock_confidential_client_success, mock_validate_token_success
):
auth_helper_require_access_control = create_authentication_helper(require_access_control=True)
filter = None
async def mock_search(self, *args, **kwargs):
nonlocal filter
filter = kwargs.get("filter")
return MockAsyncPageIterator(data=[{"sourcepage": "Benefit_Options-2.pdf"}])
monkeypatch.setattr(SearchClient, "search", mock_search)
assert (
await auth_helper_require_access_control.check_path_auth(
+ path="Benefit_Options-2's complement.pdf",
- path="Benefit_Options-2.pdf",
auth_claims={"oid": "OID_X", "groups": ["GROUP_Y", "GROUP_Z"]},
search_client=create_search_client(),
)
is True
)
assert (
filter
+ == "(oids/any(g:search.in(g, 'OID_X')) or groups/any(g:search.in(g, 'GROUP_Y, GROUP_Z'))) and ((sourcefile eq 'Benefit_Options-2''s complement.pdf') or (sourcepage eq 'Benefit_Options-2''s complement.pdf'))"
- == "(oids/any(g:search.in(g, 'OID_X')) or groups/any(g:search.in(g, 'GROUP_Y, GROUP_Z'))) and ((sourcefile eq 'Benefit_Options-2.pdf') or (sourcepage eq 'Benefit_Options-2.pdf'))"
)
===========changed ref 1===========
# module: tests.test_searchmanager
@pytest.mark.asyncio
async def test_remove_content(monkeypatch, search_info):
search_results = AsyncSearchResultsIterator(
[
{
"@search.score": 1,
"id": "file-foo_pdf-666F6F2E706466-page-0",
"content": "test content",
"category": "test",
+ "sourcepage": "foo's bar.pdf#page=1",
- "sourcepage": "foo.pdf#page=1",
+ "sourcefile": "foo's bar.pdf",
- "sourcefile": "foo.pdf",
}
]
)
searched_filters = []
async def mock_search(self, *args, **kwargs):
self.filter = kwargs.get("filter")
searched_filters.append(self.filter)
return search_results
monkeypatch.setattr(SearchClient, "search", mock_search)
deleted_documents = []
async def mock_delete_documents(self, documents):
deleted_documents.extend(documents)
return documents
monkeypatch.setattr(SearchClient, "delete_documents", mock_delete_documents)
manager = SearchManager(search_info)
+ await manager.remove_content("foo's bar.pdf")
- await manager.remove_content("foo.pdf")
assert len(searched_filters) == 2, "It should have searched twice (with no results on second try)"
+ assert searched_filters[0] == "sourcefile eq 'foo''s bar.pdf'"
- assert searched_filters[0] == "sourcefile eq 'foo.pdf'"
assert len(deleted_documents) == 1, "It should have deleted one document"
assert deleted_documents[0]["id"] == "file-foo_pdf-666F6F2E706466-page-0"
===========changed ref 2===========
# module: app.backend.prepdocslib.searchmanager
class SearchManager:
def remove_content(self, path: Optional[str] = None, only_oid: Optional[str] = None):
logger.info(
"Removing sections from '{%s or '<all>'}' from search index '%s'", path, self.search_info.index_name
)
async with self.search_info.create_search_client() as search_client:
while True:
+ filter = None
+ if path is not None:
+ # Replace ' with '' to escape the single quote for the filter
+ # https://learn.microsoft.com/azure/search/query-odata-filter-orderby-syntax#escaping-special-characters-in-string-constants
+ path_for_filter = os.path.basename(path).replace("'", "''")
+ filter = f"sourcefile eq '{path_for_filter}'"
- filter = None if path is None else f"sourcefile eq '{os.path.basename(path)}'"
max_results = 1000
result = await search_client.search(
search_text="", filter=filter, top=max_results, include_total_count=True
)
result_count = await result.get_count()
if result_count == 0:
break
documents_to_remove = []
async for document in result:
# If only_oid is set, only remove documents that have only this oid
if not only_oid or document.get("oids") == [only_oid]:
documents_to_remove.append({"id": document["id"]})
if len(documents_to_remove) == 0:
if result_count < max_results:
break
else:
continue
removed_docs = await search_client.delete_documents(documents_to_remove)
logger.info("Removed %d sections from index", len(removed_docs))
# It can take a few seconds for search results to reflect changes, so wait a bit
await asyncio.sleep(2)
===========changed ref 3===========
# module: tests.test_upload
@pytest.mark.asyncio
async def test_delete_uploaded(auth_client, monkeypatch, mock_data_lake_service_client):
async def mock_delete_file(self):
return None
monkeypatch.setattr(DataLakeFileClient, "delete_file", mock_delete_file)
def mock_directory_get_file_client(self, *args, **kwargs):
return azure.storage.filedatalake.aio.DataLakeFileClient(
account_url="https://test.blob.core.windows.net/", file_system_name="user-content", file_path=args[0]
)
monkeypatch.setattr(DataLakeDirectoryClient, "get_file_client", mock_directory_get_file_client)
class AsyncSearchResultsIterator:
def __init__(self):
self.results = [
{
+ "sourcepage": "a's doc.txt",
- "sourcepage": "a.txt",
+ "sourcefile": "a's doc.txt",
- "sourcefile": "a.txt",
"content": "This is a test document.",
"embedding": [],
"category": None,
"id": "file-a_txt-7465737420646F63756D656E742E706466",
"oids": ["OID_X"],
"@search.score": 0.03279569745063782,
"@search.reranker_score": 3.4577205181121826,
},
{
+ "sourcepage": "a's doc.txt",
- "sourcepage": "a.txt",
+ "sourcefile": "a's doc.txt",
- "sourcefile": "a.txt",
"content": "This is a test document.",
"embedding": [],
"category": None,
"id": "file-a_txt-7465737420646F63756D656E742E70</s>
|
tests.test_authenticationhelper/create_authentication_helper
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
a4d93867e8db929e20aed2004edc82494ce36e3f
|
Allow public documents when authentication is enabled (#1576)
|
<8>:<add> enable_global_documents=enable_global_documents,
<add> enable_unauthenticated_access=enable_unauthenticated_access,
|
# module: tests.test_authenticationhelper
+ def create_authentication_helper(
+ require_access_control: bool = False,
+ enable_global_documents: bool = False,
+ enable_unauthenticated_access: bool = False,
+ ):
- def create_authentication_helper(require_access_control: bool = False):
<0> return AuthenticationHelper(
<1> search_index=MockSearchIndex,
<2> use_authentication=True,
<3> server_app_id="SERVER_APP",
<4> server_app_secret="SERVER_SECRET",
<5> client_app_id="CLIENT_APP",
<6> tenant_id="TENANT_ID",
<7> require_access_control=require_access_control,
<8> )
<9>
| |
tests.test_authenticationhelper/test_build_security_filters
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
a4d93867e8db929e20aed2004edc82494ce36e3f
|
Allow public documents when authentication is enabled (#1576)
|
<2>:<add> auth_helper_enable_global_documents = create_authentication_helper(enable_global_documents=True)
<add> auth_helper_require_access_control_and_enable_global_documents = create_authentication_helper(
<add> require_access_control=True, enable_global_documents=True
<add> )
<add> auth_helper_all_options = create_authentication_helper(
<add> require_access_control=True, enable_global_documents=True, enable_unauthenticated_access=True
<add> )
|
# module: tests.test_authenticationhelper
def test_build_security_filters(mock_confidential_client_success, mock_validate_token_success):
<0> auth_helper = create_authentication_helper()
<1> auth_helper_require_access_control = create_authentication_helper(require_access_control=True)
<2> assert auth_helper.build_security_filters(overrides={}, auth_claims={}) is None
<3> assert (
<4> auth_helper_require_access_control.build_security_filters(overrides={}, auth_claims={})
<5> == "(oids/any(g:search.in(g, '')) or groups/any(g:search.in(g, '')))"
<6> )
<7> assert (
<8> auth_helper.build_security_filters(overrides={"use_oid_security_filter": True}, auth_claims={"oid": "OID_X"})
<9> == "oids/any(g:search.in(g, 'OID_X'))"
<10> )
<11> assert (
<12> auth_helper_require_access_control.build_security_filters(overrides={}, auth_claims={"oid": "OID_X"})
<13> == "(oids/any(g:search.in(g, 'OID_X')) or groups/any(g:search.in(g, '')))"
<14> )
<15> assert (
<16> auth_helper.build_security_filters(
<17> overrides={"use_groups_security_filter": True}, auth_claims={"groups": ["GROUP_Y", "GROUP_Z"]}
<18> )
<19> == "groups/any(g:search.in(g, 'GROUP_Y, GROUP_Z'))"
<20> )
<21> assert (
<22> auth_helper_require_access_control.build_security_filters(
<23> overrides={}, auth_claims={"groups": ["GROUP_Y", "GROUP_Z"]}
<24> )
<25> == "(oids/any(g:search.in(g, '')) or groups/any(g:search.in(g, 'GROUP_Y, GROUP_Z')))"
<26> )
<27> assert (</s>
|
===========below chunk 0===========
# module: tests.test_authenticationhelper
def test_build_security_filters(mock_confidential_client_success, mock_validate_token_success):
# offset: 1
overrides={"use_oid_security_filter": True, "use_groups_security_filter": True},
auth_claims={"oid": "OID_X", "groups": ["GROUP_Y", "GROUP_Z"]},
)
== "(oids/any(g:search.in(g, 'OID_X')) or groups/any(g:search.in(g, 'GROUP_Y, GROUP_Z')))"
)
assert (
auth_helper_require_access_control.build_security_filters(
overrides={},
auth_claims={"oid": "OID_X", "groups": ["GROUP_Y", "GROUP_Z"]},
)
== "(oids/any(g:search.in(g, 'OID_X')) or groups/any(g:search.in(g, 'GROUP_Y, GROUP_Z')))"
)
assert (
auth_helper.build_security_filters(overrides={"use_groups_security_filter": True}, auth_claims={"oid": "OID_X"})
== "groups/any(g:search.in(g, ''))"
)
assert (
auth_helper.build_security_filters(
overrides={"use_oid_security_filter": True}, auth_claims={"groups": ["GROUP_Y", "GROUP_Z"]}
)
== "oids/any(g:search.in(g, ''))"
)
===========changed ref 0===========
# module: tests.test_authenticationhelper
+ def test_auth_setup_required_access_control_and_unauthenticated_access(
+ mock_confidential_client_success, mock_validate_token_success, snapshot
+ ):
+ helper = create_authentication_helper(require_access_control=True, enable_unauthenticated_access=True)
+ result = helper.get_auth_setup_for_client()
+ snapshot.assert_match(json.dumps(result, indent=4), "result.json")
+
===========changed ref 1===========
# module: tests.test_authenticationhelper
+ def create_authentication_helper(
+ require_access_control: bool = False,
+ enable_global_documents: bool = False,
+ enable_unauthenticated_access: bool = False,
+ ):
- def create_authentication_helper(require_access_control: bool = False):
return AuthenticationHelper(
search_index=MockSearchIndex,
use_authentication=True,
server_app_id="SERVER_APP",
server_app_secret="SERVER_SECRET",
client_app_id="CLIENT_APP",
tenant_id="TENANT_ID",
require_access_control=require_access_control,
+ enable_global_documents=enable_global_documents,
+ enable_unauthenticated_access=enable_unauthenticated_access,
)
|
app.backend.core.authentication/AuthenticationHelper.__init__
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
a4d93867e8db929e20aed2004edc82494ce36e3f
|
Allow public documents when authentication is enabled (#1576)
|
<20>:<add> self.enable_global_documents = enable_global_documents
<add> self.enable_unauthenticated_access = enable_unauthenticated_access
|
<s>.authentication
class AuthenticationHelper:
def __init__(
self,
search_index: Optional[SearchIndex],
use_authentication: bool,
server_app_id: Optional[str],
server_app_secret: Optional[str],
client_app_id: Optional[str],
tenant_id: Optional[str],
require_access_control: bool = False,
+ enable_global_documents: bool = False,
+ enable_unauthenticated_access: bool = False,
):
<0> self.use_authentication = use_authentication
<1> self.server_app_id = server_app_id
<2> self.server_app_secret = server_app_secret
<3> self.client_app_id = client_app_id
<4> self.tenant_id = tenant_id
<5> self.authority = f"https://login.microsoftonline.com/{tenant_id}"
<6> # Depending on if requestedAccessTokenVersion is 1 or 2, the issuer and audience of the token may be different
<7> # See https://learn.microsoft.com/graph/api/resources/apiapplication
<8> self.valid_issuers = [
<9> f"https://sts.windows.net/{tenant_id}/",
<10> f"https://login.microsoftonline.com/{tenant_id}/v2.0",
<11> ]
<12> self.valid_audiences = [f"api://{server_app_id}", str(server_app_id)]
<13> # See https://learn.microsoft.com/entra/identity-platform/access-tokens#validate-the-issuer for more information on token validation
<14> self.key_url = f"{self.authority}/discovery/v2.0/keys"
<15>
<16> if self.use_authentication:
<17> field_names = [field.name for field in search_index.fields] if search_index else []
<18> self.has_auth_fields = "oids" in field_names and "groups" in field_names
<19> self.require_access_control = require_access_control
<20> self.confidential_client</s>
|
===========below chunk 0===========
<s>Helper:
def __init__(
self,
search_index: Optional[SearchIndex],
use_authentication: bool,
server_app_id: Optional[str],
server_app_secret: Optional[str],
client_app_id: Optional[str],
tenant_id: Optional[str],
require_access_control: bool = False,
+ enable_global_documents: bool = False,
+ enable_unauthenticated_access: bool = False,
):
# offset: 1
server_app_id, authority=self.authority, client_credential=server_app_secret, token_cache=TokenCache()
)
else:
self.has_auth_fields = False
self.require_access_control = False
===========changed ref 0===========
# module: tests.test_authenticationhelper
+ def test_auth_setup_required_access_control_and_unauthenticated_access(
+ mock_confidential_client_success, mock_validate_token_success, snapshot
+ ):
+ helper = create_authentication_helper(require_access_control=True, enable_unauthenticated_access=True)
+ result = helper.get_auth_setup_for_client()
+ snapshot.assert_match(json.dumps(result, indent=4), "result.json")
+
===========changed ref 1===========
# module: tests.test_authenticationhelper
+ def create_authentication_helper(
+ require_access_control: bool = False,
+ enable_global_documents: bool = False,
+ enable_unauthenticated_access: bool = False,
+ ):
- def create_authentication_helper(require_access_control: bool = False):
return AuthenticationHelper(
search_index=MockSearchIndex,
use_authentication=True,
server_app_id="SERVER_APP",
server_app_secret="SERVER_SECRET",
client_app_id="CLIENT_APP",
tenant_id="TENANT_ID",
require_access_control=require_access_control,
+ enable_global_documents=enable_global_documents,
+ enable_unauthenticated_access=enable_unauthenticated_access,
)
===========changed ref 2===========
# module: tests.test_authenticationhelper
+ @pytest.mark.asyncio
+ async def test_check_path_auth_allowed_public_empty(
+ monkeypatch, mock_confidential_client_success, mock_validate_token_success
+ ):
+ auth_helper_require_access_control_and_enable_global_documents = create_authentication_helper(
+ require_access_control=True, enable_global_documents=True
+ )
+ filter = None
+
+ async def mock_search(self, *args, **kwargs):
+ nonlocal filter
+ filter = kwargs.get("filter")
+ return MockAsyncPageIterator(data=[{"sourcefile": "Benefit_Options.pdf"}])
+
+ monkeypatch.setattr(SearchClient, "search", mock_search)
+
+ assert (
+ await auth_helper_require_access_control_and_enable_global_documents.check_path_auth(
+ path="",
+ auth_claims={"oid": "OID_X", "groups": ["GROUP_Y", "GROUP_Z"]},
+ search_client=create_search_client(),
+ )
+ is True
+ )
+ assert filter is None
+
===========changed ref 3===========
# module: tests.test_authenticationhelper
+ @pytest.mark.asyncio
+ async def test_check_path_auth_allowed_public_without_access_control(
+ monkeypatch, mock_confidential_client_success, mock_validate_token_success
+ ):
+ auth_helper_require_access_control_and_enable_global_documents = create_authentication_helper(
+ require_access_control=False, enable_global_documents=True
+ )
+ filter = None
+ called_search = False
+
+ async def mock_search(self, *args, **kwargs):
+ nonlocal filter
+ nonlocal called_search
+ filter = kwargs.get("filter")
+ called_search = True
+ return MockAsyncPageIterator(data=[])
+
+ monkeypatch.setattr(SearchClient, "search", mock_search)
+
+ assert (
+ await auth_helper_require_access_control_and_enable_global_documents.check_path_auth(
+ path="Benefit_Options-2.pdf",
+ auth_claims={"oid": "OID_X", "groups": ["GROUP_Y", "GROUP_Z"]},
+ search_client=create_search_client(),
+ )
+ is True
+ )
+ assert filter is None
+ assert called_search is False
+
===========changed ref 4===========
# module: tests.conftest
+ auth_public_envs = [
+ {
+ "OPENAI_HOST": "azure",
+ "AZURE_OPENAI_SERVICE": "test-openai-service",
+ "AZURE_OPENAI_CHATGPT_DEPLOYMENT": "test-chatgpt",
+ "AZURE_OPENAI_EMB_DEPLOYMENT": "test-ada",
+ "AZURE_USE_AUTHENTICATION": "true",
+ "AZURE_ENABLE_GLOBAL_DOCUMENT_ACCESS": "true",
+ "AZURE_ENABLE_UNAUTHENTICATED_ACCESS": "true",
+ "AZURE_USER_STORAGE_ACCOUNT": "test-user-storage-account",
+ "AZURE_USER_STORAGE_CONTAINER": "test-user-storage-container",
+ "AZURE_SERVER_APP_ID": "SERVER_APP",
+ "AZURE_SERVER_APP_SECRET": "SECRET",
+ "AZURE_CLIENT_APP_ID": "CLIENT_APP",
+ "AZURE_TENANT_ID": "TENANT_ID",
+ },
+ ]
===========changed ref 5===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_chat_text_filter_public_documents(auth_public_documents_client, snapshot):
+ response = await auth_public_documents_client.post(
+ "/chat",
+ headers={"Authorization": "Bearer MockToken"},
+ json={
+ "messages": [{"content": "What is the capital of France?", "role": "user"}],
+ "context": {
+ "overrides": {
+ "retrieval_mode": "text",
+ "use_oid_security_filter": True,
+ "use_groups_security_filter": True,
+ "exclude_category": "excluded",
+ },
+ },
+ },
+ )
+ assert response.status_code == 200
+ assert (
+ auth_public_documents_client.config[app.CONFIG_SEARCH_CLIENT].filter
+ == "category ne 'excluded' and ((oids/any(g:search.in(g, 'OID_X')) or groups/any(g:search.in(g, 'GROUP_Y, GROUP_Z'))) or (not oids/any() and not groups/any()))"
+ )
+ result = await response.get_json()
+ snapshot.assert_match(json.dumps(result, indent=4), "result.json")
+
|
app.backend.core.authentication/AuthenticationHelper.get_auth_setup_for_client
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
a4d93867e8db929e20aed2004edc82494ce36e3f
|
Allow public documents when authentication is enabled (#1576)
|
<3>:<add> "requireAccessControl": self.require_access_control, # Whether or not access control is required to access documents with access control lists
<del> "requireAccessControl": self.require_access_control, # Whether or not access control is required to use the application
<4>:<add> "enableUnauthenticatedAccess": self.enable_unauthenticated_access, # Whether or not the user can access the app without login
|
# module: app.backend.core.authentication
class AuthenticationHelper:
def get_auth_setup_for_client(self) -> dict[str, Any]:
<0> # returns MSAL.js settings used by the client app
<1> return {
<2> "useLogin": self.use_authentication, # Whether or not login elements are enabled on the UI
<3> "requireAccessControl": self.require_access_control, # Whether or not access control is required to use the application
<4> "msalConfig": {
<5> "auth": {
<6> "clientId": self.client_app_id, # Client app id used for login
<7> "authority": self.authority, # Directory to use for login https://learn.microsoft.com/azure/active-directory/develop/msal-client-application-configuration#authority
<8> "redirectUri": "/redirect", # Points to window.location.origin. You must register this URI on Azure Portal/App Registration.
<9> "postLogoutRedirectUri": "/", # Indicates the page to navigate after logout.
<10> "navigateToLoginRequestUrl": False, # If "true", will navigate back to the original request location before processing the auth code response.
<11> },
<12> "cache": {
<13> # Configures cache location. "sessionStorage" is more secure, but "localStorage" gives you SSO between tabs.
<14> "cacheLocation": "localStorage",
<15> # Set this to "true" if you are having issues on IE11 or Edge
<16> "storeAuthStateInCookie": False,
<17> },
<18> },
<19> "loginRequest": {
<20> # Scopes you add here will be prompted for user consent during sign-in.
<21> # By default, MSAL.js will add OIDC scopes (openid, profile, email) to any login request.
<22> # For more information about OIDC scopes, visit:
<23> # https://docs.microsoft.com/azure/active-directory/develop/v2-permissions-and-consent#openid-connect-scopes
<24> "scopes": [".default"],
<25> # Uncomment the following line to cause a consent dialog to appear on every login
<26> # For</s>
|
===========below chunk 0===========
# module: app.backend.core.authentication
class AuthenticationHelper:
def get_auth_setup_for_client(self) -> dict[str, Any]:
# offset: 1
# "prompt": "consent"
},
"tokenRequest": {
"scopes": [f"api://{self.server_app_id}/access_as_user"],
},
}
===========unchanged ref 0===========
at: app.backend.core.authentication.AuthenticationHelper
scope: str = "https://graph.microsoft.com/.default"
===========changed ref 0===========
<s>.authentication
class AuthenticationHelper:
def __init__(
self,
search_index: Optional[SearchIndex],
use_authentication: bool,
server_app_id: Optional[str],
server_app_secret: Optional[str],
client_app_id: Optional[str],
tenant_id: Optional[str],
require_access_control: bool = False,
+ enable_global_documents: bool = False,
+ enable_unauthenticated_access: bool = False,
):
self.use_authentication = use_authentication
self.server_app_id = server_app_id
self.server_app_secret = server_app_secret
self.client_app_id = client_app_id
self.tenant_id = tenant_id
self.authority = f"https://login.microsoftonline.com/{tenant_id}"
# Depending on if requestedAccessTokenVersion is 1 or 2, the issuer and audience of the token may be different
# See https://learn.microsoft.com/graph/api/resources/apiapplication
self.valid_issuers = [
f"https://sts.windows.net/{tenant_id}/",
f"https://login.microsoftonline.com/{tenant_id}/v2.0",
]
self.valid_audiences = [f"api://{server_app_id}", str(server_app_id)]
# See https://learn.microsoft.com/entra/identity-platform/access-tokens#validate-the-issuer for more information on token validation
self.key_url = f"{self.authority}/discovery/v2.0/keys"
if self.use_authentication:
field_names = [field.name for field in search_index.fields] if search_index else []
self.has_auth_fields = "oids" in field_names and "groups" in field_names
self.require_access_control = require_access_control
+ self.enable_global_documents = enable_global_documents
+ self.enable_unauthenticated_access = enable_</s>
===========changed ref 1===========
<s>Helper:
def __init__(
self,
search_index: Optional[SearchIndex],
use_authentication: bool,
server_app_id: Optional[str],
server_app_secret: Optional[str],
client_app_id: Optional[str],
tenant_id: Optional[str],
require_access_control: bool = False,
+ enable_global_documents: bool = False,
+ enable_unauthenticated_access: bool = False,
):
# offset: 1
<s>
+ self.enable_global_documents = enable_global_documents
+ self.enable_unauthenticated_access = enable_unauthenticated_access
self.confidential_client = ConfidentialClientApplication(
server_app_id, authority=self.authority, client_credential=server_app_secret, token_cache=TokenCache()
)
else:
self.has_auth_fields = False
self.require_access_control = False
+ self.enable_global_documents = True
+ self.enable_unauthenticated_access = True
===========changed ref 2===========
# module: tests.test_authenticationhelper
+ def test_auth_setup_required_access_control_and_unauthenticated_access(
+ mock_confidential_client_success, mock_validate_token_success, snapshot
+ ):
+ helper = create_authentication_helper(require_access_control=True, enable_unauthenticated_access=True)
+ result = helper.get_auth_setup_for_client()
+ snapshot.assert_match(json.dumps(result, indent=4), "result.json")
+
===========changed ref 3===========
# module: tests.test_authenticationhelper
+ def create_authentication_helper(
+ require_access_control: bool = False,
+ enable_global_documents: bool = False,
+ enable_unauthenticated_access: bool = False,
+ ):
- def create_authentication_helper(require_access_control: bool = False):
return AuthenticationHelper(
search_index=MockSearchIndex,
use_authentication=True,
server_app_id="SERVER_APP",
server_app_secret="SERVER_SECRET",
client_app_id="CLIENT_APP",
tenant_id="TENANT_ID",
require_access_control=require_access_control,
+ enable_global_documents=enable_global_documents,
+ enable_unauthenticated_access=enable_unauthenticated_access,
)
===========changed ref 4===========
# module: tests.test_authenticationhelper
+ @pytest.mark.asyncio
+ async def test_check_path_auth_allowed_public_empty(
+ monkeypatch, mock_confidential_client_success, mock_validate_token_success
+ ):
+ auth_helper_require_access_control_and_enable_global_documents = create_authentication_helper(
+ require_access_control=True, enable_global_documents=True
+ )
+ filter = None
+
+ async def mock_search(self, *args, **kwargs):
+ nonlocal filter
+ filter = kwargs.get("filter")
+ return MockAsyncPageIterator(data=[{"sourcefile": "Benefit_Options.pdf"}])
+
+ monkeypatch.setattr(SearchClient, "search", mock_search)
+
+ assert (
+ await auth_helper_require_access_control_and_enable_global_documents.check_path_auth(
+ path="",
+ auth_claims={"oid": "OID_X", "groups": ["GROUP_Y", "GROUP_Z"]},
+ search_client=create_search_client(),
+ )
+ is True
+ )
+ assert filter is None
+
===========changed ref 5===========
# module: tests.test_authenticationhelper
+ @pytest.mark.asyncio
+ async def test_check_path_auth_allowed_public_without_access_control(
+ monkeypatch, mock_confidential_client_success, mock_validate_token_success
+ ):
+ auth_helper_require_access_control_and_enable_global_documents = create_authentication_helper(
+ require_access_control=False, enable_global_documents=True
+ )
+ filter = None
+ called_search = False
+
+ async def mock_search(self, *args, **kwargs):
+ nonlocal filter
+ nonlocal called_search
+ filter = kwargs.get("filter")
+ called_search = True
+ return MockAsyncPageIterator(data=[])
+
+ monkeypatch.setattr(SearchClient, "search", mock_search)
+
+ assert (
+ await auth_helper_require_access_control_and_enable_global_documents.check_path_auth(
+ path="Benefit_Options-2.pdf",
+ auth_claims={"oid": "OID_X", "groups": ["GROUP_Y", "GROUP_Z"]},
+ search_client=create_search_client(),
+ )
+ is True
+ )
+ assert filter is None
+ assert called_search is False
+
|
app.backend.core.authentication/AuthenticationHelper.build_security_filters
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
a4d93867e8db929e20aed2004edc82494ce36e3f
|
Allow public documents when authentication is enabled (#1576)
|
<20>:<add> # If only one security filter is specified, use that filter
<del> # If only one security filter is specified, return that filter
<23>:<add> security_filter = None
<24>:<add> security_filter = f"{oid_security_filter}"
<del> return oid_security_filter
<26>:<add> security_filter = f"{groups_security_filter}"
<del> return groups_security_filter
<28>:<add> security_filter = f"({oid_security_filter} or {groups_security_filter})"
<del> return f"({oid_security_filter} or {groups_security_filter
|
# module: app.backend.core.authentication
class AuthenticationHelper:
def build_security_filters(self, overrides: dict[str, Any], auth_claims: dict[str, Any]):
<0> # Build different permutations of the oid or groups security filter using OData filters
<1> # https://learn.microsoft.com/azure/search/search-security-trimming-for-azure-search
<2> # https://learn.microsoft.com/azure/search/search-query-odata-filter
<3> use_oid_security_filter = self.require_access_control or overrides.get("use_oid_security_filter")
<4> use_groups_security_filter = self.require_access_control or overrides.get("use_groups_security_filter")
<5>
<6> if (use_oid_security_filter or use_groups_security_filter) and not self.has_auth_fields:
<7> raise AuthError(
<8> error="oids and groups must be defined in the search index to use authentication", status_code=400
<9> )
<10>
<11> oid_security_filter = (
<12> "oids/any(g:search.in(g, '{}'))".format(auth_claims.get("oid", "")) if use_oid_security_filter else None
<13> )
<14> groups_security_filter = (
<15> "groups/any(g:search.in(g, '{}'))".format(", ".join(auth_claims.get("groups", [])))
<16> if use_groups_security_filter
<17> else None
<18> )
<19>
<20> # If only one security filter is specified, return that filter
<21> # If both security filters are specified, combine them with "or" so only 1 security filter needs to pass
<22> # If no security filters are specified, don't return any filter
<23> if oid_security_filter and not groups_security_filter:
<24> return oid_security_filter
<25> elif groups_security_filter and not oid_security_filter:
<26> return groups_security_filter
<27> elif oid_security_filter and groups_security_filter:
<28> return f"({oid_security_filter} or {groups_security_filter</s>
|
===========below chunk 0===========
# module: app.backend.core.authentication
class AuthenticationHelper:
def build_security_filters(self, overrides: dict[str, Any], auth_claims: dict[str, Any]):
# offset: 1
else:
return None
===========unchanged ref 0===========
at: app.backend.core.authentication
AuthError(error, status_code)
at: app.backend.core.authentication.AuthenticationHelper.__init__
self.has_auth_fields = "oids" in field_names and "groups" in field_names
self.has_auth_fields = False
self.require_access_control = False
self.require_access_control = require_access_control
at: typing.Mapping
get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]
get(key: _KT) -> Optional[_VT_co]
===========changed ref 0===========
<s>.authentication
class AuthenticationHelper:
def __init__(
self,
search_index: Optional[SearchIndex],
use_authentication: bool,
server_app_id: Optional[str],
server_app_secret: Optional[str],
client_app_id: Optional[str],
tenant_id: Optional[str],
require_access_control: bool = False,
+ enable_global_documents: bool = False,
+ enable_unauthenticated_access: bool = False,
):
self.use_authentication = use_authentication
self.server_app_id = server_app_id
self.server_app_secret = server_app_secret
self.client_app_id = client_app_id
self.tenant_id = tenant_id
self.authority = f"https://login.microsoftonline.com/{tenant_id}"
# Depending on if requestedAccessTokenVersion is 1 or 2, the issuer and audience of the token may be different
# See https://learn.microsoft.com/graph/api/resources/apiapplication
self.valid_issuers = [
f"https://sts.windows.net/{tenant_id}/",
f"https://login.microsoftonline.com/{tenant_id}/v2.0",
]
self.valid_audiences = [f"api://{server_app_id}", str(server_app_id)]
# See https://learn.microsoft.com/entra/identity-platform/access-tokens#validate-the-issuer for more information on token validation
self.key_url = f"{self.authority}/discovery/v2.0/keys"
if self.use_authentication:
field_names = [field.name for field in search_index.fields] if search_index else []
self.has_auth_fields = "oids" in field_names and "groups" in field_names
self.require_access_control = require_access_control
+ self.enable_global_documents = enable_global_documents
+ self.enable_unauthenticated_access = enable_</s>
===========changed ref 1===========
<s>Helper:
def __init__(
self,
search_index: Optional[SearchIndex],
use_authentication: bool,
server_app_id: Optional[str],
server_app_secret: Optional[str],
client_app_id: Optional[str],
tenant_id: Optional[str],
require_access_control: bool = False,
+ enable_global_documents: bool = False,
+ enable_unauthenticated_access: bool = False,
):
# offset: 1
<s>
+ self.enable_global_documents = enable_global_documents
+ self.enable_unauthenticated_access = enable_unauthenticated_access
self.confidential_client = ConfidentialClientApplication(
server_app_id, authority=self.authority, client_credential=server_app_secret, token_cache=TokenCache()
)
else:
self.has_auth_fields = False
self.require_access_control = False
+ self.enable_global_documents = True
+ self.enable_unauthenticated_access = True
===========changed ref 2===========
# module: app.backend.core.authentication
class AuthenticationHelper:
def get_auth_setup_for_client(self) -> dict[str, Any]:
# returns MSAL.js settings used by the client app
return {
"useLogin": self.use_authentication, # Whether or not login elements are enabled on the UI
+ "requireAccessControl": self.require_access_control, # Whether or not access control is required to access documents with access control lists
- "requireAccessControl": self.require_access_control, # Whether or not access control is required to use the application
+ "enableUnauthenticatedAccess": self.enable_unauthenticated_access, # Whether or not the user can access the app without login
"msalConfig": {
"auth": {
"clientId": self.client_app_id, # Client app id used for login
"authority": self.authority, # Directory to use for login https://learn.microsoft.com/azure/active-directory/develop/msal-client-application-configuration#authority
"redirectUri": "/redirect", # Points to window.location.origin. You must register this URI on Azure Portal/App Registration.
"postLogoutRedirectUri": "/", # Indicates the page to navigate after logout.
"navigateToLoginRequestUrl": False, # If "true", will navigate back to the original request location before processing the auth code response.
},
"cache": {
# Configures cache location. "sessionStorage" is more secure, but "localStorage" gives you SSO between tabs.
"cacheLocation": "localStorage",
# Set this to "true" if you are having issues on IE11 or Edge
"storeAuthStateInCookie": False,
},
},
"loginRequest": {
# Scopes you add here will be prompted for user consent during sign-in.
# By default, MSAL.js will add OIDC scopes (openid, profile, email) to any login request.
# For more information about OIDC scopes, visit:
# https://docs.microsoft.com/azure/active-directory/develop/v2-permissions-and-consent#openid</s>
===========changed ref 3===========
# module: app.backend.core.authentication
class AuthenticationHelper:
def get_auth_setup_for_client(self) -> dict[str, Any]:
# offset: 1
<s> # https://docs.microsoft.com/azure/active-directory/develop/v2-permissions-and-consent#openid-connect-scopes
"scopes": [".default"],
# Uncomment the following line to cause a consent dialog to appear on every login
# For more information, please visit https://learn.microsoft.com/azure/active-directory/develop/v2-oauth2-auth-code-flow#request-an-authorization-code
# "prompt": "consent"
},
"tokenRequest": {
"scopes": [f"api://{self.server_app_id}/access_as_user"],
},
}
===========changed ref 4===========
# module: tests.test_authenticationhelper
+ def test_auth_setup_required_access_control_and_unauthenticated_access(
+ mock_confidential_client_success, mock_validate_token_success, snapshot
+ ):
+ helper = create_authentication_helper(require_access_control=True, enable_unauthenticated_access=True)
+ result = helper.get_auth_setup_for_client()
+ snapshot.assert_match(json.dumps(result, indent=4), "result.json")
+
|
app.backend.core.authentication/AuthenticationHelper.get_auth_claims_if_enabled
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
a4d93867e8db929e20aed2004edc82494ce36e3f
|
Allow public documents when authentication is enabled (#1576)
|
# module: app.backend.core.authentication
class AuthenticationHelper:
def get_auth_claims_if_enabled(self, headers: dict) -> dict[str, Any]:
<0> if not self.use_authentication:
<1> return {}
<2> try:
<3> # Read the authentication token from the authorization header and exchange it using the On Behalf Of Flow
<4> # The scope is set to the Microsoft Graph API, which may need to be called for more authorization information
<5> # https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow
<6> auth_token = AuthenticationHelper.get_token_auth_header(headers)
<7> # Validate the token before use
<8> await self.validate_access_token(auth_token)
<9>
<10> # Use the on-behalf-of-flow to acquire another token for use with Microsoft Graph
<11> # See https://learn.microsoft.com/entra/identity-platform/v2-oauth2-on-behalf-of-flow for more information
<12> graph_resource_access_token = self.confidential_client.acquire_token_on_behalf_of(
<13> user_assertion=auth_token, scopes=["https://graph.microsoft.com/.default"]
<14> )
<15> if "error" in graph_resource_access_token:
<16> raise AuthError(error=str(graph_resource_access_token), status_code=401)
<17>
<18> # Read the claims from the response. The oid and groups claims are used for security filtering
<19> # https://learn.microsoft.com/azure/active-directory/develop/id-token-claims-reference
<20> id_token_claims = graph_resource_access_token["id_token_claims"]
<21> auth_claims = {"oid": id_token_claims["oid"], "groups": id_token_claims.get("groups", [])}
<22>
<23> # A groups claim may have been omitted either because it was not added in the application manifest for the API application,
<24> # or a groups overage claim may have been emitted.
<25> # https://learn</s>
|
===========below chunk 0===========
# module: app.backend.core.authentication
class AuthenticationHelper:
def get_auth_claims_if_enabled(self, headers: dict) -> dict[str, Any]:
# offset: 1
missing_groups_claim = "groups" not in id_token_claims
has_group_overage_claim = (
missing_groups_claim
and "_claim_names" in id_token_claims
and "groups" in id_token_claims["_claim_names"]
)
if missing_groups_claim or has_group_overage_claim:
# Read the user's groups from Microsoft Graph
auth_claims["groups"] = await AuthenticationHelper.list_groups(graph_resource_access_token)
return auth_claims
except AuthError as e:
logging.exception("Exception getting authorization information - " + json.dumps(e.error))
if self.require_access_control:
raise
return {}
except Exception:
logging.exception("Exception getting authorization information")
if self.require_access_control:
raise
return {}
===========unchanged ref 0===========
at: app.backend.core.authentication
AuthError(error, status_code)
AuthenticationHelper(search_index: Optional[SearchIndex], use_authentication: bool, server_app_id: Optional[str], server_app_secret: Optional[str], client_app_id: Optional[str], tenant_id: Optional[str], require_access_control: bool=False)
at: app.backend.core.authentication.AuthenticationHelper
get_token_auth_header(headers: dict) -> str
at: json
dumps(obj: Any, *, skipkeys: bool=..., ensure_ascii: bool=..., check_circular: bool=..., allow_nan: bool=..., cls: Optional[Type[JSONEncoder]]=..., indent: Union[None, int, str]=..., separators: Optional[Tuple[str, str]]=..., default: Optional[Callable[[Any], Any]]=..., sort_keys: bool=..., **kwds: Any) -> str
===========changed ref 0===========
# module: app.backend.core.authentication
class AuthenticationHelper:
def build_security_filters(self, overrides: dict[str, Any], auth_claims: dict[str, Any]):
# Build different permutations of the oid or groups security filter using OData filters
# https://learn.microsoft.com/azure/search/search-security-trimming-for-azure-search
# https://learn.microsoft.com/azure/search/search-query-odata-filter
use_oid_security_filter = self.require_access_control or overrides.get("use_oid_security_filter")
use_groups_security_filter = self.require_access_control or overrides.get("use_groups_security_filter")
if (use_oid_security_filter or use_groups_security_filter) and not self.has_auth_fields:
raise AuthError(
error="oids and groups must be defined in the search index to use authentication", status_code=400
)
oid_security_filter = (
"oids/any(g:search.in(g, '{}'))".format(auth_claims.get("oid", "")) if use_oid_security_filter else None
)
groups_security_filter = (
"groups/any(g:search.in(g, '{}'))".format(", ".join(auth_claims.get("groups", [])))
if use_groups_security_filter
else None
)
+ # If only one security filter is specified, use that filter
- # If only one security filter is specified, return that filter
# If both security filters are specified, combine them with "or" so only 1 security filter needs to pass
# If no security filters are specified, don't return any filter
+ security_filter = None
if oid_security_filter and not groups_security_filter:
+ security_filter = f"{oid_security_filter}"
- return oid_security_filter
elif groups_security_filter and not oid_security_filter:
+ security_filter = f"{groups_security_filter}"
- return groups_security_filter
elif oid_security_</s>
===========changed ref 1===========
# module: app.backend.core.authentication
class AuthenticationHelper:
def build_security_filters(self, overrides: dict[str, Any], auth_claims: dict[str, Any]):
# offset: 1
<s> <add> security_filter = f"{groups_security_filter}"
- return groups_security_filter
elif oid_security_filter and groups_security_filter:
+ security_filter = f"({oid_security_filter} or {groups_security_filter})"
- return f"({oid_security_filter} or {groups_security_filter})"
- else:
- return None
===========changed ref 2===========
<s>.authentication
class AuthenticationHelper:
def __init__(
self,
search_index: Optional[SearchIndex],
use_authentication: bool,
server_app_id: Optional[str],
server_app_secret: Optional[str],
client_app_id: Optional[str],
tenant_id: Optional[str],
require_access_control: bool = False,
+ enable_global_documents: bool = False,
+ enable_unauthenticated_access: bool = False,
):
self.use_authentication = use_authentication
self.server_app_id = server_app_id
self.server_app_secret = server_app_secret
self.client_app_id = client_app_id
self.tenant_id = tenant_id
self.authority = f"https://login.microsoftonline.com/{tenant_id}"
# Depending on if requestedAccessTokenVersion is 1 or 2, the issuer and audience of the token may be different
# See https://learn.microsoft.com/graph/api/resources/apiapplication
self.valid_issuers = [
f"https://sts.windows.net/{tenant_id}/",
f"https://login.microsoftonline.com/{tenant_id}/v2.0",
]
self.valid_audiences = [f"api://{server_app_id}", str(server_app_id)]
# See https://learn.microsoft.com/entra/identity-platform/access-tokens#validate-the-issuer for more information on token validation
self.key_url = f"{self.authority}/discovery/v2.0/keys"
if self.use_authentication:
field_names = [field.name for field in search_index.fields] if search_index else []
self.has_auth_fields = "oids" in field_names and "groups" in field_names
self.require_access_control = require_access_control
+ self.enable_global_documents = enable_global_documents
+ self.enable_unauthenticated_access = enable_</s>
===========changed ref 3===========
<s>Helper:
def __init__(
self,
search_index: Optional[SearchIndex],
use_authentication: bool,
server_app_id: Optional[str],
server_app_secret: Optional[str],
client_app_id: Optional[str],
tenant_id: Optional[str],
require_access_control: bool = False,
+ enable_global_documents: bool = False,
+ enable_unauthenticated_access: bool = False,
):
# offset: 1
<s>
+ self.enable_global_documents = enable_global_documents
+ self.enable_unauthenticated_access = enable_unauthenticated_access
self.confidential_client = ConfidentialClientApplication(
server_app_id, authority=self.authority, client_credential=server_app_secret, token_cache=TokenCache()
)
else:
self.has_auth_fields = False
self.require_access_control = False
+ self.enable_global_documents = True
+ self.enable_unauthenticated_access = True
|
|
app.backend.prepdocs/setup_search_info
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
a74df4ee406a01e7ae67fd71fd9a13f416b73103
|
Removing unneeded key for free search service (#1620)
|
<0>:<del> if key_vault_name and search_secret_name:
<1>:<del> async with SecretClient(
<2>:<del> vault_url=f"https://{key_vault_name}.vault.azure.net", credential=azure_credential
<3>:<del> ) as key_vault_client:
<4>:<del> search_key = (await key_vault_client.get_secret(search_secret_name)).value # type: ignore[attr-defined]
<5>:<del>
|
<s>search_info(
- search_service: str,
- index_name: str,
- azure_credential: AsyncTokenCredential,
- search_key: Union[str, None] = None,
- key_vault_name: Union[str, None] = None,
- search_secret_name: Union[str, None] = None,
+ search_service: str, index_name: str, azure_credential: AsyncTokenCredential, search_key: Union[str, None] = None
) -> SearchInfo:
<0> if key_vault_name and search_secret_name:
<1> async with SecretClient(
<2> vault_url=f"https://{key_vault_name}.vault.azure.net", credential=azure_credential
<3> ) as key_vault_client:
<4> search_key = (await key_vault_client.get_secret(search_secret_name)).value # type: ignore[attr-defined]
<5>
<6> search_creds: Union[AsyncTokenCredential, AzureKeyCredential] = (
<7> azure_credential if search_key is None else AzureKeyCredential(search_key)
<8> )
<9>
<10> return SearchInfo(
<11> endpoint=f"https://{search_service}.search.windows.net/",
<12> credential=search_creds,
<13> index_name=index_name,
<14> )
<15>
|
===========unchanged ref 0===========
at: prepdocslib.strategy
SearchInfo(endpoint: str, credential: Union[AsyncTokenCredential, AzureKeyCredential], index_name: str)
===========changed ref 0===========
# module: tests.mocks
- class MockKeyVaultSecret:
- def __init__(self, value):
- self.value = value
-
===========changed ref 1===========
# module: tests.mocks
- class MockKeyVaultSecretClient:
- def get_secret(self, secret_name):
- return MockKeyVaultSecret("mysecret")
-
===========changed ref 2===========
# module: tests.test_app_config
- @pytest.mark.asyncio
- async def test_app_searchkey_notfound(monkeypatch, minimal_env):
- monkeypatch.setenv("AZURE_KEY_VAULT_NAME", "my_key_vault")
- monkeypatch.setenv("VISION_SECRET_NAME", "vision-secret-name")
- monkeypatch.setenv("AZURE_SEARCH_SECRET_NAME", "")
-
- async def get_secret(*args, **kwargs):
- if args[1] == "search-secret-name":
- raise Exception("Key not found")
- return MockKeyVaultSecret("mysecret")
-
- monkeypatch.setattr(SecretClient, "get_secret", get_secret)
-
- quart_app = app.create_app()
- async with quart_app.test_app() as test_app:
- test_app.test_client()
-
===========changed ref 3===========
# module: tests.test_app_config
- @pytest.mark.asyncio
- async def test_app_visionkey_notfound(monkeypatch, minimal_env):
- monkeypatch.setenv("AZURE_KEY_VAULT_NAME", "my_key_vault")
- monkeypatch.setenv("VISION_SECRET_NAME", "")
- monkeypatch.setenv("AZURE_SEARCH_SECRET_NAME", "search-secret-name")
-
- async def get_secret(*args, **kwargs):
- if args[1] == "vision-secret-name":
- raise Exception("Key not found")
- return MockKeyVaultSecret("mysecret")
-
- monkeypatch.setattr(SecretClient, "get_secret", get_secret)
-
- quart_app = app.create_app()
- async with quart_app.test_app() as test_app:
- test_app.test_client()
-
|
app.backend.approaches.retrievethenreadvision/RetrieveThenReadVisionApproach.__init__
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
77303da5516341bbdc78572c0ad83628b0ee5889
|
Improve token counting for messages with package (#1577)
|
<15>:<add> self.gpt4v_token_limit = get_token_limit(gpt4v_model)
|
<s> Optional[str],
gpt4v_model: str,
embedding_deployment: Optional[str], # Not needed for non-Azure OpenAI or for retrieval_mode="text"
embedding_model: str,
embedding_dimensions: int,
sourcepage_field: str,
content_field: str,
query_language: str,
query_speller: str,
vision_endpoint: str,
vision_token_provider: Callable[[], Awaitable[str]]
):
<0> self.search_client = search_client
<1> self.blob_container_client = blob_container_client
<2> self.openai_client = openai_client
<3> self.auth_helper = auth_helper
<4> self.embedding_model = embedding_model
<5> self.embedding_deployment = embedding_deployment
<6> self.embedding_dimensions = embedding_dimensions
<7> self.sourcepage_field = sourcepage_field
<8> self.content_field = content_field
<9> self.gpt4v_deployment = gpt4v_deployment
<10> self.gpt4v_model = gpt4v_model
<11> self.query_language = query_language
<12> self.query_speller = query_speller
<13> self.vision_endpoint = vision_endpoint
<14> self.vision_token_provider = vision_token_provider
<15>
|
===========unchanged ref 0===========
at: approaches.approach.Approach
__init__(self, search_client: SearchClient, openai_client: AsyncOpenAI, auth_helper: AuthenticationHelper, query_language: Optional[str], query_speller: Optional[str], embedding_deployment: Optional[str], embedding_model: str, embedding_dimensions: int, openai_host: str, vision_endpoint: str, vision_token_provider: Callable[[], Awaitable[str]])
at: core.authentication
AuthenticationHelper(search_index: Optional[SearchIndex], use_authentication: bool, server_app_id: Optional[str], server_app_secret: Optional[str], client_app_id: Optional[str], tenant_id: Optional[str], require_access_control: bool=False, enable_global_documents: bool=False, enable_unauthenticated_access: bool=False)
at: typing
Awaitable = _alias(collections.abc.Awaitable, 1)
Callable = _CallableType(collections.abc.Callable, 2)
|
app.backend.approaches.retrievethenreadvision/RetrieveThenReadVisionApproach.run
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
77303da5516341bbdc78572c0ad83628b0ee5889
|
Improve token counting for messages with package (#1577)
|
<1>:<add> if not isinstance(q, str):
<add> raise ValueError("The most recent message content must be a string.")
<add>
|
# module: app.backend.approaches.retrievethenreadvision
class RetrieveThenReadVisionApproach(Approach):
def run(
self,
+ messages: list[ChatCompletionMessageParam],
- messages: list[dict],
stream: bool = False, # Stream is not used in this approach
session_state: Any = None,
context: dict[str, Any] = {},
) -> Union[dict[str, Any], AsyncGenerator[dict[str, Any], None]]:
<0> q = messages[-1]["content"]
<1> overrides = context.get("overrides", {})
<2> auth_claims = context.get("auth_claims", {})
<3> has_text = overrides.get("retrieval_mode") in ["text", "hybrid", None]
<4> has_vector = overrides.get("retrieval_mode") in ["vectors", "hybrid", None]
<5> vector_fields = overrides.get("vector_fields", ["embedding"])
<6>
<7> include_gtpV_text = overrides.get("gpt4v_input") in ["textAndImages", "texts", None]
<8> include_gtpV_images = overrides.get("gpt4v_input") in ["textAndImages", "images", None]
<9>
<10> use_semantic_captions = True if overrides.get("semantic_captions") and has_text else False
<11> top = overrides.get("top", 3)
<12> minimum_search_score = overrides.get("minimum_search_score", 0.0)
<13> minimum_reranker_score = overrides.get("minimum_reranker_score", 0.0)
<14> filter = self.build_filter(overrides, auth_claims)
<15> use_semantic_ranker = overrides.get("semantic_ranker") and has_text
<16>
<17> # If retrieval mode includes vectors, compute an embedding for the query
<18>
<19> vectors = []
<20> if has_vector:
<21> for field in vector_fields:
<22> vector = (
<23> await self.compute_text_embedding(q)
<24> if field ==</s>
|
===========below chunk 0===========
# module: app.backend.approaches.retrievethenreadvision
class RetrieveThenReadVisionApproach(Approach):
def run(
self,
+ messages: list[ChatCompletionMessageParam],
- messages: list[dict],
stream: bool = False, # Stream is not used in this approach
session_state: Any = None,
context: dict[str, Any] = {},
) -> Union[dict[str, Any], AsyncGenerator[dict[str, Any], None]]:
# offset: 1
else await self.compute_image_embedding(q)
)
vectors.append(vector)
# Only keep the text query if the retrieval mode uses text, otherwise drop it
query_text = q if has_text else None
results = await self.search(
top,
query_text,
filter,
vectors,
use_semantic_ranker,
use_semantic_captions,
minimum_search_score,
minimum_reranker_score,
)
image_list: list[ChatCompletionContentPartImageParam] = []
user_content: list[ChatCompletionContentPartParam] = [{"text": q, "type": "text"}]
template = overrides.get("prompt_template", self.system_chat_template_gpt4v)
model = self.gpt4v_model
message_builder = MessageBuilder(template, model)
# Process results
sources_content = self.get_sources_content(results, use_semantic_captions, use_image_citation=True)
if include_gtpV_text:
content = "\n".join(sources_content)
user_content.append({"text": content, "type": "text"})
if include_gtpV_images:
for result in results:
url = await fetch_image(self.blob_container_client, result)
if url:
image_list.append({"image_url": url, "type": "image_url"})
user_content.extend(image</s>
===========below chunk 1===========
# module: app.backend.approaches.retrievethenreadvision
class RetrieveThenReadVisionApproach(Approach):
def run(
self,
+ messages: list[ChatCompletionMessageParam],
- messages: list[dict],
stream: bool = False, # Stream is not used in this approach
session_state: Any = None,
context: dict[str, Any] = {},
) -> Union[dict[str, Any], AsyncGenerator[dict[str, Any], None]]:
# offset: 2
<s>_list.append({"image_url": url, "type": "image_url"})
user_content.extend(image_list)
# Append user message
message_builder.insert_message("user", user_content)
updated_messages = message_builder.messages
chat_completion = (
await self.openai_client.chat.completions.create(
model=self.gpt4v_deployment if self.gpt4v_deployment else self.gpt4v_model,
messages=updated_messages,
temperature=overrides.get("temperature", 0.3),
max_tokens=1024,
n=1,
)
).model_dump()
data_points = {
"text": sources_content,
"images": [d["image_url"] for d in image_list],
}
extra_info = {
"data_points": data_points,
"thoughts": [
ThoughtStep(
"Search using user query",
query_text,
{
"use_semantic_captions": use_semantic_captions,
"use_semantic_ranker": use_semantic_ranker,
"top": top,
"filter": filter,
"vector_fields": vector_fields,
},
),
ThoughtStep(
"Search results",
[result.serialize</s>
===========below chunk 2===========
# module: app.backend.approaches.retrievethenreadvision
class RetrieveThenReadVisionApproach(Approach):
def run(
self,
+ messages: list[ChatCompletionMessageParam],
- messages: list[dict],
stream: bool = False, # Stream is not used in this approach
session_state: Any = None,
context: dict[str, Any] = {},
) -> Union[dict[str, Any], AsyncGenerator[dict[str, Any], None]]:
# offset: 3
<s>_results() for result in results],
),
ThoughtStep(
"Prompt to generate answer",
[str(message) for message in updated_messages],
(
{"model": self.gpt4v_model, "deployment": self.gpt4v_deployment}
if self.gpt4v_deployment
else {"model": self.gpt4v_model}
),
),
],
}
chat_completion["choices"][0]["context"] = extra_info
chat_completion["choices"][0]["session_state"] = session_state
return chat_completion
===========unchanged ref 0===========
at: app.backend.approaches.retrievethenreadvision.RetrieveThenReadVisionApproach
system_chat_template_gpt4v = (
"You are an intelligent assistant helping analyze the Annual Financial Report of Contoso Ltd., The documents contain text, graphs, tables and images. "
+ "Each image source has the file name in the top left corner of the image with coordinates (10,10) pixels and is in the format SourceFileName:<file_name> "
+ "Each text source starts in a new line and has the file name followed by colon and the actual information "
+ "Always include the source name from the image or text for each fact you use in the response in the format: [filename] "
+ "Answer the following question using only the data provided in the sources below. "
+ "For tabular information return it as an html table. Do not return markdown format. "
+ "The text and image source can be the same file name, don't use the image title when citing the image source, only use the file name as mentioned "
+ "If you cannot answer using the sources below, say you don't know. Return just the answer without any input texts "
)
at: app.backend.approaches.retrievethenreadvision.RetrieveThenReadVisionApproach.__init__
self.blob_container_client = blob_container_client
self.openai_client = openai_client
self.gpt4v_model = gpt4v_model
at: approaches.approach
ThoughtStep(title: str, description: Optional[Any], props: Optional[dict[str, Any]]=None)
at: approaches.approach.Approach
build_filter(overrides: dict[str, Any], auth_claims: dict[str, Any]) -> Optional[str]
|
app.backend.approaches.retrievethenread/RetrieveThenReadApproach.__init__
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
77303da5516341bbdc78572c0ad83628b0ee5889
|
Improve token counting for messages with package (#1577)
|
<13>:<add> self.chatgpt_token_limit = get_token_limit(chatgpt_model)
|
<s> openai_client: AsyncOpenAI,
chatgpt_model: str,
chatgpt_deployment: Optional[str], # Not needed for non-Azure OpenAI
embedding_model: str,
embedding_deployment: Optional[str], # Not needed for non-Azure OpenAI or for retrieval_mode="text"
embedding_dimensions: int,
sourcepage_field: str,
content_field: str,
query_language: str,
query_speller: str,
):
<0> self.search_client = search_client
<1> self.chatgpt_deployment = chatgpt_deployment
<2> self.openai_client = openai_client
<3> self.auth_helper = auth_helper
<4> self.chatgpt_model = chatgpt_model
<5> self.embedding_model = embedding_model
<6> self.embedding_dimensions = embedding_dimensions
<7> self.chatgpt_deployment = chatgpt_deployment
<8> self.embedding_deployment = embedding_deployment
<9> self.sourcepage_field = sourcepage_field
<10> self.content_field = content_field
<11> self.query_language = query_language
<12> self.query_speller = query_speller
<13>
|
===========unchanged ref 0===========
at: approaches.approach.Approach
__init__(self, search_client: SearchClient, openai_client: AsyncOpenAI, auth_helper: AuthenticationHelper, query_language: Optional[str], query_speller: Optional[str], embedding_deployment: Optional[str], embedding_model: str, embedding_dimensions: int, openai_host: str, vision_endpoint: str, vision_token_provider: Callable[[], Awaitable[str]])
at: core.authentication
AuthenticationHelper(search_index: Optional[SearchIndex], use_authentication: bool, server_app_id: Optional[str], server_app_secret: Optional[str], client_app_id: Optional[str], tenant_id: Optional[str], require_access_control: bool=False, enable_global_documents: bool=False, enable_unauthenticated_access: bool=False)
===========changed ref 0===========
# module: app.backend.core.imageshelper
- def get_image_dims(image_uri: str) -> tuple[int, int]:
- # From https://github.com/openai/openai-cookbook/pull/881/files
- if re.match(r"data:image\/\w+;base64", image_uri):
- image_uri = re.sub(r"data:image\/\w+;base64,", "", image_uri)
- image = Image.open(BytesIO(base64.b64decode(image_uri)))
- return image.size
- else:
- raise ValueError("Image must be a base64 string.")
-
===========changed ref 1===========
<s> Optional[str],
gpt4v_model: str,
embedding_deployment: Optional[str], # Not needed for non-Azure OpenAI or for retrieval_mode="text"
embedding_model: str,
embedding_dimensions: int,
sourcepage_field: str,
content_field: str,
query_language: str,
query_speller: str,
vision_endpoint: str,
vision_token_provider: Callable[[], Awaitable[str]]
):
self.search_client = search_client
self.blob_container_client = blob_container_client
self.openai_client = openai_client
self.auth_helper = auth_helper
self.embedding_model = embedding_model
self.embedding_deployment = embedding_deployment
self.embedding_dimensions = embedding_dimensions
self.sourcepage_field = sourcepage_field
self.content_field = content_field
self.gpt4v_deployment = gpt4v_deployment
self.gpt4v_model = gpt4v_model
self.query_language = query_language
self.query_speller = query_speller
self.vision_endpoint = vision_endpoint
self.vision_token_provider = vision_token_provider
+ self.gpt4v_token_limit = get_token_limit(gpt4v_model)
===========changed ref 2===========
# module: tests.test_chatapproach
- def test_get_messages_from_history_few_shots(chat_approach):
- user_query_request = "What does a Product manager do?"
- messages = chat_approach.get_messages_from_history(
- system_prompt=chat_approach.query_prompt_template,
- model_id=chat_approach.chatgpt_model,
- user_content=user_query_request,
- history=[],
- max_tokens=chat_approach.chatgpt_token_limit - len(user_query_request),
- few_shots=chat_approach.query_prompt_few_shots,
- )
- # Make sure messages are in the right order
- assert messages[0]["role"] == "system"
- assert messages[1]["role"] == "user"
- assert messages[2]["role"] == "assistant"
- assert messages[3]["role"] == "user"
- assert messages[4]["role"] == "assistant"
- assert messages[5]["role"] == "user"
- assert messages[5]["content"] == user_query_request
-
===========changed ref 3===========
# module: tests.test_chatapproach
- def test_get_messages_from_history_truncated(chat_approach):
- messages = chat_approach.get_messages_from_history(
- system_prompt="You are a bot.",
- model_id="gpt-35-turbo",
- history=[
- {"role": "user", "content": "What happens in a performance review?"},
- {
- "role": "assistant",
- "content": "During the performance review at Contoso Electronics, the supervisor will discuss the employee's performance over the past year and provide feedback on areas for improvement. They will also provide an opportunity for the employee to discuss their goals and objectives for the upcoming year. The review is a two-way dialogue between managers and employees, and employees will receive a written summary of their performance review which will include a rating of their performance, feedback, and goals and objectives for the upcoming year [employee_handbook-3.pdf].",
- },
- {"role": "user", "content": "What does a Product Manager do?"},
- ],
- user_content="What does a Product Manager do?",
- max_tokens=10,
- )
- assert messages == [
- {"role": "system", "content": "You are a bot."},
- {"role": "user", "content": "What does a Product Manager do?"},
- ]
-
===========changed ref 4===========
# module: app.backend.core.imageshelper
- def calculate_image_token_cost(image_uri: str, detail: str = "auto") -> int:
- # From https://github.com/openai/openai-cookbook/pull/881/files
- # Based on https://platform.openai.com/docs/guides/vision
- LOW_DETAIL_COST = 85
- HIGH_DETAIL_COST_PER_TILE = 170
- ADDITIONAL_COST = 85
-
- if detail == "auto":
- # assume high detail for now
- detail = "high"
-
- if detail == "low":
- # Low detail images have a fixed cost
- return LOW_DETAIL_COST
- elif detail == "high":
- # Calculate token cost for high detail images
- width, height = get_image_dims(image_uri)
- # Check if resizing is needed to fit within a 2048 x 2048 square
- if max(width, height) > 2048:
- # Resize dimensions to fit within a 2048 x 2048 square
- ratio = 2048 / max(width, height)
- width = int(width * ratio)
- height = int(height * ratio)
- # Further scale down to 768px on the shortest side
- if min(width, height) > 768:
- ratio = 768 / min(width, height)
- width = int(width * ratio)
- height = int(height * ratio)
- # Calculate the number of 512px squares
- num_squares = math.ceil(width / 512) * math.ceil(height / 512)
- # Calculate the total token cost
- total_cost = num_squares * HIGH_DETAIL_COST_PER_TILE + ADDITIONAL_COST
- return total_cost
- else:
- # Invalid detail_option
- raise ValueError("Invalid value for detail parameter. Use 'low' or 'high'.")
-
|
app.backend.approaches.retrievethenread/RetrieveThenReadApproach.run
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
77303da5516341bbdc78572c0ad83628b0ee5889
|
Improve token counting for messages with package (#1577)
|
<1>:<add> if not isinstance(q, str):
<add> raise ValueError("The most recent message content must be a string.")
|
# module: app.backend.approaches.retrievethenread
class RetrieveThenReadApproach(Approach):
def run(
self,
+ messages: list[ChatCompletionMessageParam],
- messages: list[dict],
stream: bool = False, # Stream is not used in this approach
session_state: Any = None,
context: dict[str, Any] = {},
) -> Union[dict[str, Any], AsyncGenerator[dict[str, Any], None]]:
<0> q = messages[-1]["content"]
<1> overrides = context.get("overrides", {})
<2> auth_claims = context.get("auth_claims", {})
<3> has_text = overrides.get("retrieval_mode") in ["text", "hybrid", None]
<4> has_vector = overrides.get("retrieval_mode") in ["vectors", "hybrid", None]
<5> use_semantic_ranker = overrides.get("semantic_ranker") and has_text
<6>
<7> use_semantic_captions = True if overrides.get("semantic_captions") and has_text else False
<8> top = overrides.get("top", 3)
<9> minimum_search_score = overrides.get("minimum_search_score", 0.0)
<10> minimum_reranker_score = overrides.get("minimum_reranker_score", 0.0)
<11> filter = self.build_filter(overrides, auth_claims)
<12> # If retrieval mode includes vectors, compute an embedding for the query
<13> vectors: list[VectorQuery] = []
<14> if has_vector:
<15> vectors.append(await self.compute_text_embedding(q))
<16>
<17> # Only keep the text query if the retrieval mode uses text, otherwise drop it
<18> query_text = q if has_text else None
<19>
<20> results = await self.search(
<21> top,
<22> query_text,
<23> filter,
<24> vectors,
<25> use_semantic_ranker,
<26> use_semantic_captions,
<27> minimum_search_score,
<28> minimum_r</s>
|
===========below chunk 0===========
# module: app.backend.approaches.retrievethenread
class RetrieveThenReadApproach(Approach):
def run(
self,
+ messages: list[ChatCompletionMessageParam],
- messages: list[dict],
stream: bool = False, # Stream is not used in this approach
session_state: Any = None,
context: dict[str, Any] = {},
) -> Union[dict[str, Any], AsyncGenerator[dict[str, Any], None]]:
# offset: 1
)
user_content = [q]
template = overrides.get("prompt_template", self.system_chat_template)
model = self.chatgpt_model
message_builder = MessageBuilder(template, model)
# Process results
sources_content = self.get_sources_content(results, use_semantic_captions, use_image_citation=False)
# Append user message
content = "\n".join(sources_content)
user_content = q + "\n" + f"Sources:\n {content}"
message_builder.insert_message("user", user_content)
message_builder.insert_message("assistant", self.answer)
message_builder.insert_message("user", self.question)
updated_messages = message_builder.messages
chat_completion = (
await self.openai_client.chat.completions.create(
# Azure OpenAI takes the deployment name as the model name
model=self.chatgpt_deployment if self.chatgpt_deployment else self.chatgpt_model,
messages=updated_messages,
temperature=overrides.get("temperature", 0.3),
max_tokens=1024,
n=1,
)
).model_dump()
data_points = {"text": sources_content}
extra_info = {
"data_points": data_points,
"thoughts": [
ThoughtStep(
"Search using user query",
query_text,
{
"use_semantic_captions":</s>
===========below chunk 1===========
# module: app.backend.approaches.retrievethenread
class RetrieveThenReadApproach(Approach):
def run(
self,
+ messages: list[ChatCompletionMessageParam],
- messages: list[dict],
stream: bool = False, # Stream is not used in this approach
session_state: Any = None,
context: dict[str, Any] = {},
) -> Union[dict[str, Any], AsyncGenerator[dict[str, Any], None]]:
# offset: 2
<s>Step(
"Search using user query",
query_text,
{
"use_semantic_captions": use_semantic_captions,
"use_semantic_ranker": use_semantic_ranker,
"top": top,
"filter": filter,
"has_vector": has_vector,
},
),
ThoughtStep(
"Search results",
[result.serialize_for_results() for result in results],
),
ThoughtStep(
"Prompt to generate answer",
[str(message) for message in updated_messages],
(
{"model": self.chatgpt_model, "deployment": self.chatgpt_deployment}
if self.chatgpt_deployment
else {"model": self.chatgpt_model}
),
),
],
}
chat_completion["choices"][0]["context"] = extra_info
chat_completion["choices"][0]["session_state"] = session_state
return chat_completion
===========unchanged ref 0===========
at: app.backend.approaches.retrievethenread.RetrieveThenReadApproach
system_chat_template = (
"You are an intelligent assistant helping Contoso Inc employees with their healthcare plan questions and employee handbook questions. "
+ "Use 'you' to refer to the individual asking the questions even if they ask with 'I'. "
+ "Answer the following question using only the data provided in the sources below. "
+ "For tabular information return it as an html table. Do not return markdown format. "
+ "Each source has a name followed by colon and the actual information, always include the source name for each fact you use in the response. "
+ "If you cannot answer using the sources below, say you don't know. Use below example to answer"
)
question = """
'What is the deductible for the employee plan for a visit to Overlake in Bellevue?'
Sources:
info1.txt: deductibles depend on whether you are in-network or out-of-network. In-network deductibles are $500 for employee and $1000 for family. Out-of-network deductibles are $1000 for employee and $2000 for family.
info2.pdf: Overlake is in-network for the employee plan.
info3.pdf: Overlake is the name of the area that includes a park and ride near Bellevue.
info4.pdf: In-network institutions include Overlake, Swedish and others in the region
"""
answer = "In-network deductibles are $500 for employee and $1000 for family [info1.txt] and Overlake is in-network for the employee plan [info2.pdf][info4.pdf]."
at: app.backend.approaches.retrievethenread.RetrieveThenReadApproach.__init__
self.openai_client = openai_client
self.chatgpt_model = chatgpt_model
===========unchanged ref 1===========
at: approaches.approach
ThoughtStep(title: str, description: Optional[Any], props: Optional[dict[str, Any]]=None)
at: approaches.approach.Approach
build_filter(overrides: dict[str, Any], auth_claims: dict[str, Any]) -> Optional[str]
search(top: int, query_text: Optional[str], filter: Optional[str], vectors: List[VectorQuery], use_semantic_ranker: bool, use_semantic_captions: bool, minimum_search_score: Optional[float], minimum_reranker_score: Optional[float]) -> List[Document]
get_sources_content(results: List[Document], use_semantic_captions: bool, use_image_citation: bool) -> list[str]
compute_text_embedding(q: str)
run(self, messages: list[ChatCompletionMessageParam], stream: bool=False, session_state: Any=None, context: dict[str, Any]={}) -> Union[dict[str, Any], AsyncGenerator[dict[str, Any], None]]
at: typing
AsyncGenerator = _alias(collections.abc.AsyncGenerator, 2)
at: typing.Mapping
get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]
get(key: _KT) -> Optional[_VT_co]
|
app.backend.approaches.chatapproach/ChatApproach.run_without_streaming
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
77303da5516341bbdc78572c0ad83628b0ee5889
|
Improve token counting for messages with package (#1577)
|
<1>:<add> messages, overrides, auth_claims, should_stream=False
<del> history, overrides, auth_claims, should_stream=False
|
# module: app.backend.approaches.chatapproach
class ChatApproach(Approach, ABC):
def run_without_streaming(
self,
+ messages: list[ChatCompletionMessageParam],
- history: list[dict[str, str]],
overrides: dict[str, Any],
auth_claims: dict[str, Any],
session_state: Any = None,
) -> dict[str, Any]:
<0> extra_info, chat_coroutine = await self.run_until_final_call(
<1> history, overrides, auth_claims, should_stream=False
<2> )
<3> chat_completion_response: ChatCompletion = await chat_coroutine
<4> chat_resp = chat_completion_response.model_dump() # Convert to dict to make it JSON serializable
<5> chat_resp["choices"][0]["context"] = extra_info
<6> if overrides.get("suggest_followup_questions"):
<7> content, followup_questions = self.extract_followup_questions(chat_resp["choices"][0]["message"]["content"])
<8> chat_resp["choices"][0]["message"]["content"] = content
<9> chat_resp["choices"][0]["context"]["followup_questions"] = followup_questions
<10> chat_resp["choices"][0]["session_state"] = session_state
<11> return chat_resp
<12>
|
===========unchanged ref 0===========
at: app.backend.approaches.chatapproach.ChatApproach.run_with_streaming
extra_info, chat_coroutine = await self.run_until_final_call(
messages, overrides, auth_claims, should_stream=True
)
at: typing.Mapping
get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]
get(key: _KT) -> Optional[_VT_co]
===========changed ref 0===========
# module: app.backend.approaches.chatapproach
class ChatApproach(Approach, ABC):
- def get_messages_from_history(
- self,
- system_prompt: str,
- model_id: str,
- history: list[dict[str, str]],
- user_content: Union[str, list[ChatCompletionContentPartParam]],
- max_tokens: int,
- few_shots=[],
- ) -> list[ChatCompletionMessageParam]:
- message_builder = MessageBuilder(system_prompt, model_id)
-
- # Add examples to show the chat what responses we want. It will try to mimic any responses and make sure they match the rules laid out in the system message.
- for shot in reversed(few_shots):
- message_builder.insert_message(shot.get("role"), shot.get("content"))
-
- append_index = len(few_shots) + 1
-
- message_builder.insert_message(self.USER, user_content, index=append_index)
-
- total_token_count = 0
- for existing_message in message_builder.messages:
- total_token_count += message_builder.count_tokens_for_message(existing_message)
-
- newest_to_oldest = list(reversed(history[:-1]))
- for message in newest_to_oldest:
- potential_message_count = message_builder.count_tokens_for_message(message)
- if (total_token_count + potential_message_count) > max_tokens:
- logging.info("Reached max tokens of %d, history will be truncated", max_tokens)
- break
- message_builder.insert_message(message["role"], message["content"], index=append_index)
- total_token_count += potential_message_count
- return message_builder.messages
-
===========changed ref 1===========
# module: app.backend.approaches.chatapproach
class ChatApproach(Approach, ABC):
- # Chat roles
- SYSTEM = "system"
- USER = "user"
- ASSISTANT = "assistant"
-
- query_prompt_few_shots = [
+ query_prompt_few_shots: list[ChatCompletionMessageParam] = [
+ {"role": "user", "content": "How did crypto do last year?"},
- {"role": USER, "content": "How did crypto do last year?"},
+ {"role": "assistant", "content": "Summarize Cryptocurrency Market Dynamics from last year"},
- {"role": ASSISTANT, "content": "Summarize Cryptocurrency Market Dynamics from last year"},
+ {"role": "user", "content": "What are my health plans?"},
- {"role": USER, "content": "What are my health plans?"},
+ {"role": "assistant", "content": "Show available health plans"},
- {"role": ASSISTANT, "content": "Show available health plans"},
]
NO_RESPONSE = "0"
follow_up_questions_prompt_content = """Generate 3 very brief follow-up questions that the user would likely ask next.
Enclose the follow-up questions in double angle brackets. Example:
<<Are there exclusions for prescriptions?>>
<<Which pharmacies can be ordered from?>>
<<What is the limit for over-the-counter medication?>>
Do no repeat questions that have already been asked.
Make sure the last question ends with ">>".
"""
query_prompt_template = """Below is a history of the conversation so far, and a new question asked by the user that needs to be answered by searching in a knowledge base.
You have access to Azure AI Search index with 100's of documents.
Generate a search query based on the conversation and the new question.
Do not include cited source filenames and document names e.g info.txt or doc.pdf in the search query terms.</s>
===========changed ref 2===========
# module: app.backend.approaches.chatapproach
class ChatApproach(Approach, ABC):
# offset: 1
<s> question.
Do not include cited source filenames and document names e.g info.txt or doc.pdf in the search query terms.
Do not include any text inside [] or <<>> in the search query terms.
Do not include any special characters like '+'.
If the question is not in English, translate the question to English before generating the search query.
If you cannot generate a search query, return just the number 0.
"""
===========changed ref 3===========
# module: app.backend.core.imageshelper
- def get_image_dims(image_uri: str) -> tuple[int, int]:
- # From https://github.com/openai/openai-cookbook/pull/881/files
- if re.match(r"data:image\/\w+;base64", image_uri):
- image_uri = re.sub(r"data:image\/\w+;base64,", "", image_uri)
- image = Image.open(BytesIO(base64.b64decode(image_uri)))
- return image.size
- else:
- raise ValueError("Image must be a base64 string.")
-
===========changed ref 4===========
<s> openai_client: AsyncOpenAI,
chatgpt_model: str,
chatgpt_deployment: Optional[str], # Not needed for non-Azure OpenAI
embedding_model: str,
embedding_deployment: Optional[str], # Not needed for non-Azure OpenAI or for retrieval_mode="text"
embedding_dimensions: int,
sourcepage_field: str,
content_field: str,
query_language: str,
query_speller: str,
):
self.search_client = search_client
self.chatgpt_deployment = chatgpt_deployment
self.openai_client = openai_client
self.auth_helper = auth_helper
self.chatgpt_model = chatgpt_model
self.embedding_model = embedding_model
self.embedding_dimensions = embedding_dimensions
self.chatgpt_deployment = chatgpt_deployment
self.embedding_deployment = embedding_deployment
self.sourcepage_field = sourcepage_field
self.content_field = content_field
self.query_language = query_language
self.query_speller = query_speller
+ self.chatgpt_token_limit = get_token_limit(chatgpt_model)
|
app.backend.approaches.chatapproach/ChatApproach.run_with_streaming
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
77303da5516341bbdc78572c0ad83628b0ee5889
|
Improve token counting for messages with package (#1577)
|
<1>:<add> messages, overrides, auth_claims, should_stream=True
<del> history, overrides, auth_claims, should_stream=True
<6>:<add> "delta": {"role": "assistant"},
<del> "delta": {"role": self.ASSISTANT},
|
# module: app.backend.approaches.chatapproach
class ChatApproach(Approach, ABC):
def run_with_streaming(
self,
+ messages: list[ChatCompletionMessageParam],
- history: list[dict[str, str]],
overrides: dict[str, Any],
auth_claims: dict[str, Any],
session_state: Any = None,
) -> AsyncGenerator[dict, None]:
<0> extra_info, chat_coroutine = await self.run_until_final_call(
<1> history, overrides, auth_claims, should_stream=True
<2> )
<3> yield {
<4> "choices": [
<5> {
<6> "delta": {"role": self.ASSISTANT},
<7> "context": extra_info,
<8> "session_state": session_state,
<9> "finish_reason": None,
<10> "index": 0,
<11> }
<12> ],
<13> "object": "chat.completion.chunk",
<14> }
<15>
<16> followup_questions_started = False
<17> followup_content = ""
<18> async for event_chunk in await chat_coroutine:
<19> # "2023-07-01-preview" API version has a bug where first response has empty choices
<20> event = event_chunk.model_dump() # Convert pydantic model to dict
<21> if event["choices"]:
<22> # if event contains << and not >>, it is start of follow-up question, truncate
<23> content = event["choices"][0]["delta"].get("content")
<24> content = content or "" # content may either not exist in delta, or explicitly be None
<25> if overrides.get("suggest_followup_questions") and "<<" in content:
<26> followup_questions_started = True
<27> earlier_content = content[: content.index("<<")]
<28> if earlier_content:
<29> event["choices"][0]["delta"]["content"] = earlier_content
<30> yield event
<31> followup_content += content[content.index("<<") :]
<32> </s>
|
===========below chunk 0===========
# module: app.backend.approaches.chatapproach
class ChatApproach(Approach, ABC):
def run_with_streaming(
self,
+ messages: list[ChatCompletionMessageParam],
- history: list[dict[str, str]],
overrides: dict[str, Any],
auth_claims: dict[str, Any],
session_state: Any = None,
) -> AsyncGenerator[dict, None]:
# offset: 1
followup_content += content
else:
yield event
if followup_content:
_, followup_questions = self.extract_followup_questions(followup_content)
yield {
"choices": [
{
"delta": {"role": self.ASSISTANT},
"context": {"followup_questions": followup_questions},
"finish_reason": None,
"index": 0,
}
],
"object": "chat.completion.chunk",
}
===========unchanged ref 0===========
at: app.backend.approaches.chatapproach.ChatApproach
query_prompt_few_shots: list[ChatCompletionMessageParam] = [
{"role": "user", "content": "How did crypto do last year?"},
{"role": "assistant", "content": "Summarize Cryptocurrency Market Dynamics from last year"},
{"role": "user", "content": "What are my health plans?"},
{"role": "assistant", "content": "Show available health plans"},
]
NO_RESPONSE = "0"
follow_up_questions_prompt_content = """Generate 3 very brief follow-up questions that the user would likely ask next.
Enclose the follow-up questions in double angle brackets. Example:
<<Are there exclusions for prescriptions?>>
<<Which pharmacies can be ordered from?>>
<<What is the limit for over-the-counter medication?>>
Do no repeat questions that have already been asked.
Make sure the last question ends with ">>".
"""
query_prompt_template = """Below is a history of the conversation so far, and a new question asked by the user that needs to be answered by searching in a knowledge base.
You have access to Azure AI Search index with 100's of documents.
Generate a search query based on the conversation and the new question.
Do not include cited source filenames and document names e.g info.txt or doc.pdf in the search query terms.
Do not include any text inside [] or <<>> in the search query terms.
Do not include any special characters like '+'.
If the question is not in English, translate the question to English before generating the search query.
If you cannot generate a search query, return just the number 0.
"""
extract_followup_questions(content: str)
run_without_streaming(messages: list[ChatCompletionMessageParam], overrides: dict[str, Any], auth_claims: dict[str, Any], session_state: Any=None) -> dict[str, Any]
===========unchanged ref 1===========
run_with_streaming(messages: list[ChatCompletionMessageParam], overrides: dict[str, Any], auth_claims: dict[str, Any], session_state: Any=None) -> AsyncGenerator[dict, None]
at: app.backend.approaches.chatapproach.ChatApproach.run_with_streaming
followup_content += content[content.index("<<") :]
followup_content = ""
followup_content += content
at: approaches.approach.Approach
run(self, messages: list[ChatCompletionMessageParam], stream: bool=False, session_state: Any=None, context: dict[str, Any]={}) -> Union[dict[str, Any], AsyncGenerator[dict[str, Any], None]]
at: typing
AsyncGenerator = _alias(collections.abc.AsyncGenerator, 2)
at: typing.Mapping
get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]
get(key: _KT) -> Optional[_VT_co]
===========changed ref 0===========
# module: app.backend.approaches.chatapproach
class ChatApproach(Approach, ABC):
def run_without_streaming(
self,
+ messages: list[ChatCompletionMessageParam],
- history: list[dict[str, str]],
overrides: dict[str, Any],
auth_claims: dict[str, Any],
session_state: Any = None,
) -> dict[str, Any]:
extra_info, chat_coroutine = await self.run_until_final_call(
+ messages, overrides, auth_claims, should_stream=False
- history, overrides, auth_claims, should_stream=False
)
chat_completion_response: ChatCompletion = await chat_coroutine
chat_resp = chat_completion_response.model_dump() # Convert to dict to make it JSON serializable
chat_resp["choices"][0]["context"] = extra_info
if overrides.get("suggest_followup_questions"):
content, followup_questions = self.extract_followup_questions(chat_resp["choices"][0]["message"]["content"])
chat_resp["choices"][0]["message"]["content"] = content
chat_resp["choices"][0]["context"]["followup_questions"] = followup_questions
chat_resp["choices"][0]["session_state"] = session_state
return chat_resp
===========changed ref 1===========
# module: app.backend.approaches.chatapproach
class ChatApproach(Approach, ABC):
- def get_messages_from_history(
- self,
- system_prompt: str,
- model_id: str,
- history: list[dict[str, str]],
- user_content: Union[str, list[ChatCompletionContentPartParam]],
- max_tokens: int,
- few_shots=[],
- ) -> list[ChatCompletionMessageParam]:
- message_builder = MessageBuilder(system_prompt, model_id)
-
- # Add examples to show the chat what responses we want. It will try to mimic any responses and make sure they match the rules laid out in the system message.
- for shot in reversed(few_shots):
- message_builder.insert_message(shot.get("role"), shot.get("content"))
-
- append_index = len(few_shots) + 1
-
- message_builder.insert_message(self.USER, user_content, index=append_index)
-
- total_token_count = 0
- for existing_message in message_builder.messages:
- total_token_count += message_builder.count_tokens_for_message(existing_message)
-
- newest_to_oldest = list(reversed(history[:-1]))
- for message in newest_to_oldest:
- potential_message_count = message_builder.count_tokens_for_message(message)
- if (total_token_count + potential_message_count) > max_tokens:
- logging.info("Reached max tokens of %d, history will be truncated", max_tokens)
- break
- message_builder.insert_message(message["role"], message["content"], index=append_index)
- total_token_count += potential_message_count
- return message_builder.messages
-
|
scripts.auth_update/main
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
c6b8c6e23e6738c55daca84aabf047af7ceef988
|
Updates to login docs (login step, Entra branding) (#1574)
|
<4>:<add> auth_tenant = os.getenv("AZURE_AUTH_TENANT_ID", os.environ["AZURE_TENANT_ID"])
<del> credential = AzureDeveloperCliCredential(tenant_id=os.getenv("AZURE_AUTH_TENANT_ID", os.environ["AZURE_TENANT_ID"]))
<5>:<add> credential = AzureDeveloperCliCredential(tenant_id=auth_tenant)
|
# module: scripts.auth_update
def main():
<0> if not test_authentication_enabled():
<1> print("Not updating authentication.")
<2> exit(0)
<3>
<4> credential = AzureDeveloperCliCredential(tenant_id=os.getenv("AZURE_AUTH_TENANT_ID", os.environ["AZURE_TENANT_ID"]))
<5>
<6> scopes = ["https://graph.microsoft.com/.default"]
<7> graph_client = GraphServiceClient(credentials=credential, scopes=scopes)
<8>
<9> uri = os.getenv("BACKEND_URI")
<10> client_app_id = os.getenv("AZURE_CLIENT_APP_ID", None)
<11> if client_app_id:
<12> client_object_id = await get_application(graph_client, client_app_id)
<13> if client_object_id:
<14> print(f"Updating redirect URIs for client app ID {client_app_id}...")
<15> # Redirect URIs need to be relative to the deployed application
<16> app = Application(
<17> public_client=PublicClientApplication(redirect_uris=[]),
<18> spa=SpaApplication(
<19> redirect_uris=[
<20> "http://localhost:50505/redirect",
<21> "http://localhost:5173/redirect",
<22> f"{uri}/redirect",
<23> ]
<24> ),
<25> web=WebApplication(
<26> redirect_uris=[
<27> f"{uri}/.auth/login/aad/callback",
<28> ]
<29> ),
<30> )
<31> await graph_client.applications.by_application_id(client_object_id).patch(app)
<32> print(f"Application update for client app id {client_app_id} complete.")
<33>
|
===========unchanged ref 0===========
at: auth_common
get_application(graph_client: GraphServiceClient, client_id: str) -> Optional[str]
test_authentication_enabled()
at: os
environ = _createenviron()
getenv(key: str, default: _T) -> Union[str, _T]
getenv(key: str) -> Optional[str]
===========changed ref 0===========
# module: scripts.adlsgen2setup
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Upload sample data to a Data Lake Storage Gen2 account and associate sample access control lists with it using sample groups",
epilog="Example: ./scripts/adlsgen2setup.py ./data --data-access-control ./scripts/sampleacls.json --storage-account <name of storage account> --create-security-enabled-groups <true|false>",
)
parser.add_argument("data_directory", help="Data directory that contains sample PDFs")
parser.add_argument(
"--storage-account",
required=True,
help="Name of the Data Lake Storage Gen2 account to upload the sample data to",
)
parser.add_argument(
"--create-security-enabled-groups",
required=False,
action="store_true",
+ help="Whether or not the sample groups created are security enabled in Microsoft Entra",
- help="Whether or not the sample groups created are security enabled in Azure AD",
)
parser.add_argument(
"--data-access-control", required=True, help="JSON file describing access control for the sample data"
)
parser.add_argument("--verbose", "-v", required=False, action="store_true", help="Verbose output")
args = parser.parse_args()
if args.verbose:
logging.basicConfig()
logging.getLogger().setLevel(logging.INFO)
asyncio.run(main(args))
|
scripts.auth_init/main
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
c6b8c6e23e6738c55daca84aabf047af7ceef988
|
Updates to login docs (login step, Entra branding) (#1574)
|
<4>:<del> print("Setting up authentication...")
<5>:<add> auth_tenant = os.getenv("AZURE_AUTH_TENANT_ID", os.environ["AZURE_TENANT_ID"])
<del> credential = AzureDeveloperCliCredential(tenant_id=os.getenv("AZURE_AUTH_TENANT_ID", os.environ["AZURE_TENANT_ID"]))
<6>:<add> print("Setting up authentication for tenant", auth_tenant)
<add> credential = AzureDeveloperCliCredential(tenant_id=auth_tenant)
|
# module: scripts.auth_init
def main():
<0> if not test_authentication_enabled():
<1> print("Not setting up authentication.")
<2> exit(0)
<3>
<4> print("Setting up authentication...")
<5> credential = AzureDeveloperCliCredential(tenant_id=os.getenv("AZURE_AUTH_TENANT_ID", os.environ["AZURE_TENANT_ID"]))
<6>
<7> scopes = ["https://graph.microsoft.com/.default"]
<8> graph_client = GraphServiceClient(credentials=credential, scopes=scopes)
<9>
<10> app_identifier = random_app_identifier()
<11> server_object_id, server_app_id, _ = await create_or_update_application_with_secret(
<12> graph_client,
<13> app_id_env_var="AZURE_SERVER_APP_ID",
<14> app_secret_env_var="AZURE_SERVER_APP_SECRET",
<15> request_app=server_app_initial(app_identifier),
<16> )
<17> print("Setting up server application permissions...")
<18> server_app_permission = server_app_permission_setup(server_app_id)
<19> await graph_client.applications.by_application_id(server_object_id).patch(server_app_permission)
<20>
<21> _, client_app_id, _ = await create_or_update_application_with_secret(
<22> graph_client,
<23> app_id_env_var="AZURE_CLIENT_APP_ID",
<24> app_secret_env_var="AZURE_CLIENT_APP_SECRET",
<25> request_app=client_app(server_app_id, server_app_permission, app_identifier),
<26> )
<27>
<28> print("Setting up server known client applications...")
<29> await graph_client.applications.by_application_id(server_object_id).patch(
<30> server_app_known_client_application(client_app_id)
<31> )
<32> print("Authentication setup complete.")
<33>
|
===========unchanged ref 0===========
at: auth_common
test_authentication_enabled()
at: os
environ = _createenviron()
getenv(key: str, default: _T) -> Union[str, _T]
getenv(key: str) -> Optional[str]
at: scripts.auth_init
create_or_update_application_with_secret(graph_client: GraphServiceClient, app_id_env_var: str, app_secret_env_var: str, request_app: Application) -> Tuple[str, str, bool]
random_app_identifier()
server_app_initial(identifier: int) -> Application
server_app_permission_setup(server_app_id: str) -> Application
client_app(server_app_id: str, server_app: Application, identifier: int) -> Application
server_app_known_client_application(client_app_id: str) -> Application
===========changed ref 0===========
# module: scripts.adlsgen2setup
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Upload sample data to a Data Lake Storage Gen2 account and associate sample access control lists with it using sample groups",
epilog="Example: ./scripts/adlsgen2setup.py ./data --data-access-control ./scripts/sampleacls.json --storage-account <name of storage account> --create-security-enabled-groups <true|false>",
)
parser.add_argument("data_directory", help="Data directory that contains sample PDFs")
parser.add_argument(
"--storage-account",
required=True,
help="Name of the Data Lake Storage Gen2 account to upload the sample data to",
)
parser.add_argument(
"--create-security-enabled-groups",
required=False,
action="store_true",
+ help="Whether or not the sample groups created are security enabled in Microsoft Entra",
- help="Whether or not the sample groups created are security enabled in Azure AD",
)
parser.add_argument(
"--data-access-control", required=True, help="JSON file describing access control for the sample data"
)
parser.add_argument("--verbose", "-v", required=False, action="store_true", help="Verbose output")
args = parser.parse_args()
if args.verbose:
logging.basicConfig()
logging.getLogger().setLevel(logging.INFO)
asyncio.run(main(args))
===========changed ref 1===========
# module: scripts.auth_update
def main():
if not test_authentication_enabled():
print("Not updating authentication.")
exit(0)
+ auth_tenant = os.getenv("AZURE_AUTH_TENANT_ID", os.environ["AZURE_TENANT_ID"])
- credential = AzureDeveloperCliCredential(tenant_id=os.getenv("AZURE_AUTH_TENANT_ID", os.environ["AZURE_TENANT_ID"]))
+ credential = AzureDeveloperCliCredential(tenant_id=auth_tenant)
scopes = ["https://graph.microsoft.com/.default"]
graph_client = GraphServiceClient(credentials=credential, scopes=scopes)
uri = os.getenv("BACKEND_URI")
client_app_id = os.getenv("AZURE_CLIENT_APP_ID", None)
if client_app_id:
client_object_id = await get_application(graph_client, client_app_id)
if client_object_id:
print(f"Updating redirect URIs for client app ID {client_app_id}...")
# Redirect URIs need to be relative to the deployed application
app = Application(
public_client=PublicClientApplication(redirect_uris=[]),
spa=SpaApplication(
redirect_uris=[
"http://localhost:50505/redirect",
"http://localhost:5173/redirect",
f"{uri}/redirect",
]
),
web=WebApplication(
redirect_uris=[
f"{uri}/.auth/login/aad/callback",
]
),
)
await graph_client.applications.by_application_id(client_object_id).patch(app)
print(f"Application update for client app id {client_app_id} complete.")
|
tests.test_chatvisionapproach/chat_approach
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
69b6e8a387d10a0242bbb88dbebce8a4ca74b153
|
Use chat model for query rewriting (#1659)
|
<15>:<add> chatgpt_model="gpt-35-turbo",
<add> chatgpt_deployment="chat",
|
# module: tests.test_chatvisionapproach
@pytest.fixture
def chat_approach(openai_client, mock_confidential_client_success):
<0> return ChatReadRetrieveReadVisionApproach(
<1> search_client=None,
<2> openai_client=openai_client,
<3> auth_helper=AuthenticationHelper(
<4> search_index=MockSearchIndex,
<5> use_authentication=True,
<6> server_app_id="SERVER_APP",
<7> server_app_secret="SERVER_SECRET",
<8> client_app_id="CLIENT_APP",
<9> tenant_id="TENANT_ID",
<10> require_access_control=None,
<11> ),
<12> blob_container_client=None,
<13> vision_endpoint="endpoint",
<14> vision_token_provider=lambda: "token",
<15> gpt4v_deployment="gpt-4v",
<16> gpt4v_model="gpt-4v",
<17> embedding_deployment="embeddings",
<18> embedding_model=MOCK_EMBEDDING_MODEL_NAME,
<19> embedding_dimensions=MOCK_EMBEDDING_DIMENSIONS,
<20> sourcepage_field="",
<21> content_field="",
<22> query_language="en-us",
<23> query_speller="lexicon",
<24> )
<25>
|
===========unchanged ref 0===========
at: _pytest.fixtures
fixture(fixture_function: FixtureFunction, *, scope: "Union[_ScopeName, Callable[[str, Config], _ScopeName]]"=..., params: Optional[Iterable[object]]=..., autouse: bool=..., ids: Optional[
Union[Sequence[Optional[object]], Callable[[Any], Optional[object]]]
]=..., name: Optional[str]=...) -> FixtureFunction
fixture(fixture_function: None=..., *, scope: "Union[_ScopeName, Callable[[str, Config], _ScopeName]]"=..., params: Optional[Iterable[object]]=..., autouse: bool=..., ids: Optional[
Union[Sequence[Optional[object]], Callable[[Any], Optional[object]]]
]=..., name: Optional[str]=None) -> FixtureFunctionMarker
at: tests.conftest
mock_confidential_client_success(monkeypatch)
at: tests.mocks
MOCK_EMBEDDING_DIMENSIONS = 1536
MOCK_EMBEDDING_MODEL_NAME = "text-embedding-ada-002"
at: tests.test_chatvisionapproach
MockSearchIndex = SearchIndex(
name="test",
fields=[
SearchField(name="oids", type="Collection(Edm.String)"),
SearchField(name="groups", type="Collection(Edm.String)"),
],
)
openai_client()
|
app.backend.approaches.chatreadretrievereadvision/ChatReadRetrieveReadVisionApproach.__init__
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
69b6e8a387d10a0242bbb88dbebce8a4ca74b153
|
Use chat model for query rewriting (#1659)
|
<4>:<add> self.chatgpt_model = chatgpt_model
<add> self.chatgpt_deployment = chatgpt_deployment
|
<s>Azure OpenAI
gpt4v_model: str,
embedding_deployment: Optional[str], # Not needed for non-Azure OpenAI or for retrieval_mode="text"
embedding_model: str,
embedding_dimensions: int,
sourcepage_field: str,
content_field: str,
query_language: str,
query_speller: str,
vision_endpoint: str,
vision_token_provider: Callable[[], Awaitable[str]]
):
<0> self.search_client = search_client
<1> self.blob_container_client = blob_container_client
<2> self.openai_client = openai_client
<3> self.auth_helper = auth_helper
<4> self.gpt4v_deployment = gpt4v_deployment
<5> self.gpt4v_model = gpt4v_model
<6> self.embedding_deployment = embedding_deployment
<7> self.embedding_model = embedding_model
<8> self.embedding_dimensions = embedding_dimensions
<9> self.sourcepage_field = sourcepage_field
<10> self.content_field = content_field
<11> self.query_language = query_language
<12> self.query_speller = query_speller
<13> self.vision_endpoint = vision_endpoint
<14> self.vision_token_provider = vision_token_provider
<15> self.chatgpt_token_limit = get_token_limit(gpt4v_model)
<16>
|
===========unchanged ref 0===========
at: approaches.approach.Approach
__init__(self, search_client: SearchClient, openai_client: AsyncOpenAI, auth_helper: AuthenticationHelper, query_language: Optional[str], query_speller: Optional[str], embedding_deployment: Optional[str], embedding_model: str, embedding_dimensions: int, openai_host: str, vision_endpoint: str, vision_token_provider: Callable[[], Awaitable[str]])
at: core.authentication
AuthenticationHelper(search_index: Optional[SearchIndex], use_authentication: bool, server_app_id: Optional[str], server_app_secret: Optional[str], client_app_id: Optional[str], tenant_id: Optional[str], require_access_control: bool=False, enable_global_documents: bool=False, enable_unauthenticated_access: bool=False)
at: typing
Awaitable = _alias(collections.abc.Awaitable, 1)
Callable = _CallableType(collections.abc.Callable, 2)
===========changed ref 0===========
# module: tests.test_chatvisionapproach
@pytest.fixture
def chat_approach(openai_client, mock_confidential_client_success):
return ChatReadRetrieveReadVisionApproach(
search_client=None,
openai_client=openai_client,
auth_helper=AuthenticationHelper(
search_index=MockSearchIndex,
use_authentication=True,
server_app_id="SERVER_APP",
server_app_secret="SERVER_SECRET",
client_app_id="CLIENT_APP",
tenant_id="TENANT_ID",
require_access_control=None,
),
blob_container_client=None,
vision_endpoint="endpoint",
vision_token_provider=lambda: "token",
+ chatgpt_model="gpt-35-turbo",
+ chatgpt_deployment="chat",
gpt4v_deployment="gpt-4v",
gpt4v_model="gpt-4v",
embedding_deployment="embeddings",
embedding_model=MOCK_EMBEDDING_MODEL_NAME,
embedding_dimensions=MOCK_EMBEDDING_DIMENSIONS,
sourcepage_field="",
content_field="",
query_language="en-us",
query_speller="lexicon",
)
|
tests.conftest/mock_env
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
7ffcb3b95500dd741de2e6d1b70fa8073c9c3ce3
|
Add speech recognizer and synthesis on browser interface (#113)
|
<5>:<add> monkeypatch.setenv("USE_SPEECH_INPUT_BROWSER", "true")
<add> monkeypatch.setenv("USE_SPEECH_OUTPUT_AZURE", "true")
<7>:<add> monkeypatch.setenv("AZURE_SPEECH_SERVICE_ID", "test-id")
<add> monkeypatch.setenv("AZURE_SPEECH_SERVICE_LOCATION", "eastus")
|
# module: tests.conftest
@pytest.fixture(params=envs, ids=["client0", "client1"])
def mock_env(monkeypatch, request):
<0> with mock.patch.dict(os.environ, clear=True):
<1> monkeypatch.setenv("AZURE_STORAGE_ACCOUNT", "test-storage-account")
<2> monkeypatch.setenv("AZURE_STORAGE_CONTAINER", "test-storage-container")
<3> monkeypatch.setenv("AZURE_STORAGE_RESOURCE_GROUP", "test-storage-rg")
<4> monkeypatch.setenv("AZURE_SUBSCRIPTION_ID", "test-storage-subid")
<5> monkeypatch.setenv("AZURE_SEARCH_INDEX", "test-search-index")
<6> monkeypatch.setenv("AZURE_SEARCH_SERVICE", "test-search-service")
<7> monkeypatch.setenv("AZURE_OPENAI_CHATGPT_MODEL", "gpt-35-turbo")
<8> monkeypatch.setenv("ALLOWED_ORIGIN", "https://frontend.com")
<9> for key, value in request.param.items():
<10> monkeypatch.setenv(key, value)
<11> if os.getenv("AZURE_USE_AUTHENTICATION") is not None:
<12> monkeypatch.delenv("AZURE_USE_AUTHENTICATION")
<13>
<14> with mock.patch("app.DefaultAzureCredential") as mock_default_azure_credential:
<15> mock_default_azure_credential.return_value = MockAzureCredential()
<16> yield
<17>
|
===========changed ref 0===========
# module: tests.conftest
+ @pytest.fixture
+ def mock_speech_failed(monkeypatch):
+ monkeypatch.setattr(azure.cognitiveservices.speech.SpeechSynthesizer, "speak_text_async", mock_speak_text_failed)
+
===========changed ref 1===========
# module: tests.conftest
+ @pytest.fixture
+ def mock_speech_cancelled(monkeypatch):
+ monkeypatch.setattr(azure.cognitiveservices.speech.SpeechSynthesizer, "speak_text_async", mock_speak_text_cancelled)
+
===========changed ref 2===========
# module: tests.conftest
+ @pytest.fixture
+ def mock_speech_success(monkeypatch):
+ monkeypatch.setattr(azure.cognitiveservices.speech.SpeechSynthesizer, "speak_text_async", mock_speak_text_success)
+
===========changed ref 3===========
# module: tests.mocks
+ class MockSynthesisResult:
+ def get(self):
+ return self.__result
+
===========changed ref 4===========
# module: tests.mocks
+ class MockSynthesisResult:
+ def __init__(self, result):
+ self.__result = result
+
===========changed ref 5===========
# module: tests.mocks
+ class MockAudioFailure:
+ def read(self):
+ return self.audio_data
+
===========changed ref 6===========
# module: tests.mocks
+ class MockAudioCancelled:
+ def read(self):
+ return self.audio_data
+
===========changed ref 7===========
# module: tests.mocks
+ class MockAudio:
+ def read(self):
+ return self.audio_data
+
===========changed ref 8===========
# module: tests.mocks
+ class MockAzureCredentialExpired(AsyncTokenCredential):
+ def __init__(self):
+ self.access_number = 0
+
===========changed ref 9===========
# module: tests.mocks
+ def mock_speak_text_success(self, text):
+ return MockSynthesisResult(MockAudio("mock_audio_data"))
+
===========changed ref 10===========
# module: tests.mocks
+ def mock_speak_text_failed(self, text):
+ return MockSynthesisResult(MockAudioFailure("mock_audio_data"))
+
===========changed ref 11===========
# module: tests.mocks
+ def mock_speak_text_cancelled(self, text):
+ return MockSynthesisResult(MockAudioCancelled("mock_audio_data"))
+
===========changed ref 12===========
# module: tests.mocks
+ class MockAudioFailure:
+ def __init__(self, audio_data):
+ self.audio_data = audio_data
+ self.reason = ResultReason.NoMatch
+
===========changed ref 13===========
# module: tests.mocks
+ class MockSpeechSynthesisCancellationDetails:
+ def __init__(self):
+ self.reason = "Canceled"
+ self.error_details = "The synthesis was canceled."
+
===========changed ref 14===========
# module: tests.mocks
+ class MockAudio:
+ def __init__(self, audio_data):
+ self.audio_data = audio_data
+ self.reason = ResultReason.SynthesizingAudioCompleted
+
===========changed ref 15===========
# module: tests.mocks
+ class MockAudioCancelled:
+ def __init__(self, audio_data):
+ self.audio_data = audio_data
+ self.reason = ResultReason.Canceled
+ self.cancellation_details = MockSpeechSynthesisCancellationDetails()
+
===========changed ref 16===========
# module: tests.mocks
+ class MockAzureCredentialExpired(AsyncTokenCredential):
+ def get_token(self, uri):
+ self.access_number += 1
+ if self.access_number == 1:
+ return MockToken("", 0, "")
+ else:
+ return MockToken("", 9999999999, "")
+
===========changed ref 17===========
# module: app.backend.config
CONFIG_OPENAI_TOKEN = "openai_token"
CONFIG_CREDENTIAL = "azure_credential"
CONFIG_ASK_APPROACH = "ask_approach"
CONFIG_ASK_VISION_APPROACH = "ask_vision_approach"
CONFIG_CHAT_VISION_APPROACH = "chat_vision_approach"
CONFIG_CHAT_APPROACH = "chat_approach"
CONFIG_BLOB_CONTAINER_CLIENT = "blob_container_client"
CONFIG_USER_UPLOAD_ENABLED = "user_upload_enabled"
CONFIG_USER_BLOB_CONTAINER_CLIENT = "user_blob_container_client"
CONFIG_AUTH_CLIENT = "auth_client"
CONFIG_GPT4V_DEPLOYED = "gpt4v_deployed"
CONFIG_SEMANTIC_RANKER_DEPLOYED = "semantic_ranker_deployed"
CONFIG_VECTOR_SEARCH_ENABLED = "vector_search_enabled"
CONFIG_SEARCH_CLIENT = "search_client"
CONFIG_OPENAI_CLIENT = "openai_client"
CONFIG_INGESTER = "ingester"
+ CONFIG_SPEECH_INPUT_ENABLED = "speech_input_enabled"
+ CONFIG_SPEECH_OUTPUT_ENABLED = "speech_output_enabled"
+ CONFIG_SPEECH_SERVICE_ID = "speech_service_id"
+ CONFIG_SPEECH_SERVICE_LOCATION = "speech_service_location"
+ CONFIG_SPEECH_SERVICE_TOKEN = "speech_service_token"
+ CONFIG_SPEECH_SERVICE_VOICE = "speech_service_voice"
|
tests.test_app/test_favicon
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
7ffcb3b95500dd741de2e6d1b70fa8073c9c3ce3
|
Add speech recognizer and synthesis on browser interface (#113)
|
<2>:<add> assert response.content_type.startswith("image")
<add> assert response.content_type.endswith("icon")
<del> assert response.content_type == "image/vnd.microsoft.icon"
|
# module: tests.test_app
@pytest.mark.asyncio
async def test_favicon(client):
<0> response = await client.get("/favicon.ico")
<1> assert response.status_code == 200
<2> assert response.content_type == "image/vnd.microsoft.icon"
<3>
|
===========unchanged ref 0===========
at: _pytest.mark.structures
MARK_GEN = MarkGenerator(_ispytest=True)
===========changed ref 0===========
# module: tests.mocks
+ class MockSynthesisResult:
+ def get(self):
+ return self.__result
+
===========changed ref 1===========
# module: tests.mocks
+ class MockSynthesisResult:
+ def __init__(self, result):
+ self.__result = result
+
===========changed ref 2===========
# module: tests.mocks
+ class MockAudioFailure:
+ def read(self):
+ return self.audio_data
+
===========changed ref 3===========
# module: tests.mocks
+ class MockAudioCancelled:
+ def read(self):
+ return self.audio_data
+
===========changed ref 4===========
# module: tests.mocks
+ class MockAudio:
+ def read(self):
+ return self.audio_data
+
===========changed ref 5===========
# module: tests.mocks
+ class MockAzureCredentialExpired(AsyncTokenCredential):
+ def __init__(self):
+ self.access_number = 0
+
===========changed ref 6===========
# module: tests.mocks
+ def mock_speak_text_success(self, text):
+ return MockSynthesisResult(MockAudio("mock_audio_data"))
+
===========changed ref 7===========
# module: tests.mocks
+ def mock_speak_text_failed(self, text):
+ return MockSynthesisResult(MockAudioFailure("mock_audio_data"))
+
===========changed ref 8===========
# module: tests.mocks
+ def mock_speak_text_cancelled(self, text):
+ return MockSynthesisResult(MockAudioCancelled("mock_audio_data"))
+
===========changed ref 9===========
# module: tests.mocks
+ class MockAudioFailure:
+ def __init__(self, audio_data):
+ self.audio_data = audio_data
+ self.reason = ResultReason.NoMatch
+
===========changed ref 10===========
# module: tests.mocks
+ class MockSpeechSynthesisCancellationDetails:
+ def __init__(self):
+ self.reason = "Canceled"
+ self.error_details = "The synthesis was canceled."
+
===========changed ref 11===========
# module: tests.mocks
+ class MockAudio:
+ def __init__(self, audio_data):
+ self.audio_data = audio_data
+ self.reason = ResultReason.SynthesizingAudioCompleted
+
===========changed ref 12===========
# module: tests.mocks
+ class MockAudioCancelled:
+ def __init__(self, audio_data):
+ self.audio_data = audio_data
+ self.reason = ResultReason.Canceled
+ self.cancellation_details = MockSpeechSynthesisCancellationDetails()
+
===========changed ref 13===========
# module: tests.conftest
+ @pytest.fixture
+ def mock_speech_failed(monkeypatch):
+ monkeypatch.setattr(azure.cognitiveservices.speech.SpeechSynthesizer, "speak_text_async", mock_speak_text_failed)
+
===========changed ref 14===========
# module: tests.conftest
+ @pytest.fixture
+ def mock_speech_success(monkeypatch):
+ monkeypatch.setattr(azure.cognitiveservices.speech.SpeechSynthesizer, "speak_text_async", mock_speak_text_success)
+
===========changed ref 15===========
# module: tests.conftest
+ @pytest.fixture
+ def mock_speech_cancelled(monkeypatch):
+ monkeypatch.setattr(azure.cognitiveservices.speech.SpeechSynthesizer, "speak_text_async", mock_speak_text_cancelled)
+
===========changed ref 16===========
# module: tests.mocks
+ class MockAzureCredentialExpired(AsyncTokenCredential):
+ def get_token(self, uri):
+ self.access_number += 1
+ if self.access_number == 1:
+ return MockToken("", 0, "")
+ else:
+ return MockToken("", 9999999999, "")
+
===========changed ref 17===========
# module: tests.conftest
+ @pytest_asyncio.fixture()
+ async def client_with_expiring_token(
+ monkeypatch,
+ mock_env,
+ mock_openai_chatcompletion,
+ mock_openai_embedding,
+ mock_acs_search,
+ mock_blob_container_client,
+ mock_compute_embeddings_call,
+ ):
+ quart_app = app.create_app()
+
+ async with quart_app.test_app() as test_app:
+ test_app.app.config.update({"TESTING": True})
+ test_app.app.config.update({"azure_credential": MockAzureCredentialExpired()})
+ mock_openai_chatcompletion(test_app.app.config[app.CONFIG_OPENAI_CLIENT])
+ mock_openai_embedding(test_app.app.config[app.CONFIG_OPENAI_CLIENT])
+ yield test_app.test_client()
+
===========changed ref 18===========
# module: app.backend.config
CONFIG_OPENAI_TOKEN = "openai_token"
CONFIG_CREDENTIAL = "azure_credential"
CONFIG_ASK_APPROACH = "ask_approach"
CONFIG_ASK_VISION_APPROACH = "ask_vision_approach"
CONFIG_CHAT_VISION_APPROACH = "chat_vision_approach"
CONFIG_CHAT_APPROACH = "chat_approach"
CONFIG_BLOB_CONTAINER_CLIENT = "blob_container_client"
CONFIG_USER_UPLOAD_ENABLED = "user_upload_enabled"
CONFIG_USER_BLOB_CONTAINER_CLIENT = "user_blob_container_client"
CONFIG_AUTH_CLIENT = "auth_client"
CONFIG_GPT4V_DEPLOYED = "gpt4v_deployed"
CONFIG_SEMANTIC_RANKER_DEPLOYED = "semantic_ranker_deployed"
CONFIG_VECTOR_SEARCH_ENABLED = "vector_search_enabled"
CONFIG_SEARCH_CLIENT = "search_client"
CONFIG_OPENAI_CLIENT = "openai_client"
CONFIG_INGESTER = "ingester"
+ CONFIG_SPEECH_INPUT_ENABLED = "speech_input_enabled"
+ CONFIG_SPEECH_OUTPUT_ENABLED = "speech_output_enabled"
+ CONFIG_SPEECH_SERVICE_ID = "speech_service_id"
+ CONFIG_SPEECH_SERVICE_LOCATION = "speech_service_location"
+ CONFIG_SPEECH_SERVICE_TOKEN = "speech_service_token"
+ CONFIG_SPEECH_SERVICE_VOICE = "speech_service_voice"
|
app.backend.app/config
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
7ffcb3b95500dd741de2e6d1b70fa8073c9c3ce3
|
Add speech recognizer and synthesis on browser interface (#113)
|
<6>:<add> "showSpeechInput": current_app.config[CONFIG_SPEECH_INPUT_ENABLED],
<add> "showSpeechOutput": current_app.config[CONFIG_SPEECH_OUTPUT_ENABLED],
|
# module: app.backend.app
@bp.route("/config", methods=["GET"])
def config():
<0> return jsonify(
<1> {
<2> "showGPT4VOptions": current_app.config[CONFIG_GPT4V_DEPLOYED],
<3> "showSemanticRankerOption": current_app.config[CONFIG_SEMANTIC_RANKER_DEPLOYED],
<4> "showVectorOption": current_app.config[CONFIG_VECTOR_SEARCH_ENABLED],
<5> "showUserUpload": current_app.config[CONFIG_USER_UPLOAD_ENABLED],
<6> }
<7> )
<8>
|
===========unchanged ref 0===========
at: app.backend.app
bp = Blueprint("routes", __name__, static_folder="static")
format_as_ndjson(r: AsyncGenerator[dict, None]) -> AsyncGenerator[str, None]
at: app.backend.app.chat
result = await approach.run(
request_json["messages"],
stream=request_json.get("stream", False),
context=context,
session_state=request_json.get("session_state"),
)
at: error
error_response(error: Exception, route: str, status_code: int=500)
===========changed ref 0===========
# module: tests.mocks
+ class MockSynthesisResult:
+ def get(self):
+ return self.__result
+
===========changed ref 1===========
# module: tests.mocks
+ class MockSynthesisResult:
+ def __init__(self, result):
+ self.__result = result
+
===========changed ref 2===========
# module: tests.mocks
+ class MockAudioFailure:
+ def read(self):
+ return self.audio_data
+
===========changed ref 3===========
# module: tests.mocks
+ class MockAudioCancelled:
+ def read(self):
+ return self.audio_data
+
===========changed ref 4===========
# module: tests.mocks
+ class MockAudio:
+ def read(self):
+ return self.audio_data
+
===========changed ref 5===========
# module: tests.mocks
+ class MockAzureCredentialExpired(AsyncTokenCredential):
+ def __init__(self):
+ self.access_number = 0
+
===========changed ref 6===========
# module: tests.mocks
+ def mock_speak_text_success(self, text):
+ return MockSynthesisResult(MockAudio("mock_audio_data"))
+
===========changed ref 7===========
# module: tests.mocks
+ def mock_speak_text_failed(self, text):
+ return MockSynthesisResult(MockAudioFailure("mock_audio_data"))
+
===========changed ref 8===========
# module: tests.mocks
+ def mock_speak_text_cancelled(self, text):
+ return MockSynthesisResult(MockAudioCancelled("mock_audio_data"))
+
===========changed ref 9===========
# module: tests.mocks
+ class MockAudioFailure:
+ def __init__(self, audio_data):
+ self.audio_data = audio_data
+ self.reason = ResultReason.NoMatch
+
===========changed ref 10===========
# module: tests.mocks
+ class MockSpeechSynthesisCancellationDetails:
+ def __init__(self):
+ self.reason = "Canceled"
+ self.error_details = "The synthesis was canceled."
+
===========changed ref 11===========
# module: tests.mocks
+ class MockAudio:
+ def __init__(self, audio_data):
+ self.audio_data = audio_data
+ self.reason = ResultReason.SynthesizingAudioCompleted
+
===========changed ref 12===========
# module: tests.mocks
+ class MockAudioCancelled:
+ def __init__(self, audio_data):
+ self.audio_data = audio_data
+ self.reason = ResultReason.Canceled
+ self.cancellation_details = MockSpeechSynthesisCancellationDetails()
+
===========changed ref 13===========
# module: tests.conftest
+ @pytest.fixture
+ def mock_speech_failed(monkeypatch):
+ monkeypatch.setattr(azure.cognitiveservices.speech.SpeechSynthesizer, "speak_text_async", mock_speak_text_failed)
+
===========changed ref 14===========
# module: tests.conftest
+ @pytest.fixture
+ def mock_speech_success(monkeypatch):
+ monkeypatch.setattr(azure.cognitiveservices.speech.SpeechSynthesizer, "speak_text_async", mock_speak_text_success)
+
===========changed ref 15===========
# module: tests.conftest
+ @pytest.fixture
+ def mock_speech_cancelled(monkeypatch):
+ monkeypatch.setattr(azure.cognitiveservices.speech.SpeechSynthesizer, "speak_text_async", mock_speak_text_cancelled)
+
===========changed ref 16===========
# module: tests.mocks
+ class MockAzureCredentialExpired(AsyncTokenCredential):
+ def get_token(self, uri):
+ self.access_number += 1
+ if self.access_number == 1:
+ return MockToken("", 0, "")
+ else:
+ return MockToken("", 9999999999, "")
+
===========changed ref 17===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_speech_request_must_be_json(client, mock_speech_success):
+ response = await client.post("/speech")
+ assert response.status_code == 415
+ result = await response.get_json()
+ assert result["error"] == "request must be json"
+
===========changed ref 18===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_speech(client, mock_speech_success):
+ response = await client.post(
+ "/speech",
+ json={
+ "text": "test",
+ },
+ )
+ assert response.status_code == 200
+ assert await response.get_data() == b"mock_audio_data"
+
===========changed ref 19===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_favicon(client):
response = await client.get("/favicon.ico")
assert response.status_code == 200
+ assert response.content_type.startswith("image")
+ assert response.content_type.endswith("icon")
- assert response.content_type == "image/vnd.microsoft.icon"
===========changed ref 20===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_speech_request_failed(client, mock_speech_failed):
+ response = await client.post(
+ "/speech",
+ json={
+ "text": "test",
+ },
+ )
+ assert response.status_code == 500
+ result = await response.get_json()
+ assert result["error"] == "Speech synthesis failed. Check logs for details."
+
===========changed ref 21===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_speech_request_cancelled(client, mock_speech_cancelled):
+ response = await client.post(
+ "/speech",
+ json={
+ "text": "test",
+ },
+ )
+ assert response.status_code == 500
+ result = await response.get_json()
+ assert result["error"] == "Speech synthesis canceled. Check logs for details."
+
===========changed ref 22===========
# module: tests.conftest
+ @pytest_asyncio.fixture()
+ async def client_with_expiring_token(
+ monkeypatch,
+ mock_env,
+ mock_openai_chatcompletion,
+ mock_openai_embedding,
+ mock_acs_search,
+ mock_blob_container_client,
+ mock_compute_embeddings_call,
+ ):
+ quart_app = app.create_app()
+
+ async with quart_app.test_app() as test_app:
+ test_app.app.config.update({"TESTING": True})
+ test_app.app.config.update({"azure_credential": MockAzureCredentialExpired()})
+ mock_openai_chatcompletion(test_app.app.config[app.CONFIG_OPENAI_CLIENT])
+ mock_openai_embedding(test_app.app.config[app.CONFIG_OPENAI_CLIENT])
+ yield test_app.test_client()
+
|
tests.e2e/live_server_url
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
7ffcb3b95500dd741de2e6d1b70fa8073c9c3ce3
|
Add speech recognizer and synthesis on browser interface (#113)
|
<0>:<add> proc = Process(target=run_server, args=(free_port,), daemon=True)
<del> proc = Process(target=lambda: uvicorn.run(app.create_app(), port=free_port), daemon=True)
|
# module: tests.e2e
@pytest.fixture()
def live_server_url(mock_env, mock_acs_search, free_port: int) -> Generator[str, None, None]:
<0> proc = Process(target=lambda: uvicorn.run(app.create_app(), port=free_port), daemon=True)
<1> proc.start()
<2> url = f"http://localhost:{free_port}/"
<3> wait_for_server_ready(url, timeout=10.0, check_interval=0.5)
<4> yield url
<5> proc.kill()
<6>
|
===========changed ref 0===========
# module: tests.mocks
+ class MockSynthesisResult:
+ def get(self):
+ return self.__result
+
===========changed ref 1===========
# module: tests.mocks
+ class MockSynthesisResult:
+ def __init__(self, result):
+ self.__result = result
+
===========changed ref 2===========
# module: tests.mocks
+ class MockAudioFailure:
+ def read(self):
+ return self.audio_data
+
===========changed ref 3===========
# module: tests.mocks
+ class MockAudioCancelled:
+ def read(self):
+ return self.audio_data
+
===========changed ref 4===========
# module: tests.mocks
+ class MockAudio:
+ def read(self):
+ return self.audio_data
+
===========changed ref 5===========
# module: tests.mocks
+ class MockAzureCredentialExpired(AsyncTokenCredential):
+ def __init__(self):
+ self.access_number = 0
+
===========changed ref 6===========
# module: tests.mocks
+ def mock_speak_text_success(self, text):
+ return MockSynthesisResult(MockAudio("mock_audio_data"))
+
===========changed ref 7===========
# module: tests.mocks
+ def mock_speak_text_failed(self, text):
+ return MockSynthesisResult(MockAudioFailure("mock_audio_data"))
+
===========changed ref 8===========
# module: tests.mocks
+ def mock_speak_text_cancelled(self, text):
+ return MockSynthesisResult(MockAudioCancelled("mock_audio_data"))
+
===========changed ref 9===========
# module: tests.mocks
+ class MockAudioFailure:
+ def __init__(self, audio_data):
+ self.audio_data = audio_data
+ self.reason = ResultReason.NoMatch
+
===========changed ref 10===========
# module: tests.mocks
+ class MockSpeechSynthesisCancellationDetails:
+ def __init__(self):
+ self.reason = "Canceled"
+ self.error_details = "The synthesis was canceled."
+
===========changed ref 11===========
# module: tests.mocks
+ class MockAudio:
+ def __init__(self, audio_data):
+ self.audio_data = audio_data
+ self.reason = ResultReason.SynthesizingAudioCompleted
+
===========changed ref 12===========
# module: tests.mocks
+ class MockAudioCancelled:
+ def __init__(self, audio_data):
+ self.audio_data = audio_data
+ self.reason = ResultReason.Canceled
+ self.cancellation_details = MockSpeechSynthesisCancellationDetails()
+
===========changed ref 13===========
# module: tests.conftest
+ @pytest.fixture
+ def mock_speech_failed(monkeypatch):
+ monkeypatch.setattr(azure.cognitiveservices.speech.SpeechSynthesizer, "speak_text_async", mock_speak_text_failed)
+
===========changed ref 14===========
# module: tests.conftest
+ @pytest.fixture
+ def mock_speech_success(monkeypatch):
+ monkeypatch.setattr(azure.cognitiveservices.speech.SpeechSynthesizer, "speak_text_async", mock_speak_text_success)
+
===========changed ref 15===========
# module: tests.conftest
+ @pytest.fixture
+ def mock_speech_cancelled(monkeypatch):
+ monkeypatch.setattr(azure.cognitiveservices.speech.SpeechSynthesizer, "speak_text_async", mock_speak_text_cancelled)
+
===========changed ref 16===========
# module: tests.mocks
+ class MockAzureCredentialExpired(AsyncTokenCredential):
+ def get_token(self, uri):
+ self.access_number += 1
+ if self.access_number == 1:
+ return MockToken("", 0, "")
+ else:
+ return MockToken("", 9999999999, "")
+
===========changed ref 17===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_speech_request_must_be_json(client, mock_speech_success):
+ response = await client.post("/speech")
+ assert response.status_code == 415
+ result = await response.get_json()
+ assert result["error"] == "request must be json"
+
===========changed ref 18===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_speech(client, mock_speech_success):
+ response = await client.post(
+ "/speech",
+ json={
+ "text": "test",
+ },
+ )
+ assert response.status_code == 200
+ assert await response.get_data() == b"mock_audio_data"
+
===========changed ref 19===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_favicon(client):
response = await client.get("/favicon.ico")
assert response.status_code == 200
+ assert response.content_type.startswith("image")
+ assert response.content_type.endswith("icon")
- assert response.content_type == "image/vnd.microsoft.icon"
===========changed ref 20===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_speech_request_failed(client, mock_speech_failed):
+ response = await client.post(
+ "/speech",
+ json={
+ "text": "test",
+ },
+ )
+ assert response.status_code == 500
+ result = await response.get_json()
+ assert result["error"] == "Speech synthesis failed. Check logs for details."
+
===========changed ref 21===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_speech_request_cancelled(client, mock_speech_cancelled):
+ response = await client.post(
+ "/speech",
+ json={
+ "text": "test",
+ },
+ )
+ assert response.status_code == 500
+ result = await response.get_json()
+ assert result["error"] == "Speech synthesis canceled. Check logs for details."
+
===========changed ref 22===========
# module: tests.conftest
+ @pytest_asyncio.fixture()
+ async def client_with_expiring_token(
+ monkeypatch,
+ mock_env,
+ mock_openai_chatcompletion,
+ mock_openai_embedding,
+ mock_acs_search,
+ mock_blob_container_client,
+ mock_compute_embeddings_call,
+ ):
+ quart_app = app.create_app()
+
+ async with quart_app.test_app() as test_app:
+ test_app.app.config.update({"TESTING": True})
+ test_app.app.config.update({"azure_credential": MockAzureCredentialExpired()})
+ mock_openai_chatcompletion(test_app.app.config[app.CONFIG_OPENAI_CLIENT])
+ mock_openai_embedding(test_app.app.config[app.CONFIG_OPENAI_CLIENT])
+ yield test_app.test_client()
+
===========changed ref 23===========
# module: app.backend.app
@bp.route("/config", methods=["GET"])
def config():
return jsonify(
{
"showGPT4VOptions": current_app.config[CONFIG_GPT4V_DEPLOYED],
"showSemanticRankerOption": current_app.config[CONFIG_SEMANTIC_RANKER_DEPLOYED],
"showVectorOption": current_app.config[CONFIG_VECTOR_SEARCH_ENABLED],
"showUserUpload": current_app.config[CONFIG_USER_UPLOAD_ENABLED],
+ "showSpeechInput": current_app.config[CONFIG_SPEECH_INPUT_ENABLED],
+ "showSpeechOutput": current_app.config[CONFIG_SPEECH_OUTPUT_ENABLED],
}
)
|
tests.e2e/test_chat
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
7ffcb3b95500dd741de2e6d1b70fa8073c9c3ce3
|
Add speech recognizer and synthesis on browser interface (#113)
|
<25>:<add> page.get_by_role("button", name="Submit question").click()
<del> page.get_by_role("button", name="Ask question button").click()
|
# module: tests.e2e
def test_chat(page: Page, live_server_url: str):
<0> # Set up a mock route to the /chat endpoint with streaming results
<1> def handle(route: Route):
<2> # Assert that session_state is specified in the request (None for now)
<3> session_state = route.request.post_data_json["session_state"]
<4> assert session_state is None
<5> # Read the JSONL from our snapshot results and return as the response
<6> f = open("tests/snapshots/test_app/test_chat_stream_text/client0/result.jsonlines")
<7> jsonl = f.read()
<8> f.close()
<9> route.fulfill(body=jsonl, status=200, headers={"Transfer-encoding": "Chunked"})
<10>
<11> page.route("*/**/chat", handle)
<12>
<13> # Check initial page state
<14> page.goto(live_server_url)
<15> expect(page).to_have_title("GPT + Enterprise data | Sample")
<16> expect(page.get_by_role("heading", name="Chat with your data")).to_be_visible()
<17> expect(page.get_by_role("button", name="Clear chat")).to_be_disabled()
<18> expect(page.get_by_role("button", name="Developer settings")).to_be_enabled()
<19>
<20> # Ask a question and wait for the message to appear
<21> page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").click()
<22> page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").fill(
<23> "Whats the dental plan?"
<24> )
<25> page.get_by_role("button", name="Ask question button").click()
<26>
<27> expect(page.get_by_text("Whats the dental plan?")).to_be_visible()
<28> expect(page.get_by_text("The capital of France is</s>
|
===========below chunk 0===========
# module: tests.e2e
def test_chat(page: Page, live_server_url: str):
# offset: 1
expect(page.get_by_role("button", name="Clear chat")).to_be_enabled()
# Show the citation document
page.get_by_text("1. Benefit_Options-2.pdf").click()
expect(page.get_by_role("tab", name="Citation")).to_be_visible()
expect(page.get_by_title("Citation")).to_be_visible()
# Show the thought process
page.get_by_label("Show thought process").click()
expect(page.get_by_title("Thought process")).to_be_visible()
expect(page.get_by_text("Generated search query")).to_be_visible()
# Show the supporting content
page.get_by_label("Show supporting content").click()
expect(page.get_by_title("Supporting content")).to_be_visible()
expect(page.get_by_role("heading", name="Benefit_Options-2.pdf")).to_be_visible()
# Clear the chat
page.get_by_role("button", name="Clear chat").click()
expect(page.get_by_text("Whats the dental plan?")).not_to_be_visible()
expect(page.get_by_text("The capital of France is Paris.")).not_to_be_visible()
expect(page.get_by_role("button", name="Clear chat")).to_be_disabled()
===========changed ref 0===========
# module: tests.e2e
@pytest.fixture()
def live_server_url(mock_env, mock_acs_search, free_port: int) -> Generator[str, None, None]:
+ proc = Process(target=run_server, args=(free_port,), daemon=True)
- proc = Process(target=lambda: uvicorn.run(app.create_app(), port=free_port), daemon=True)
proc.start()
url = f"http://localhost:{free_port}/"
wait_for_server_ready(url, timeout=10.0, check_interval=0.5)
yield url
proc.kill()
===========changed ref 1===========
# module: tests.e2e
+ def run_server(port: int):
+ with mock.patch.dict(
+ os.environ,
+ {
+ "AZURE_STORAGE_ACCOUNT": "test-storage-account",
+ "AZURE_STORAGE_CONTAINER": "test-storage-container",
+ "AZURE_STORAGE_RESOURCE_GROUP": "test-storage-rg",
+ "AZURE_SUBSCRIPTION_ID": "test-storage-subid",
+ "USE_SPEECH_INPUT_BROWSER": "false",
+ "USE_SPEECH_OUTPUT_AZURE": "false",
+ "AZURE_SEARCH_INDEX": "test-search-index",
+ "AZURE_SEARCH_SERVICE": "test-search-service",
+ "AZURE_SPEECH_SERVICE_ID": "test-id",
+ "AZURE_SPEECH_SERVICE_LOCATION": "eastus",
+ "AZURE_OPENAI_CHATGPT_MODEL": "gpt-35-turbo",
+ },
+ clear=True,
+ ):
+ uvicorn.run(app.create_app(), port=port)
+
===========changed ref 2===========
# module: tests.mocks
+ class MockSynthesisResult:
+ def get(self):
+ return self.__result
+
===========changed ref 3===========
# module: tests.mocks
+ class MockSynthesisResult:
+ def __init__(self, result):
+ self.__result = result
+
===========changed ref 4===========
# module: tests.mocks
+ class MockAudioFailure:
+ def read(self):
+ return self.audio_data
+
===========changed ref 5===========
# module: tests.mocks
+ class MockAudioCancelled:
+ def read(self):
+ return self.audio_data
+
===========changed ref 6===========
# module: tests.mocks
+ class MockAudio:
+ def read(self):
+ return self.audio_data
+
===========changed ref 7===========
# module: tests.mocks
+ class MockAzureCredentialExpired(AsyncTokenCredential):
+ def __init__(self):
+ self.access_number = 0
+
===========changed ref 8===========
# module: tests.mocks
+ def mock_speak_text_success(self, text):
+ return MockSynthesisResult(MockAudio("mock_audio_data"))
+
===========changed ref 9===========
# module: tests.mocks
+ def mock_speak_text_failed(self, text):
+ return MockSynthesisResult(MockAudioFailure("mock_audio_data"))
+
===========changed ref 10===========
# module: tests.mocks
+ def mock_speak_text_cancelled(self, text):
+ return MockSynthesisResult(MockAudioCancelled("mock_audio_data"))
+
===========changed ref 11===========
# module: tests.mocks
+ class MockAudioFailure:
+ def __init__(self, audio_data):
+ self.audio_data = audio_data
+ self.reason = ResultReason.NoMatch
+
===========changed ref 12===========
# module: tests.mocks
+ class MockSpeechSynthesisCancellationDetails:
+ def __init__(self):
+ self.reason = "Canceled"
+ self.error_details = "The synthesis was canceled."
+
===========changed ref 13===========
# module: tests.mocks
+ class MockAudio:
+ def __init__(self, audio_data):
+ self.audio_data = audio_data
+ self.reason = ResultReason.SynthesizingAudioCompleted
+
===========changed ref 14===========
# module: tests.mocks
+ class MockAudioCancelled:
+ def __init__(self, audio_data):
+ self.audio_data = audio_data
+ self.reason = ResultReason.Canceled
+ self.cancellation_details = MockSpeechSynthesisCancellationDetails()
+
===========changed ref 15===========
# module: tests.conftest
+ @pytest.fixture
+ def mock_speech_failed(monkeypatch):
+ monkeypatch.setattr(azure.cognitiveservices.speech.SpeechSynthesizer, "speak_text_async", mock_speak_text_failed)
+
===========changed ref 16===========
# module: tests.conftest
+ @pytest.fixture
+ def mock_speech_success(monkeypatch):
+ monkeypatch.setattr(azure.cognitiveservices.speech.SpeechSynthesizer, "speak_text_async", mock_speak_text_success)
+
===========changed ref 17===========
# module: tests.conftest
+ @pytest.fixture
+ def mock_speech_cancelled(monkeypatch):
+ monkeypatch.setattr(azure.cognitiveservices.speech.SpeechSynthesizer, "speak_text_async", mock_speak_text_cancelled)
+
===========changed ref 18===========
# module: tests.mocks
+ class MockAzureCredentialExpired(AsyncTokenCredential):
+ def get_token(self, uri):
+ self.access_number += 1
+ if self.access_number == 1:
+ return MockToken("", 0, "")
+ else:
+ return MockToken("", 9999999999, "")
+
===========changed ref 19===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_speech_request_must_be_json(client, mock_speech_success):
+ response = await client.post("/speech")
+ assert response.status_code == 415
+ result = await response.get_json()
+ assert result["error"] == "request must be json"
+
===========changed ref 20===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_speech(client, mock_speech_success):
+ response = await client.post(
+ "/speech",
+ json={
+ "text": "test",
+ },
+ )
+ assert response.status_code == 200
+ assert await response.get_data() == b"mock_audio_data"
+
|
tests.e2e/test_chat_customization
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
7ffcb3b95500dd741de2e6d1b70fa8073c9c3ce3
|
Add speech recognizer and synthesis on browser interface (#113)
|
# module: tests.e2e
def test_chat_customization(page: Page, live_server_url: str):
<0> # Set up a mock route to the /chat endpoint
<1> def handle(route: Route):
<2> assert route.request.post_data_json["stream"] is False
<3> overrides = route.request.post_data_json["context"]["overrides"]
<4> assert overrides["retrieval_mode"] == "vectors"
<5> assert overrides["semantic_ranker"] is False
<6> assert overrides["semantic_captions"] is True
<7> assert overrides["top"] == 1
<8> assert overrides["prompt_template"] == "You are a cat and only talk about tuna."
<9> assert overrides["exclude_category"] == "dogs"
<10> assert overrides["use_oid_security_filter"] is False
<11> assert overrides["use_groups_security_filter"] is False
<12>
<13> # Read the JSON from our snapshot results and return as the response
<14> f = open("tests/snapshots/test_app/test_chat_text/client0/result.json")
<15> json = f.read()
<16> f.close()
<17> route.fulfill(body=json, status=200)
<18>
<19> page.route("*/**/chat", handle)
<20>
<21> # Check initial page state
<22> page.goto(live_server_url)
<23> expect(page).to_have_title("GPT + Enterprise data | Sample")
<24>
<25> # Customize all the settings
<26> page.get_by_role("button", name="Developer settings").click()
<27> page.get_by_label("Override prompt template").click()
<28> page.get_by_label("Override prompt template").fill("You are a cat and only talk about tuna.")
<29> page.get_by_label("Retrieve this many search results:").click()
<30> page.get_by_label("Retrieve this many search results:").fill("1")
<31> page.get_by_label("Exclude category").click()
<32> page.get_by_label("Exclude category").fill("dogs")
<33> </s>
|
===========below chunk 0===========
# module: tests.e2e
def test_chat_customization(page: Page, live_server_url: str):
# offset: 1
page.get_by_text("Use semantic ranker for retrieval").click()
page.get_by_text("Vectors + Text (Hybrid)").click()
page.get_by_role("option", name="Vectors", exact=True).click()
page.get_by_text("Stream chat completion responses").click()
page.locator("button").filter(has_text="Close").click()
# Ask a question and wait for the message to appear
page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").click()
page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").fill(
"Whats the dental plan?"
)
page.get_by_role("button", name="Ask question button").click()
expect(page.get_by_text("Whats the dental plan?")).to_be_visible()
expect(page.get_by_text("The capital of France is Paris.")).to_be_visible()
expect(page.get_by_role("button", name="Clear chat")).to_be_enabled()
===========changed ref 0===========
# module: tests.e2e
@pytest.fixture()
def live_server_url(mock_env, mock_acs_search, free_port: int) -> Generator[str, None, None]:
+ proc = Process(target=run_server, args=(free_port,), daemon=True)
- proc = Process(target=lambda: uvicorn.run(app.create_app(), port=free_port), daemon=True)
proc.start()
url = f"http://localhost:{free_port}/"
wait_for_server_ready(url, timeout=10.0, check_interval=0.5)
yield url
proc.kill()
===========changed ref 1===========
# module: tests.e2e
+ def run_server(port: int):
+ with mock.patch.dict(
+ os.environ,
+ {
+ "AZURE_STORAGE_ACCOUNT": "test-storage-account",
+ "AZURE_STORAGE_CONTAINER": "test-storage-container",
+ "AZURE_STORAGE_RESOURCE_GROUP": "test-storage-rg",
+ "AZURE_SUBSCRIPTION_ID": "test-storage-subid",
+ "USE_SPEECH_INPUT_BROWSER": "false",
+ "USE_SPEECH_OUTPUT_AZURE": "false",
+ "AZURE_SEARCH_INDEX": "test-search-index",
+ "AZURE_SEARCH_SERVICE": "test-search-service",
+ "AZURE_SPEECH_SERVICE_ID": "test-id",
+ "AZURE_SPEECH_SERVICE_LOCATION": "eastus",
+ "AZURE_OPENAI_CHATGPT_MODEL": "gpt-35-turbo",
+ },
+ clear=True,
+ ):
+ uvicorn.run(app.create_app(), port=port)
+
===========changed ref 2===========
# module: tests.e2e
def test_chat(page: Page, live_server_url: str):
# Set up a mock route to the /chat endpoint with streaming results
def handle(route: Route):
# Assert that session_state is specified in the request (None for now)
session_state = route.request.post_data_json["session_state"]
assert session_state is None
# Read the JSONL from our snapshot results and return as the response
f = open("tests/snapshots/test_app/test_chat_stream_text/client0/result.jsonlines")
jsonl = f.read()
f.close()
route.fulfill(body=jsonl, status=200, headers={"Transfer-encoding": "Chunked"})
page.route("*/**/chat", handle)
# Check initial page state
page.goto(live_server_url)
expect(page).to_have_title("GPT + Enterprise data | Sample")
expect(page.get_by_role("heading", name="Chat with your data")).to_be_visible()
expect(page.get_by_role("button", name="Clear chat")).to_be_disabled()
expect(page.get_by_role("button", name="Developer settings")).to_be_enabled()
# Ask a question and wait for the message to appear
page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").click()
page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").fill(
"Whats the dental plan?"
)
+ page.get_by_role("button", name="Submit question").click()
- page.get_by_role("button", name="Ask question button").click()
expect(page.get_by_text("Whats the dental plan?")).to_be_visible()
expect(page.get_by_text("The capital of France is Paris.")).to_be</s>
===========changed ref 3===========
# module: tests.e2e
def test_chat(page: Page, live_server_url: str):
# offset: 1
<s>be_visible()
expect(page.get_by_text("The capital of France is Paris.")).to_be_visible()
expect(page.get_by_role("button", name="Clear chat")).to_be_enabled()
# Show the citation document
page.get_by_text("1. Benefit_Options-2.pdf").click()
expect(page.get_by_role("tab", name="Citation")).to_be_visible()
expect(page.get_by_title("Citation")).to_be_visible()
# Show the thought process
page.get_by_label("Show thought process").click()
expect(page.get_by_title("Thought process")).to_be_visible()
expect(page.get_by_text("Generated search query")).to_be_visible()
# Show the supporting content
page.get_by_label("Show supporting content").click()
expect(page.get_by_title("Supporting content")).to_be_visible()
expect(page.get_by_role("heading", name="Benefit_Options-2.pdf")).to_be_visible()
# Clear the chat
page.get_by_role("button", name="Clear chat").click()
expect(page.get_by_text("Whats the dental plan?")).not_to_be_visible()
expect(page.get_by_text("The capital of France is Paris.")).not_to_be_visible()
expect(page.get_by_role("button", name="Clear chat")).to_be_disabled()
===========changed ref 4===========
# module: tests.mocks
+ class MockSynthesisResult:
+ def get(self):
+ return self.__result
+
===========changed ref 5===========
# module: tests.mocks
+ class MockSynthesisResult:
+ def __init__(self, result):
+ self.__result = result
+
===========changed ref 6===========
# module: tests.mocks
+ class MockAudioFailure:
+ def read(self):
+ return self.audio_data
+
===========changed ref 7===========
# module: tests.mocks
+ class MockAudioCancelled:
+ def read(self):
+ return self.audio_data
+
===========changed ref 8===========
# module: tests.mocks
+ class MockAudio:
+ def read(self):
+ return self.audio_data
+
===========changed ref 9===========
# module: tests.mocks
+ class MockAzureCredentialExpired(AsyncTokenCredential):
+ def __init__(self):
+ self.access_number = 0
+
===========changed ref 10===========
# module: tests.mocks
+ def mock_speak_text_success(self, text):
+ return MockSynthesisResult(MockAudio("mock_audio_data"))
+
|
|
tests.e2e/test_chat_nonstreaming
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
7ffcb3b95500dd741de2e6d1b70fa8073c9c3ce3
|
Add speech recognizer and synthesis on browser interface (#113)
|
<23>:<add> page.get_by_label("Submit question").click()
<del> page.get_by_label("Ask question button").click()
|
# module: tests.e2e
def test_chat_nonstreaming(page: Page, live_server_url: str):
<0> # Set up a mock route to the /chat_stream endpoint
<1> def handle(route: Route):
<2> # Read the JSON from our snapshot results and return as the response
<3> f = open("tests/snapshots/test_app/test_chat_text/client0/result.json")
<4> json = f.read()
<5> f.close()
<6> route.fulfill(body=json, status=200)
<7>
<8> page.route("*/**/chat", handle)
<9>
<10> # Check initial page state
<11> page.goto(live_server_url)
<12> expect(page).to_have_title("GPT + Enterprise data | Sample")
<13> expect(page.get_by_role("button", name="Developer settings")).to_be_enabled()
<14> page.get_by_role("button", name="Developer settings").click()
<15> page.get_by_text("Stream chat completion responses").click()
<16> page.locator("button").filter(has_text="Close").click()
<17>
<18> # Ask a question and wait for the message to appear
<19> page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").click()
<20> page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").fill(
<21> "Whats the dental plan?"
<22> )
<23> page.get_by_label("Ask question button").click()
<24>
<25> expect(page.get_by_text("Whats the dental plan?")).to_be_visible()
<26> expect(page.get_by_text("The capital of France is Paris.")).to_be_visible()
<27> expect(page.get_by_role("button", name="Clear chat")).to_be_enabled()
<28>
|
===========changed ref 0===========
# module: tests.e2e
@pytest.fixture()
def live_server_url(mock_env, mock_acs_search, free_port: int) -> Generator[str, None, None]:
+ proc = Process(target=run_server, args=(free_port,), daemon=True)
- proc = Process(target=lambda: uvicorn.run(app.create_app(), port=free_port), daemon=True)
proc.start()
url = f"http://localhost:{free_port}/"
wait_for_server_ready(url, timeout=10.0, check_interval=0.5)
yield url
proc.kill()
===========changed ref 1===========
# module: tests.e2e
+ def run_server(port: int):
+ with mock.patch.dict(
+ os.environ,
+ {
+ "AZURE_STORAGE_ACCOUNT": "test-storage-account",
+ "AZURE_STORAGE_CONTAINER": "test-storage-container",
+ "AZURE_STORAGE_RESOURCE_GROUP": "test-storage-rg",
+ "AZURE_SUBSCRIPTION_ID": "test-storage-subid",
+ "USE_SPEECH_INPUT_BROWSER": "false",
+ "USE_SPEECH_OUTPUT_AZURE": "false",
+ "AZURE_SEARCH_INDEX": "test-search-index",
+ "AZURE_SEARCH_SERVICE": "test-search-service",
+ "AZURE_SPEECH_SERVICE_ID": "test-id",
+ "AZURE_SPEECH_SERVICE_LOCATION": "eastus",
+ "AZURE_OPENAI_CHATGPT_MODEL": "gpt-35-turbo",
+ },
+ clear=True,
+ ):
+ uvicorn.run(app.create_app(), port=port)
+
===========changed ref 2===========
# module: tests.e2e
def test_chat_customization(page: Page, live_server_url: str):
# Set up a mock route to the /chat endpoint
def handle(route: Route):
assert route.request.post_data_json["stream"] is False
overrides = route.request.post_data_json["context"]["overrides"]
assert overrides["retrieval_mode"] == "vectors"
assert overrides["semantic_ranker"] is False
assert overrides["semantic_captions"] is True
assert overrides["top"] == 1
assert overrides["prompt_template"] == "You are a cat and only talk about tuna."
assert overrides["exclude_category"] == "dogs"
assert overrides["use_oid_security_filter"] is False
assert overrides["use_groups_security_filter"] is False
# Read the JSON from our snapshot results and return as the response
f = open("tests/snapshots/test_app/test_chat_text/client0/result.json")
json = f.read()
f.close()
route.fulfill(body=json, status=200)
page.route("*/**/chat", handle)
# Check initial page state
page.goto(live_server_url)
expect(page).to_have_title("GPT + Enterprise data | Sample")
# Customize all the settings
page.get_by_role("button", name="Developer settings").click()
page.get_by_label("Override prompt template").click()
page.get_by_label("Override prompt template").fill("You are a cat and only talk about tuna.")
page.get_by_label("Retrieve this many search results:").click()
page.get_by_label("Retrieve this many search results:").fill("1")
page.get_by_label("Exclude category").click()
page.get_by_label("Exclude category").fill("dogs")
page.get_by_text("Use query-contextual summaries instead of whole documents").click()
page.get_by_text("Use semantic rank</s>
===========changed ref 3===========
# module: tests.e2e
def test_chat_customization(page: Page, live_server_url: str):
# offset: 1
<s>by_text("Use query-contextual summaries instead of whole documents").click()
page.get_by_text("Use semantic ranker for retrieval").click()
page.get_by_text("Vectors + Text (Hybrid)").click()
page.get_by_role("option", name="Vectors", exact=True).click()
page.get_by_text("Stream chat completion responses").click()
page.locator("button").filter(has_text="Close").click()
# Ask a question and wait for the message to appear
page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").click()
page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").fill(
"Whats the dental plan?"
)
+ page.get_by_role("button", name="Submit question").click()
- page.get_by_role("button", name="Ask question button").click()
expect(page.get_by_text("Whats the dental plan?")).to_be_visible()
expect(page.get_by_text("The capital of France is Paris.")).to_be_visible()
expect(page.get_by_role("button", name="Clear chat")).to_be_enabled()
===========changed ref 4===========
# module: tests.e2e
def test_chat(page: Page, live_server_url: str):
# Set up a mock route to the /chat endpoint with streaming results
def handle(route: Route):
# Assert that session_state is specified in the request (None for now)
session_state = route.request.post_data_json["session_state"]
assert session_state is None
# Read the JSONL from our snapshot results and return as the response
f = open("tests/snapshots/test_app/test_chat_stream_text/client0/result.jsonlines")
jsonl = f.read()
f.close()
route.fulfill(body=jsonl, status=200, headers={"Transfer-encoding": "Chunked"})
page.route("*/**/chat", handle)
# Check initial page state
page.goto(live_server_url)
expect(page).to_have_title("GPT + Enterprise data | Sample")
expect(page.get_by_role("heading", name="Chat with your data")).to_be_visible()
expect(page.get_by_role("button", name="Clear chat")).to_be_disabled()
expect(page.get_by_role("button", name="Developer settings")).to_be_enabled()
# Ask a question and wait for the message to appear
page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").click()
page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").fill(
"Whats the dental plan?"
)
+ page.get_by_role("button", name="Submit question").click()
- page.get_by_role("button", name="Ask question button").click()
expect(page.get_by_text("Whats the dental plan?")).to_be_visible()
expect(page.get_by_text("The capital of France is Paris.")).to_be</s>
|
tests.e2e/test_chat_followup_streaming
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
7ffcb3b95500dd741de2e6d1b70fa8073c9c3ce3
|
Add speech recognizer and synthesis on browser interface (#113)
|
<25>:<add> page.get_by_label("Submit question").click()
<del> page.get_by_label("Ask question button").click()
|
# module: tests.e2e
def test_chat_followup_streaming(page: Page, live_server_url: str):
<0> # Set up a mock route to the /chat_stream endpoint
<1> def handle(route: Route):
<2> overrides = route.request.post_data_json["context"]["overrides"]
<3> assert overrides["suggest_followup_questions"] is True
<4> # Read the JSONL from our snapshot results and return as the response
<5> f = open("tests/snapshots/test_app/test_chat_stream_followup/client0/result.jsonlines")
<6> jsonl = f.read()
<7> f.close()
<8> route.fulfill(body=jsonl, status=200, headers={"Transfer-encoding": "Chunked"})
<9>
<10> page.route("*/**/chat", handle)
<11>
<12> # Check initial page state
<13> page.goto(live_server_url)
<14> expect(page).to_have_title("GPT + Enterprise data | Sample")
<15> expect(page.get_by_role("button", name="Developer settings")).to_be_enabled()
<16> page.get_by_role("button", name="Developer settings").click()
<17> page.get_by_text("Suggest follow-up questions").click()
<18> page.locator("button").filter(has_text="Close").click()
<19>
<20> # Ask a question and wait for the message to appear
<21> page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").click()
<22> page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").fill(
<23> "Whats the dental plan?"
<24> )
<25> page.get_by_label("Ask question button").click()
<26>
<27> expect(page.get_by_text("Whats the dental plan?")).to_be_visible()
<28> expect(page.get_by_text("The capital of France is Paris.")).to_</s>
|
===========below chunk 0===========
# module: tests.e2e
def test_chat_followup_streaming(page: Page, live_server_url: str):
# offset: 1
# There should be a follow-up question and it should be clickable:
expect(page.get_by_text("What is the capital of Spain?")).to_be_visible()
page.get_by_text("What is the capital of Spain?").click()
# Now there should be a follow-up answer (same, since we're using same test data)
expect(page.get_by_text("The capital of France is Paris.")).to_have_count(2)
===========changed ref 0===========
# module: tests.e2e
@pytest.fixture()
def live_server_url(mock_env, mock_acs_search, free_port: int) -> Generator[str, None, None]:
+ proc = Process(target=run_server, args=(free_port,), daemon=True)
- proc = Process(target=lambda: uvicorn.run(app.create_app(), port=free_port), daemon=True)
proc.start()
url = f"http://localhost:{free_port}/"
wait_for_server_ready(url, timeout=10.0, check_interval=0.5)
yield url
proc.kill()
===========changed ref 1===========
# module: tests.e2e
+ def run_server(port: int):
+ with mock.patch.dict(
+ os.environ,
+ {
+ "AZURE_STORAGE_ACCOUNT": "test-storage-account",
+ "AZURE_STORAGE_CONTAINER": "test-storage-container",
+ "AZURE_STORAGE_RESOURCE_GROUP": "test-storage-rg",
+ "AZURE_SUBSCRIPTION_ID": "test-storage-subid",
+ "USE_SPEECH_INPUT_BROWSER": "false",
+ "USE_SPEECH_OUTPUT_AZURE": "false",
+ "AZURE_SEARCH_INDEX": "test-search-index",
+ "AZURE_SEARCH_SERVICE": "test-search-service",
+ "AZURE_SPEECH_SERVICE_ID": "test-id",
+ "AZURE_SPEECH_SERVICE_LOCATION": "eastus",
+ "AZURE_OPENAI_CHATGPT_MODEL": "gpt-35-turbo",
+ },
+ clear=True,
+ ):
+ uvicorn.run(app.create_app(), port=port)
+
===========changed ref 2===========
# module: tests.e2e
def test_chat_nonstreaming(page: Page, live_server_url: str):
# Set up a mock route to the /chat_stream endpoint
def handle(route: Route):
# Read the JSON from our snapshot results and return as the response
f = open("tests/snapshots/test_app/test_chat_text/client0/result.json")
json = f.read()
f.close()
route.fulfill(body=json, status=200)
page.route("*/**/chat", handle)
# Check initial page state
page.goto(live_server_url)
expect(page).to_have_title("GPT + Enterprise data | Sample")
expect(page.get_by_role("button", name="Developer settings")).to_be_enabled()
page.get_by_role("button", name="Developer settings").click()
page.get_by_text("Stream chat completion responses").click()
page.locator("button").filter(has_text="Close").click()
# Ask a question and wait for the message to appear
page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").click()
page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").fill(
"Whats the dental plan?"
)
+ page.get_by_label("Submit question").click()
- page.get_by_label("Ask question button").click()
expect(page.get_by_text("Whats the dental plan?")).to_be_visible()
expect(page.get_by_text("The capital of France is Paris.")).to_be_visible()
expect(page.get_by_role("button", name="Clear chat")).to_be_enabled()
===========changed ref 3===========
# module: tests.e2e
def test_chat_customization(page: Page, live_server_url: str):
# Set up a mock route to the /chat endpoint
def handle(route: Route):
assert route.request.post_data_json["stream"] is False
overrides = route.request.post_data_json["context"]["overrides"]
assert overrides["retrieval_mode"] == "vectors"
assert overrides["semantic_ranker"] is False
assert overrides["semantic_captions"] is True
assert overrides["top"] == 1
assert overrides["prompt_template"] == "You are a cat and only talk about tuna."
assert overrides["exclude_category"] == "dogs"
assert overrides["use_oid_security_filter"] is False
assert overrides["use_groups_security_filter"] is False
# Read the JSON from our snapshot results and return as the response
f = open("tests/snapshots/test_app/test_chat_text/client0/result.json")
json = f.read()
f.close()
route.fulfill(body=json, status=200)
page.route("*/**/chat", handle)
# Check initial page state
page.goto(live_server_url)
expect(page).to_have_title("GPT + Enterprise data | Sample")
# Customize all the settings
page.get_by_role("button", name="Developer settings").click()
page.get_by_label("Override prompt template").click()
page.get_by_label("Override prompt template").fill("You are a cat and only talk about tuna.")
page.get_by_label("Retrieve this many search results:").click()
page.get_by_label("Retrieve this many search results:").fill("1")
page.get_by_label("Exclude category").click()
page.get_by_label("Exclude category").fill("dogs")
page.get_by_text("Use query-contextual summaries instead of whole documents").click()
page.get_by_text("Use semantic rank</s>
===========changed ref 4===========
# module: tests.e2e
def test_chat_customization(page: Page, live_server_url: str):
# offset: 1
<s>by_text("Use query-contextual summaries instead of whole documents").click()
page.get_by_text("Use semantic ranker for retrieval").click()
page.get_by_text("Vectors + Text (Hybrid)").click()
page.get_by_role("option", name="Vectors", exact=True).click()
page.get_by_text("Stream chat completion responses").click()
page.locator("button").filter(has_text="Close").click()
# Ask a question and wait for the message to appear
page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").click()
page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").fill(
"Whats the dental plan?"
)
+ page.get_by_role("button", name="Submit question").click()
- page.get_by_role("button", name="Ask question button").click()
expect(page.get_by_text("Whats the dental plan?")).to_be_visible()
expect(page.get_by_text("The capital of France is Paris.")).to_be_visible()
expect(page.get_by_role("button", name="Clear chat")).to_be_enabled()
|
tests.e2e/test_chat_followup_nonstreaming
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
7ffcb3b95500dd741de2e6d1b70fa8073c9c3ce3
|
Add speech recognizer and synthesis on browser interface (#113)
|
<24>:<add> page.get_by_label("Submit question").click()
<del> page.get_by_label("Ask question button").click()
|
# module: tests.e2e
def test_chat_followup_nonstreaming(page: Page, live_server_url: str):
<0> # Set up a mock route to the /chat_stream endpoint
<1> def handle(route: Route):
<2> # Read the JSON from our snapshot results and return as the response
<3> f = open("tests/snapshots/test_app/test_chat_followup/client0/result.json")
<4> json = f.read()
<5> f.close()
<6> route.fulfill(body=json, status=200)
<7>
<8> page.route("*/**/chat", handle)
<9>
<10> # Check initial page state
<11> page.goto(live_server_url)
<12> expect(page).to_have_title("GPT + Enterprise data | Sample")
<13> expect(page.get_by_role("button", name="Developer settings")).to_be_enabled()
<14> page.get_by_role("button", name="Developer settings").click()
<15> page.get_by_text("Stream chat completion responses").click()
<16> page.get_by_text("Suggest follow-up questions").click()
<17> page.locator("button").filter(has_text="Close").click()
<18>
<19> # Ask a question and wait for the message to appear
<20> page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").click()
<21> page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").fill(
<22> "Whats the dental plan?"
<23> )
<24> page.get_by_label("Ask question button").click()
<25>
<26> expect(page.get_by_text("Whats the dental plan?")).to_be_visible()
<27> expect(page.get_by_text("The capital of France is Paris.")).to_be_visible()
<28>
<29> # There should be a follow-up question and it should be clickable:
<30> expect(page.get_by_</s>
|
===========below chunk 0===========
# module: tests.e2e
def test_chat_followup_nonstreaming(page: Page, live_server_url: str):
# offset: 1
page.get_by_text("What is the capital of Spain?").click()
# Now there should be a follow-up answer (same, since we're using same test data)
expect(page.get_by_text("The capital of France is Paris.")).to_have_count(2)
===========changed ref 0===========
# module: tests.e2e
@pytest.fixture()
def live_server_url(mock_env, mock_acs_search, free_port: int) -> Generator[str, None, None]:
+ proc = Process(target=run_server, args=(free_port,), daemon=True)
- proc = Process(target=lambda: uvicorn.run(app.create_app(), port=free_port), daemon=True)
proc.start()
url = f"http://localhost:{free_port}/"
wait_for_server_ready(url, timeout=10.0, check_interval=0.5)
yield url
proc.kill()
===========changed ref 1===========
# module: tests.e2e
+ def run_server(port: int):
+ with mock.patch.dict(
+ os.environ,
+ {
+ "AZURE_STORAGE_ACCOUNT": "test-storage-account",
+ "AZURE_STORAGE_CONTAINER": "test-storage-container",
+ "AZURE_STORAGE_RESOURCE_GROUP": "test-storage-rg",
+ "AZURE_SUBSCRIPTION_ID": "test-storage-subid",
+ "USE_SPEECH_INPUT_BROWSER": "false",
+ "USE_SPEECH_OUTPUT_AZURE": "false",
+ "AZURE_SEARCH_INDEX": "test-search-index",
+ "AZURE_SEARCH_SERVICE": "test-search-service",
+ "AZURE_SPEECH_SERVICE_ID": "test-id",
+ "AZURE_SPEECH_SERVICE_LOCATION": "eastus",
+ "AZURE_OPENAI_CHATGPT_MODEL": "gpt-35-turbo",
+ },
+ clear=True,
+ ):
+ uvicorn.run(app.create_app(), port=port)
+
===========changed ref 2===========
# module: tests.e2e
def test_chat_nonstreaming(page: Page, live_server_url: str):
# Set up a mock route to the /chat_stream endpoint
def handle(route: Route):
# Read the JSON from our snapshot results and return as the response
f = open("tests/snapshots/test_app/test_chat_text/client0/result.json")
json = f.read()
f.close()
route.fulfill(body=json, status=200)
page.route("*/**/chat", handle)
# Check initial page state
page.goto(live_server_url)
expect(page).to_have_title("GPT + Enterprise data | Sample")
expect(page.get_by_role("button", name="Developer settings")).to_be_enabled()
page.get_by_role("button", name="Developer settings").click()
page.get_by_text("Stream chat completion responses").click()
page.locator("button").filter(has_text="Close").click()
# Ask a question and wait for the message to appear
page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").click()
page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").fill(
"Whats the dental plan?"
)
+ page.get_by_label("Submit question").click()
- page.get_by_label("Ask question button").click()
expect(page.get_by_text("Whats the dental plan?")).to_be_visible()
expect(page.get_by_text("The capital of France is Paris.")).to_be_visible()
expect(page.get_by_role("button", name="Clear chat")).to_be_enabled()
===========changed ref 3===========
# module: tests.e2e
def test_chat_followup_streaming(page: Page, live_server_url: str):
# Set up a mock route to the /chat_stream endpoint
def handle(route: Route):
overrides = route.request.post_data_json["context"]["overrides"]
assert overrides["suggest_followup_questions"] is True
# Read the JSONL from our snapshot results and return as the response
f = open("tests/snapshots/test_app/test_chat_stream_followup/client0/result.jsonlines")
jsonl = f.read()
f.close()
route.fulfill(body=jsonl, status=200, headers={"Transfer-encoding": "Chunked"})
page.route("*/**/chat", handle)
# Check initial page state
page.goto(live_server_url)
expect(page).to_have_title("GPT + Enterprise data | Sample")
expect(page.get_by_role("button", name="Developer settings")).to_be_enabled()
page.get_by_role("button", name="Developer settings").click()
page.get_by_text("Suggest follow-up questions").click()
page.locator("button").filter(has_text="Close").click()
# Ask a question and wait for the message to appear
page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").click()
page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").fill(
"Whats the dental plan?"
)
+ page.get_by_label("Submit question").click()
- page.get_by_label("Ask question button").click()
expect(page.get_by_text("Whats the dental plan?")).to_be_visible()
expect(page.get_by_text("The capital of France is Paris.")).to_be_visible()
# There should be a</s>
===========changed ref 4===========
# module: tests.e2e
def test_chat_followup_streaming(page: Page, live_server_url: str):
# offset: 1
<s>_by_text("The capital of France is Paris.")).to_be_visible()
# There should be a follow-up question and it should be clickable:
expect(page.get_by_text("What is the capital of Spain?")).to_be_visible()
page.get_by_text("What is the capital of Spain?").click()
# Now there should be a follow-up answer (same, since we're using same test data)
expect(page.get_by_text("The capital of France is Paris.")).to_have_count(2)
|
tests.e2e/test_ask
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
7ffcb3b95500dd741de2e6d1b70fa8073c9c3ce3
|
Add speech recognizer and synthesis on browser interface (#113)
|
<19>:<add> page.get_by_label("Submit question").click()
<del> page.get_by_label("Ask question button").click()
|
# module: tests.e2e
def test_ask(page: Page, live_server_url: str):
<0> # Set up a mock route to the /ask endpoint
<1> def handle(route: Route):
<2> # Assert that session_state is specified in the request (None for now)
<3> session_state = route.request.post_data_json["session_state"]
<4> assert session_state is None
<5> # Read the JSON from our snapshot results and return as the response
<6> f = open("tests/snapshots/test_app/test_ask_rtr_hybrid/client0/result.json")
<7> json = f.read()
<8> f.close()
<9> route.fulfill(body=json, status=200)
<10>
<11> page.route("*/**/ask", handle)
<12> page.goto(live_server_url)
<13> expect(page).to_have_title("GPT + Enterprise data | Sample")
<14>
<15> page.get_by_role("link", name="Ask a question").click()
<16> page.get_by_placeholder("Example: Does my plan cover annual eye exams?").click()
<17> page.get_by_placeholder("Example: Does my plan cover annual eye exams?").fill("Whats the dental plan?")
<18> page.get_by_placeholder("Example: Does my plan cover annual eye exams?").click()
<19> page.get_by_label("Ask question button").click()
<20>
<21> expect(page.get_by_text("Whats the dental plan?")).to_be_visible()
<22> expect(page.get_by_text("The capital of France is Paris.")).to_be_visible()
<23>
|
===========changed ref 0===========
# module: tests.e2e
@pytest.fixture()
def live_server_url(mock_env, mock_acs_search, free_port: int) -> Generator[str, None, None]:
+ proc = Process(target=run_server, args=(free_port,), daemon=True)
- proc = Process(target=lambda: uvicorn.run(app.create_app(), port=free_port), daemon=True)
proc.start()
url = f"http://localhost:{free_port}/"
wait_for_server_ready(url, timeout=10.0, check_interval=0.5)
yield url
proc.kill()
===========changed ref 1===========
# module: tests.e2e
+ def run_server(port: int):
+ with mock.patch.dict(
+ os.environ,
+ {
+ "AZURE_STORAGE_ACCOUNT": "test-storage-account",
+ "AZURE_STORAGE_CONTAINER": "test-storage-container",
+ "AZURE_STORAGE_RESOURCE_GROUP": "test-storage-rg",
+ "AZURE_SUBSCRIPTION_ID": "test-storage-subid",
+ "USE_SPEECH_INPUT_BROWSER": "false",
+ "USE_SPEECH_OUTPUT_AZURE": "false",
+ "AZURE_SEARCH_INDEX": "test-search-index",
+ "AZURE_SEARCH_SERVICE": "test-search-service",
+ "AZURE_SPEECH_SERVICE_ID": "test-id",
+ "AZURE_SPEECH_SERVICE_LOCATION": "eastus",
+ "AZURE_OPENAI_CHATGPT_MODEL": "gpt-35-turbo",
+ },
+ clear=True,
+ ):
+ uvicorn.run(app.create_app(), port=port)
+
===========changed ref 2===========
# module: tests.e2e
def test_chat_nonstreaming(page: Page, live_server_url: str):
# Set up a mock route to the /chat_stream endpoint
def handle(route: Route):
# Read the JSON from our snapshot results and return as the response
f = open("tests/snapshots/test_app/test_chat_text/client0/result.json")
json = f.read()
f.close()
route.fulfill(body=json, status=200)
page.route("*/**/chat", handle)
# Check initial page state
page.goto(live_server_url)
expect(page).to_have_title("GPT + Enterprise data | Sample")
expect(page.get_by_role("button", name="Developer settings")).to_be_enabled()
page.get_by_role("button", name="Developer settings").click()
page.get_by_text("Stream chat completion responses").click()
page.locator("button").filter(has_text="Close").click()
# Ask a question and wait for the message to appear
page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").click()
page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").fill(
"Whats the dental plan?"
)
+ page.get_by_label("Submit question").click()
- page.get_by_label("Ask question button").click()
expect(page.get_by_text("Whats the dental plan?")).to_be_visible()
expect(page.get_by_text("The capital of France is Paris.")).to_be_visible()
expect(page.get_by_role("button", name="Clear chat")).to_be_enabled()
===========changed ref 3===========
# module: tests.e2e
def test_chat_followup_nonstreaming(page: Page, live_server_url: str):
# Set up a mock route to the /chat_stream endpoint
def handle(route: Route):
# Read the JSON from our snapshot results and return as the response
f = open("tests/snapshots/test_app/test_chat_followup/client0/result.json")
json = f.read()
f.close()
route.fulfill(body=json, status=200)
page.route("*/**/chat", handle)
# Check initial page state
page.goto(live_server_url)
expect(page).to_have_title("GPT + Enterprise data | Sample")
expect(page.get_by_role("button", name="Developer settings")).to_be_enabled()
page.get_by_role("button", name="Developer settings").click()
page.get_by_text("Stream chat completion responses").click()
page.get_by_text("Suggest follow-up questions").click()
page.locator("button").filter(has_text="Close").click()
# Ask a question and wait for the message to appear
page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").click()
page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").fill(
"Whats the dental plan?"
)
+ page.get_by_label("Submit question").click()
- page.get_by_label("Ask question button").click()
expect(page.get_by_text("Whats the dental plan?")).to_be_visible()
expect(page.get_by_text("The capital of France is Paris.")).to_be_visible()
# There should be a follow-up question and it should be clickable:
expect(page.get_by_text("What is the capital of Spain?")).to_</s>
===========changed ref 4===========
# module: tests.e2e
def test_chat_followup_nonstreaming(page: Page, live_server_url: str):
# offset: 1
<s> it should be clickable:
expect(page.get_by_text("What is the capital of Spain?")).to_be_visible()
page.get_by_text("What is the capital of Spain?").click()
# Now there should be a follow-up answer (same, since we're using same test data)
expect(page.get_by_text("The capital of France is Paris.")).to_have_count(2)
|
app.backend.prepdocslib.textsplitter/SentenceTextSplitter.__init__
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
23d2e38f3004195c959baae2e803a134e3320e26
|
Fix overlap percentage calculation (#1668)
|
<5>:<add> self.section_overlap = int(self.max_section_length * DEFAULT_OVERLAP_PERCENT / 100)
<del> self.section_overlap = self.max_section_length // DEFAULT_OVERLAP_PERCENT
|
# module: app.backend.prepdocslib.textsplitter
class SentenceTextSplitter(TextSplitter):
def __init__(self, has_image_embeddings: bool, max_tokens_per_section: int = 500):
<0> self.sentence_endings = STANDARD_SENTENCE_ENDINGS + CJK_SENTENCE_ENDINGS
<1> self.word_breaks = STANDARD_WORD_BREAKS + CJK_WORD_BREAKS
<2> self.max_section_length = DEFAULT_SECTION_LENGTH
<3> self.sentence_search_limit = 100
<4> self.max_tokens_per_section = max_tokens_per_section
<5> self.section_overlap = self.max_section_length // DEFAULT_OVERLAP_PERCENT
<6> self.has_image_embeddings = has_image_embeddings
<7>
|
===========unchanged ref 0===========
at: app.backend.prepdocslib.textsplitter
STANDARD_WORD_BREAKS = [",", ";", ":", " ", "(", ")", "[", "]", "{", "}", "\t", "\n"]
CJK_WORD_BREAKS = [
"、",
",",
";",
":",
"(",
")",
"【",
"】",
"「",
"」",
"『",
"』",
"〔",
"〕",
"〈",
"〉",
"《",
"》",
"〖",
"〗",
"〘",
"〙",
"〚",
"〛",
"〝",
"〞",
"〟",
"〰",
"–",
"—",
"‘",
"’",
"‚",
"‛",
"“",
"”",
"„",
"‟",
"‹",
"›",
]
STANDARD_SENTENCE_ENDINGS = [".", "!", "?"]
CJK_SENTENCE_ENDINGS = ["。", "!", "?", "‼", "⁇", "⁈", "⁉"]
DEFAULT_OVERLAP_PERCENT = 10 # See semantic search article for 10% overlap performance
DEFAULT_SECTION_LENGTH = 1000 # Roughly 400-500 tokens for English
===========changed ref 0===========
+ # module: tests.test_sentencetextsplitter
+
+
===========changed ref 1===========
<s>sentencetextsplitter
+ @pytest.mark.parametrize(
+ "actual_percentage, expected_section_overlap",
+ [
+ (100, 1000),
+ (80, 800),
+ (10.75, 107),
+ (10, 100),
+ (0, 0),
+ ],
+ )
+ def test_sentence_text_splitter_initializes_overlap_correctly(
+ actual_percentage: float, expected_section_overlap: float
+ ):
+ with patch("prepdocslib.textsplitter.DEFAULT_OVERLAP_PERCENT", actual_percentage):
+ subject = SentenceTextSplitter(False)
+ assert subject.section_overlap == expected_section_overlap
+
|
app.backend.app/config
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
306ac386573b443d4086ee097c222b80e3206311
|
feat: add low cost browser text to speech output using WebSpeechAPI (#1671)
|
<7>:<add> "showSpeechOutputBrowser": current_app.config[CONFIG_SPEECH_OUTPUT_BROWSER_ENABLED],
<add> "showSpeechOutputAzure": current_app.config[CONFIG_SPEECH_OUTPUT_AZURE_ENABLED],
<del> "showSpeechOutput": current_app.config[CONFIG_SPEECH_OUTPUT_ENABLED],
|
# module: app.backend.app
@bp.route("/config", methods=["GET"])
def config():
<0> return jsonify(
<1> {
<2> "showGPT4VOptions": current_app.config[CONFIG_GPT4V_DEPLOYED],
<3> "showSemanticRankerOption": current_app.config[CONFIG_SEMANTIC_RANKER_DEPLOYED],
<4> "showVectorOption": current_app.config[CONFIG_VECTOR_SEARCH_ENABLED],
<5> "showUserUpload": current_app.config[CONFIG_USER_UPLOAD_ENABLED],
<6> "showSpeechInput": current_app.config[CONFIG_SPEECH_INPUT_ENABLED],
<7> "showSpeechOutput": current_app.config[CONFIG_SPEECH_OUTPUT_ENABLED],
<8> }
<9> )
<10>
|
===========unchanged ref 0===========
at: app.backend.app
bp = Blueprint("routes", __name__, static_folder="static")
at: config
CONFIG_USER_UPLOAD_ENABLED = "user_upload_enabled"
CONFIG_GPT4V_DEPLOYED = "gpt4v_deployed"
CONFIG_SEMANTIC_RANKER_DEPLOYED = "semantic_ranker_deployed"
CONFIG_VECTOR_SEARCH_ENABLED = "vector_search_enabled"
CONFIG_SPEECH_INPUT_ENABLED = "speech_input_enabled"
CONFIG_SPEECH_OUTPUT_BROWSER_ENABLED = "speech_output_browser_enabled"
CONFIG_SPEECH_OUTPUT_AZURE_ENABLED = "speech_output_azure_enabled"
|
tests.e2e/test_chat_customization
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
c873b49614558093326caf5c3db2436cf349b71b
|
Add clickable help icons for developer settings (#1522)
|
<33>:<add> page.get_by_text("Use semantic captions").click()
<del>
|
# module: tests.e2e
def test_chat_customization(page: Page, live_server_url: str):
<0> # Set up a mock route to the /chat endpoint
<1> def handle(route: Route):
<2> assert route.request.post_data_json["stream"] is False
<3> overrides = route.request.post_data_json["context"]["overrides"]
<4> assert overrides["retrieval_mode"] == "vectors"
<5> assert overrides["semantic_ranker"] is False
<6> assert overrides["semantic_captions"] is True
<7> assert overrides["top"] == 1
<8> assert overrides["prompt_template"] == "You are a cat and only talk about tuna."
<9> assert overrides["exclude_category"] == "dogs"
<10> assert overrides["use_oid_security_filter"] is False
<11> assert overrides["use_groups_security_filter"] is False
<12>
<13> # Read the JSON from our snapshot results and return as the response
<14> f = open("tests/snapshots/test_app/test_chat_text/client0/result.json")
<15> json = f.read()
<16> f.close()
<17> route.fulfill(body=json, status=200)
<18>
<19> page.route("*/**/chat", handle)
<20>
<21> # Check initial page state
<22> page.goto(live_server_url)
<23> expect(page).to_have_title("GPT + Enterprise data | Sample")
<24>
<25> # Customize all the settings
<26> page.get_by_role("button", name="Developer settings").click()
<27> page.get_by_label("Override prompt template").click()
<28> page.get_by_label("Override prompt template").fill("You are a cat and only talk about tuna.")
<29> page.get_by_label("Retrieve this many search results:").click()
<30> page.get_by_label("Retrieve this many search results:").fill("1")
<31> page.get_by_label("Exclude category").click()
<32> page.get_by_label("Exclude category").fill("dogs")
<33> </s>
|
===========below chunk 0===========
# module: tests.e2e
def test_chat_customization(page: Page, live_server_url: str):
# offset: 1
page.get_by_text("Use semantic ranker for retrieval").click()
page.get_by_text("Vectors + Text (Hybrid)").click()
page.get_by_role("option", name="Vectors", exact=True).click()
page.get_by_text("Stream chat completion responses").click()
page.locator("button").filter(has_text="Close").click()
# Ask a question and wait for the message to appear
page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").click()
page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").fill(
"Whats the dental plan?"
)
page.get_by_role("button", name="Submit question").click()
expect(page.get_by_text("Whats the dental plan?")).to_be_visible()
expect(page.get_by_text("The capital of France is Paris.")).to_be_visible()
expect(page.get_by_role("button", name="Clear chat")).to_be_enabled()
===========unchanged ref 0===========
at: io.BufferedWriter
close(self) -> None
at: io.FileIO
read(self, size: int=..., /) -> bytes
at: typing.IO
__slots__ = ()
close() -> None
read(n: int=...) -> AnyStr
|
app.backend.approaches.retrievethenreadvision/RetrieveThenReadVisionApproach.run
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
dd7c1d2d17dd4c9b3909328693a936bc854e5a35
|
Upgrade to latest version of AI Chat Protocol (#1682)
|
# module: app.backend.approaches.retrievethenreadvision
class RetrieveThenReadVisionApproach(Approach):
def run(
self,
messages: list[ChatCompletionMessageParam],
- stream: bool = False, # Stream is not used in this approach
session_state: Any = None,
context: dict[str, Any] = {},
+ ) -> dict[str, Any]:
- ) -> Union[dict[str, Any], AsyncGenerator[dict[str, Any], None]]:
<0> q = messages[-1]["content"]
<1> if not isinstance(q, str):
<2> raise ValueError("The most recent message content must be a string.")
<3>
<4> overrides = context.get("overrides", {})
<5> auth_claims = context.get("auth_claims", {})
<6> has_text = overrides.get("retrieval_mode") in ["text", "hybrid", None]
<7> has_vector = overrides.get("retrieval_mode") in ["vectors", "hybrid", None]
<8> vector_fields = overrides.get("vector_fields", ["embedding"])
<9>
<10> include_gtpV_text = overrides.get("gpt4v_input") in ["textAndImages", "texts", None]
<11> include_gtpV_images = overrides.get("gpt4v_input") in ["textAndImages", "images", None]
<12>
<13> use_semantic_captions = True if overrides.get("semantic_captions") and has_text else False
<14> top = overrides.get("top", 3)
<15> minimum_search_score = overrides.get("minimum_search_score", 0.0)
<16> minimum_reranker_score = overrides.get("minimum_reranker_score", 0.0)
<17> filter = self.build_filter(overrides, auth_claims)
<18> use_semantic_ranker = overrides.get("semantic_ranker") and has_text
<19>
<20> # If retrieval mode includes vectors, compute an embedding for the query
<21>
<22> vectors = []
<23> if has_vector:
<24> </s>
|
===========below chunk 0===========
<s>.backend.approaches.retrievethenreadvision
class RetrieveThenReadVisionApproach(Approach):
def run(
self,
messages: list[ChatCompletionMessageParam],
- stream: bool = False, # Stream is not used in this approach
session_state: Any = None,
context: dict[str, Any] = {},
+ ) -> dict[str, Any]:
- ) -> Union[dict[str, Any], AsyncGenerator[dict[str, Any], None]]:
# offset: 1
vector = (
await self.compute_text_embedding(q)
if field == "embedding"
else await self.compute_image_embedding(q)
)
vectors.append(vector)
# Only keep the text query if the retrieval mode uses text, otherwise drop it
query_text = q if has_text else None
results = await self.search(
top,
query_text,
filter,
vectors,
use_semantic_ranker,
use_semantic_captions,
minimum_search_score,
minimum_reranker_score,
)
image_list: list[ChatCompletionContentPartImageParam] = []
user_content: list[ChatCompletionContentPartParam] = [{"text": q, "type": "text"}]
# Process results
sources_content = self.get_sources_content(results, use_semantic_captions, use_image_citation=True)
if include_gtpV_text:
content = "\n".join(sources_content)
user_content.append({"text": content, "type": "text"})
if include_gtpV_images:
for result in results:
url = await fetch_image(self.blob_container_client, result)
if url:
image_list.append({"image_url": url, "type": "image_url"})
user_content.extend(image_list)
response_token_limit = 1024
updated_messages = build_messages(
model</s>
===========below chunk 1===========
<s>.backend.approaches.retrievethenreadvision
class RetrieveThenReadVisionApproach(Approach):
def run(
self,
messages: list[ChatCompletionMessageParam],
- stream: bool = False, # Stream is not used in this approach
session_state: Any = None,
context: dict[str, Any] = {},
+ ) -> dict[str, Any]:
- ) -> Union[dict[str, Any], AsyncGenerator[dict[str, Any], None]]:
# offset: 2
<s>.extend(image_list)
response_token_limit = 1024
updated_messages = build_messages(
model=self.gpt4v_model,
system_prompt=overrides.get("prompt_template", self.system_chat_template_gpt4v),
new_user_content=user_content,
max_tokens=self.gpt4v_token_limit - response_token_limit,
)
chat_completion = (
await self.openai_client.chat.completions.create(
model=self.gpt4v_deployment if self.gpt4v_deployment else self.gpt4v_model,
messages=updated_messages,
temperature=overrides.get("temperature", 0.3),
max_tokens=response_token_limit,
n=1,
)
).model_dump()
data_points = {
"text": sources_content,
"images": [d["image_url"] for d in image_list],
}
extra_info = {
"data_points": data_points,
"thoughts": [
ThoughtStep(
"Search using user query",
query_text,
{
"use_semantic_captions": use_semantic_captions,
"use_semantic_ranker": use_semantic_ranker,
"top": top,
"</s>
===========below chunk 2===========
<s>.backend.approaches.retrievethenreadvision
class RetrieveThenReadVisionApproach(Approach):
def run(
self,
messages: list[ChatCompletionMessageParam],
- stream: bool = False, # Stream is not used in this approach
session_state: Any = None,
context: dict[str, Any] = {},
+ ) -> dict[str, Any]:
- ) -> Union[dict[str, Any], AsyncGenerator[dict[str, Any], None]]:
# offset: 3
<s> filter,
"vector_fields": vector_fields,
},
),
ThoughtStep(
"Search results",
[result.serialize_for_results() for result in results],
),
ThoughtStep(
"Prompt to generate answer",
[str(message) for message in updated_messages],
(
{"model": self.gpt4v_model, "deployment": self.gpt4v_deployment}
if self.gpt4v_deployment
else {"model": self.gpt4v_model}
),
),
],
}
chat_completion["choices"][0]["context"] = extra_info
chat_completion["choices"][0]["session_state"] = session_state
return chat_completion
===========unchanged ref 0===========
at: app.backend.approaches.retrievethenreadvision.RetrieveThenReadVisionApproach
system_chat_template_gpt4v = (
"You are an intelligent assistant helping analyze the Annual Financial Report of Contoso Ltd., The documents contain text, graphs, tables and images. "
+ "Each image source has the file name in the top left corner of the image with coordinates (10,10) pixels and is in the format SourceFileName:<file_name> "
+ "Each text source starts in a new line and has the file name followed by colon and the actual information "
+ "Always include the source name from the image or text for each fact you use in the response in the format: [filename] "
+ "Answer the following question using only the data provided in the sources below. "
+ "For tabular information return it as an html table. Do not return markdown format. "
+ "The text and image source can be the same file name, don't use the image title when citing the image source, only use the file name as mentioned "
+ "If you cannot answer using the sources below, say you don't know. Return just the answer without any input texts "
)
at: app.backend.approaches.retrievethenreadvision.RetrieveThenReadVisionApproach.__init__
self.blob_container_client = blob_container_client
self.openai_client = openai_client
self.gpt4v_model = gpt4v_model
self.gpt4v_token_limit = get_token_limit(gpt4v_model)
at: approaches.approach
ThoughtStep(title: str, description: Optional[Any], props: Optional[dict[str, Any]]=None)
at: approaches.approach.Approach
build_filter(overrides: dict[str, Any], auth_claims: dict[str, Any]) -> Optional[str]
|
|
tests.test_app/test_chat_handle_exception_streaming
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
dd7c1d2d17dd4c9b3909328693a936bc854e5a35
|
Upgrade to latest version of AI Chat Protocol (#1682)
|
<6>:<add> "/chat/stream",
<del> "/chat",
<7>:<add> json={"messages": [{"content": "What is the capital of France?", "role": "user"}]},
<del> json={"messages": [{"content": "What is the capital of France?", "role": "user"}], "stream": True},
|
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_handle_exception_streaming(client, monkeypatch, snapshot, caplog):
<0> chat_client = client.app.config[app.CONFIG_OPENAI_CLIENT]
<1> monkeypatch.setattr(
<2> chat_client.chat.completions, "create", mock.Mock(side_effect=ZeroDivisionError("something bad happened"))
<3> )
<4>
<5> response = await client.post(
<6> "/chat",
<7> json={"messages": [{"content": "What is the capital of France?", "role": "user"}], "stream": True},
<8> )
<9> assert response.status_code == 200
<10> assert "Exception while generating response stream: something bad happened" in caplog.text
<11> result = await response.get_data()
<12> snapshot.assert_match(result, "result.jsonlines")
<13>
|
===========changed ref 0===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_chat_stream_request_must_be_json(client):
+ response = await client.post("/chat/stream")
+ assert response.status_code == 415
+ result = await response.get_json()
+ assert result["error"] == "request must be json"
+
===========changed ref 1===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_chat_stream_handle_exception(client, monkeypatch, snapshot, caplog):
+ monkeypatch.setattr(
+ "approaches.chatreadretrieveread.ChatReadRetrieveReadApproach.run_stream",
+ mock.Mock(side_effect=ZeroDivisionError("something bad happened")),
+ )
+
+ response = await client.post(
+ "/chat/stream",
+ json={"messages": [{"content": "What is the capital of France?", "role": "user"}]},
+ )
+ assert response.status_code == 500
+ result = await response.get_json()
+ assert "Exception in /chat: something bad happened" in caplog.text
+ snapshot.assert_match(json.dumps(result, indent=4), "result.json")
+
===========changed ref 2===========
# module: app.backend.approaches.approach
class Approach(ABC):
+ def run_stream(
+ self,
+ messages: list[ChatCompletionMessageParam],
+ session_state: Any = None,
+ context: dict[str, Any] = {},
+ ) -> AsyncGenerator[dict[str, Any], None]:
+ raise NotImplementedError
+
===========changed ref 3===========
# module: app.backend.approaches.retrievethenreadvision
class RetrieveThenReadVisionApproach(Approach):
def run(
self,
messages: list[ChatCompletionMessageParam],
- stream: bool = False, # Stream is not used in this approach
session_state: Any = None,
context: dict[str, Any] = {},
+ ) -> dict[str, Any]:
- ) -> Union[dict[str, Any], AsyncGenerator[dict[str, Any], None]]:
q = messages[-1]["content"]
if not isinstance(q, str):
raise ValueError("The most recent message content must be a string.")
overrides = context.get("overrides", {})
auth_claims = context.get("auth_claims", {})
has_text = overrides.get("retrieval_mode") in ["text", "hybrid", None]
has_vector = overrides.get("retrieval_mode") in ["vectors", "hybrid", None]
vector_fields = overrides.get("vector_fields", ["embedding"])
include_gtpV_text = overrides.get("gpt4v_input") in ["textAndImages", "texts", None]
include_gtpV_images = overrides.get("gpt4v_input") in ["textAndImages", "images", None]
use_semantic_captions = True if overrides.get("semantic_captions") and has_text else False
top = overrides.get("top", 3)
minimum_search_score = overrides.get("minimum_search_score", 0.0)
minimum_reranker_score = overrides.get("minimum_reranker_score", 0.0)
filter = self.build_filter(overrides, auth_claims)
use_semantic_ranker = overrides.get("semantic_ranker") and has_text
# If retrieval mode includes vectors, compute an embedding for the query
vectors = []
if has_vector:
for field in vector_fields:
vector = (
await self.compute_text_embedding(q)</s>
===========changed ref 4===========
<s>.backend.approaches.retrievethenreadvision
class RetrieveThenReadVisionApproach(Approach):
def run(
self,
messages: list[ChatCompletionMessageParam],
- stream: bool = False, # Stream is not used in this approach
session_state: Any = None,
context: dict[str, Any] = {},
+ ) -> dict[str, Any]:
- ) -> Union[dict[str, Any], AsyncGenerator[dict[str, Any], None]]:
# offset: 1
<s>_vector:
for field in vector_fields:
vector = (
await self.compute_text_embedding(q)
if field == "embedding"
else await self.compute_image_embedding(q)
)
vectors.append(vector)
# Only keep the text query if the retrieval mode uses text, otherwise drop it
query_text = q if has_text else None
results = await self.search(
top,
query_text,
filter,
vectors,
use_semantic_ranker,
use_semantic_captions,
minimum_search_score,
minimum_reranker_score,
)
image_list: list[ChatCompletionContentPartImageParam] = []
user_content: list[ChatCompletionContentPartParam] = [{"text": q, "type": "text"}]
# Process results
sources_content = self.get_sources_content(results, use_semantic_captions, use_image_citation=True)
if include_gtpV_text:
content = "\n".join(sources_content)
user_content.append({"text": content, "type": "text"})
if include_gtpV_images:
for result in results:
url = await fetch_image(self.blob_container_client, result)
if url:
image_list.append({"image_url":</s>
===========changed ref 5===========
<s>.backend.approaches.retrievethenreadvision
class RetrieveThenReadVisionApproach(Approach):
def run(
self,
messages: list[ChatCompletionMessageParam],
- stream: bool = False, # Stream is not used in this approach
session_state: Any = None,
context: dict[str, Any] = {},
+ ) -> dict[str, Any]:
- ) -> Union[dict[str, Any], AsyncGenerator[dict[str, Any], None]]:
# offset: 2
<s> "type": "image_url"})
user_content.extend(image_list)
response_token_limit = 1024
updated_messages = build_messages(
model=self.gpt4v_model,
system_prompt=overrides.get("prompt_template", self.system_chat_template_gpt4v),
new_user_content=user_content,
max_tokens=self.gpt4v_token_limit - response_token_limit,
)
chat_completion = (
await self.openai_client.chat.completions.create(
model=self.gpt4v_deployment if self.gpt4v_deployment else self.gpt4v_model,
messages=updated_messages,
temperature=overrides.get("temperature", 0.3),
max_tokens=response_token_limit,
n=1,
)
).model_dump()
data_points = {
"text": sources_content,
"images": [d["image_url"] for d in image_list],
}
extra_info = {
"data_points": data_points,
"thoughts": [
ThoughtStep(
"Search using user query",
query_text,
{
"use_semantic_captions": use_semantic_captions,
"use_semantic_ranker": use_semantic</s>
|
tests.test_app/test_chat_handle_exception_contentsafety_streaming
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
dd7c1d2d17dd4c9b3909328693a936bc854e5a35
|
Upgrade to latest version of AI Chat Protocol (#1682)
|
<4>:<add> "/chat/stream",
<del> "/chat",
<5>:<add> json={"messages": [{"content": "How do I do something bad?", "role": "user"}]},
<del> json={"messages": [{"content": "How do I do something bad?", "role": "user"}], "stream": True},
|
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_handle_exception_contentsafety_streaming(client, monkeypatch, snapshot, caplog):
<0> chat_client = client.app.config[app.CONFIG_OPENAI_CLIENT]
<1> monkeypatch.setattr(chat_client.chat.completions, "create", mock.Mock(side_effect=filtered_response))
<2>
<3> response = await client.post(
<4> "/chat",
<5> json={"messages": [{"content": "How do I do something bad?", "role": "user"}], "stream": True},
<6> )
<7> assert response.status_code == 200
<8> assert "Exception while generating response stream: The response was filtered" in caplog.text
<9> result = await response.get_data()
<10> snapshot.assert_match(result, "result.jsonlines")
<11>
|
===========changed ref 0===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_chat_stream_request_must_be_json(client):
+ response = await client.post("/chat/stream")
+ assert response.status_code == 415
+ result = await response.get_json()
+ assert result["error"] == "request must be json"
+
===========changed ref 1===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_chat_stream_handle_exception(client, monkeypatch, snapshot, caplog):
+ monkeypatch.setattr(
+ "approaches.chatreadretrieveread.ChatReadRetrieveReadApproach.run_stream",
+ mock.Mock(side_effect=ZeroDivisionError("something bad happened")),
+ )
+
+ response = await client.post(
+ "/chat/stream",
+ json={"messages": [{"content": "What is the capital of France?", "role": "user"}]},
+ )
+ assert response.status_code == 500
+ result = await response.get_json()
+ assert "Exception in /chat: something bad happened" in caplog.text
+ snapshot.assert_match(json.dumps(result, indent=4), "result.json")
+
===========changed ref 2===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_handle_exception_streaming(client, monkeypatch, snapshot, caplog):
chat_client = client.app.config[app.CONFIG_OPENAI_CLIENT]
monkeypatch.setattr(
chat_client.chat.completions, "create", mock.Mock(side_effect=ZeroDivisionError("something bad happened"))
)
response = await client.post(
+ "/chat/stream",
- "/chat",
+ json={"messages": [{"content": "What is the capital of France?", "role": "user"}]},
- json={"messages": [{"content": "What is the capital of France?", "role": "user"}], "stream": True},
)
assert response.status_code == 200
assert "Exception while generating response stream: something bad happened" in caplog.text
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
===========changed ref 3===========
# module: app.backend.approaches.approach
class Approach(ABC):
+ def run_stream(
+ self,
+ messages: list[ChatCompletionMessageParam],
+ session_state: Any = None,
+ context: dict[str, Any] = {},
+ ) -> AsyncGenerator[dict[str, Any], None]:
+ raise NotImplementedError
+
===========changed ref 4===========
# module: app.backend.approaches.retrievethenreadvision
class RetrieveThenReadVisionApproach(Approach):
def run(
self,
messages: list[ChatCompletionMessageParam],
- stream: bool = False, # Stream is not used in this approach
session_state: Any = None,
context: dict[str, Any] = {},
+ ) -> dict[str, Any]:
- ) -> Union[dict[str, Any], AsyncGenerator[dict[str, Any], None]]:
q = messages[-1]["content"]
if not isinstance(q, str):
raise ValueError("The most recent message content must be a string.")
overrides = context.get("overrides", {})
auth_claims = context.get("auth_claims", {})
has_text = overrides.get("retrieval_mode") in ["text", "hybrid", None]
has_vector = overrides.get("retrieval_mode") in ["vectors", "hybrid", None]
vector_fields = overrides.get("vector_fields", ["embedding"])
include_gtpV_text = overrides.get("gpt4v_input") in ["textAndImages", "texts", None]
include_gtpV_images = overrides.get("gpt4v_input") in ["textAndImages", "images", None]
use_semantic_captions = True if overrides.get("semantic_captions") and has_text else False
top = overrides.get("top", 3)
minimum_search_score = overrides.get("minimum_search_score", 0.0)
minimum_reranker_score = overrides.get("minimum_reranker_score", 0.0)
filter = self.build_filter(overrides, auth_claims)
use_semantic_ranker = overrides.get("semantic_ranker") and has_text
# If retrieval mode includes vectors, compute an embedding for the query
vectors = []
if has_vector:
for field in vector_fields:
vector = (
await self.compute_text_embedding(q)</s>
===========changed ref 5===========
<s>.backend.approaches.retrievethenreadvision
class RetrieveThenReadVisionApproach(Approach):
def run(
self,
messages: list[ChatCompletionMessageParam],
- stream: bool = False, # Stream is not used in this approach
session_state: Any = None,
context: dict[str, Any] = {},
+ ) -> dict[str, Any]:
- ) -> Union[dict[str, Any], AsyncGenerator[dict[str, Any], None]]:
# offset: 1
<s>_vector:
for field in vector_fields:
vector = (
await self.compute_text_embedding(q)
if field == "embedding"
else await self.compute_image_embedding(q)
)
vectors.append(vector)
# Only keep the text query if the retrieval mode uses text, otherwise drop it
query_text = q if has_text else None
results = await self.search(
top,
query_text,
filter,
vectors,
use_semantic_ranker,
use_semantic_captions,
minimum_search_score,
minimum_reranker_score,
)
image_list: list[ChatCompletionContentPartImageParam] = []
user_content: list[ChatCompletionContentPartParam] = [{"text": q, "type": "text"}]
# Process results
sources_content = self.get_sources_content(results, use_semantic_captions, use_image_citation=True)
if include_gtpV_text:
content = "\n".join(sources_content)
user_content.append({"text": content, "type": "text"})
if include_gtpV_images:
for result in results:
url = await fetch_image(self.blob_container_client, result)
if url:
image_list.append({"image_url":</s>
|
tests.test_app/test_chat_stream_text
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
dd7c1d2d17dd4c9b3909328693a936bc854e5a35
|
Upgrade to latest version of AI Chat Protocol (#1682)
|
<1>:<add> "/chat/stream",
<del> "/chat",
<3>:<del> "stream": True,
|
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_stream_text(client, snapshot):
<0> response = await client.post(
<1> "/chat",
<2> json={
<3> "stream": True,
<4> "messages": [{"content": "What is the capital of France?", "role": "user"}],
<5> "context": {
<6> "overrides": {"retrieval_mode": "text"},
<7> },
<8> },
<9> )
<10> assert response.status_code == 200
<11> result = await response.get_data()
<12> snapshot.assert_match(result, "result.jsonlines")
<13>
|
===========changed ref 0===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_chat_stream_request_must_be_json(client):
+ response = await client.post("/chat/stream")
+ assert response.status_code == 415
+ result = await response.get_json()
+ assert result["error"] == "request must be json"
+
===========changed ref 1===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_chat_stream_handle_exception(client, monkeypatch, snapshot, caplog):
+ monkeypatch.setattr(
+ "approaches.chatreadretrieveread.ChatReadRetrieveReadApproach.run_stream",
+ mock.Mock(side_effect=ZeroDivisionError("something bad happened")),
+ )
+
+ response = await client.post(
+ "/chat/stream",
+ json={"messages": [{"content": "What is the capital of France?", "role": "user"}]},
+ )
+ assert response.status_code == 500
+ result = await response.get_json()
+ assert "Exception in /chat: something bad happened" in caplog.text
+ snapshot.assert_match(json.dumps(result, indent=4), "result.json")
+
===========changed ref 2===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_handle_exception_contentsafety_streaming(client, monkeypatch, snapshot, caplog):
chat_client = client.app.config[app.CONFIG_OPENAI_CLIENT]
monkeypatch.setattr(chat_client.chat.completions, "create", mock.Mock(side_effect=filtered_response))
response = await client.post(
+ "/chat/stream",
- "/chat",
+ json={"messages": [{"content": "How do I do something bad?", "role": "user"}]},
- json={"messages": [{"content": "How do I do something bad?", "role": "user"}], "stream": True},
)
assert response.status_code == 200
assert "Exception while generating response stream: The response was filtered" in caplog.text
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
===========changed ref 3===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_handle_exception_streaming(client, monkeypatch, snapshot, caplog):
chat_client = client.app.config[app.CONFIG_OPENAI_CLIENT]
monkeypatch.setattr(
chat_client.chat.completions, "create", mock.Mock(side_effect=ZeroDivisionError("something bad happened"))
)
response = await client.post(
+ "/chat/stream",
- "/chat",
+ json={"messages": [{"content": "What is the capital of France?", "role": "user"}]},
- json={"messages": [{"content": "What is the capital of France?", "role": "user"}], "stream": True},
)
assert response.status_code == 200
assert "Exception while generating response stream: something bad happened" in caplog.text
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
===========changed ref 4===========
# module: app.backend.approaches.approach
class Approach(ABC):
+ def run_stream(
+ self,
+ messages: list[ChatCompletionMessageParam],
+ session_state: Any = None,
+ context: dict[str, Any] = {},
+ ) -> AsyncGenerator[dict[str, Any], None]:
+ raise NotImplementedError
+
===========changed ref 5===========
# module: app.backend.approaches.retrievethenreadvision
class RetrieveThenReadVisionApproach(Approach):
def run(
self,
messages: list[ChatCompletionMessageParam],
- stream: bool = False, # Stream is not used in this approach
session_state: Any = None,
context: dict[str, Any] = {},
+ ) -> dict[str, Any]:
- ) -> Union[dict[str, Any], AsyncGenerator[dict[str, Any], None]]:
q = messages[-1]["content"]
if not isinstance(q, str):
raise ValueError("The most recent message content must be a string.")
overrides = context.get("overrides", {})
auth_claims = context.get("auth_claims", {})
has_text = overrides.get("retrieval_mode") in ["text", "hybrid", None]
has_vector = overrides.get("retrieval_mode") in ["vectors", "hybrid", None]
vector_fields = overrides.get("vector_fields", ["embedding"])
include_gtpV_text = overrides.get("gpt4v_input") in ["textAndImages", "texts", None]
include_gtpV_images = overrides.get("gpt4v_input") in ["textAndImages", "images", None]
use_semantic_captions = True if overrides.get("semantic_captions") and has_text else False
top = overrides.get("top", 3)
minimum_search_score = overrides.get("minimum_search_score", 0.0)
minimum_reranker_score = overrides.get("minimum_reranker_score", 0.0)
filter = self.build_filter(overrides, auth_claims)
use_semantic_ranker = overrides.get("semantic_ranker") and has_text
# If retrieval mode includes vectors, compute an embedding for the query
vectors = []
if has_vector:
for field in vector_fields:
vector = (
await self.compute_text_embedding(q)</s>
===========changed ref 6===========
<s>.backend.approaches.retrievethenreadvision
class RetrieveThenReadVisionApproach(Approach):
def run(
self,
messages: list[ChatCompletionMessageParam],
- stream: bool = False, # Stream is not used in this approach
session_state: Any = None,
context: dict[str, Any] = {},
+ ) -> dict[str, Any]:
- ) -> Union[dict[str, Any], AsyncGenerator[dict[str, Any], None]]:
# offset: 1
<s>_vector:
for field in vector_fields:
vector = (
await self.compute_text_embedding(q)
if field == "embedding"
else await self.compute_image_embedding(q)
)
vectors.append(vector)
# Only keep the text query if the retrieval mode uses text, otherwise drop it
query_text = q if has_text else None
results = await self.search(
top,
query_text,
filter,
vectors,
use_semantic_ranker,
use_semantic_captions,
minimum_search_score,
minimum_reranker_score,
)
image_list: list[ChatCompletionContentPartImageParam] = []
user_content: list[ChatCompletionContentPartParam] = [{"text": q, "type": "text"}]
# Process results
sources_content = self.get_sources_content(results, use_semantic_captions, use_image_citation=True)
if include_gtpV_text:
content = "\n".join(sources_content)
user_content.append({"text": content, "type": "text"})
if include_gtpV_images:
for result in results:
url = await fetch_image(self.blob_container_client, result)
if url:
image_list.append({"image_url":</s>
|
tests.test_app/test_chat_stream_text_filter
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
dd7c1d2d17dd4c9b3909328693a936bc854e5a35
|
Upgrade to latest version of AI Chat Protocol (#1682)
|
<1>:<add> "/chat/stream",
<del> "/chat",
<4>:<del> "stream": True,
|
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_stream_text_filter(auth_client, snapshot):
<0> response = await auth_client.post(
<1> "/chat",
<2> headers={"Authorization": "Bearer MockToken"},
<3> json={
<4> "stream": True,
<5> "messages": [{"content": "What is the capital of France?", "role": "user"}],
<6> "context": {
<7> "overrides": {
<8> "retrieval_mode": "text",
<9> "use_oid_security_filter": True,
<10> "use_groups_security_filter": True,
<11> "exclude_category": "excluded",
<12> }
<13> },
<14> },
<15> )
<16> assert response.status_code == 200
<17> assert (
<18> auth_client.config[app.CONFIG_SEARCH_CLIENT].filter
<19> == "category ne 'excluded' and (oids/any(g:search.in(g, 'OID_X')) or groups/any(g:search.in(g, 'GROUP_Y, GROUP_Z')))"
<20> )
<21> result = await response.get_data()
<22> snapshot.assert_match(result, "result.jsonlines")
<23>
|
===========changed ref 0===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_stream_text(client, snapshot):
response = await client.post(
+ "/chat/stream",
- "/chat",
json={
- "stream": True,
"messages": [{"content": "What is the capital of France?", "role": "user"}],
"context": {
"overrides": {"retrieval_mode": "text"},
},
},
)
assert response.status_code == 200
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
===========changed ref 1===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_chat_stream_request_must_be_json(client):
+ response = await client.post("/chat/stream")
+ assert response.status_code == 415
+ result = await response.get_json()
+ assert result["error"] == "request must be json"
+
===========changed ref 2===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_chat_stream_handle_exception(client, monkeypatch, snapshot, caplog):
+ monkeypatch.setattr(
+ "approaches.chatreadretrieveread.ChatReadRetrieveReadApproach.run_stream",
+ mock.Mock(side_effect=ZeroDivisionError("something bad happened")),
+ )
+
+ response = await client.post(
+ "/chat/stream",
+ json={"messages": [{"content": "What is the capital of France?", "role": "user"}]},
+ )
+ assert response.status_code == 500
+ result = await response.get_json()
+ assert "Exception in /chat: something bad happened" in caplog.text
+ snapshot.assert_match(json.dumps(result, indent=4), "result.json")
+
===========changed ref 3===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_handle_exception_contentsafety_streaming(client, monkeypatch, snapshot, caplog):
chat_client = client.app.config[app.CONFIG_OPENAI_CLIENT]
monkeypatch.setattr(chat_client.chat.completions, "create", mock.Mock(side_effect=filtered_response))
response = await client.post(
+ "/chat/stream",
- "/chat",
+ json={"messages": [{"content": "How do I do something bad?", "role": "user"}]},
- json={"messages": [{"content": "How do I do something bad?", "role": "user"}], "stream": True},
)
assert response.status_code == 200
assert "Exception while generating response stream: The response was filtered" in caplog.text
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
===========changed ref 4===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_handle_exception_streaming(client, monkeypatch, snapshot, caplog):
chat_client = client.app.config[app.CONFIG_OPENAI_CLIENT]
monkeypatch.setattr(
chat_client.chat.completions, "create", mock.Mock(side_effect=ZeroDivisionError("something bad happened"))
)
response = await client.post(
+ "/chat/stream",
- "/chat",
+ json={"messages": [{"content": "What is the capital of France?", "role": "user"}]},
- json={"messages": [{"content": "What is the capital of France?", "role": "user"}], "stream": True},
)
assert response.status_code == 200
assert "Exception while generating response stream: something bad happened" in caplog.text
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
===========changed ref 5===========
# module: app.backend.approaches.approach
class Approach(ABC):
+ def run_stream(
+ self,
+ messages: list[ChatCompletionMessageParam],
+ session_state: Any = None,
+ context: dict[str, Any] = {},
+ ) -> AsyncGenerator[dict[str, Any], None]:
+ raise NotImplementedError
+
===========changed ref 6===========
# module: app.backend.approaches.retrievethenreadvision
class RetrieveThenReadVisionApproach(Approach):
def run(
self,
messages: list[ChatCompletionMessageParam],
- stream: bool = False, # Stream is not used in this approach
session_state: Any = None,
context: dict[str, Any] = {},
+ ) -> dict[str, Any]:
- ) -> Union[dict[str, Any], AsyncGenerator[dict[str, Any], None]]:
q = messages[-1]["content"]
if not isinstance(q, str):
raise ValueError("The most recent message content must be a string.")
overrides = context.get("overrides", {})
auth_claims = context.get("auth_claims", {})
has_text = overrides.get("retrieval_mode") in ["text", "hybrid", None]
has_vector = overrides.get("retrieval_mode") in ["vectors", "hybrid", None]
vector_fields = overrides.get("vector_fields", ["embedding"])
include_gtpV_text = overrides.get("gpt4v_input") in ["textAndImages", "texts", None]
include_gtpV_images = overrides.get("gpt4v_input") in ["textAndImages", "images", None]
use_semantic_captions = True if overrides.get("semantic_captions") and has_text else False
top = overrides.get("top", 3)
minimum_search_score = overrides.get("minimum_search_score", 0.0)
minimum_reranker_score = overrides.get("minimum_reranker_score", 0.0)
filter = self.build_filter(overrides, auth_claims)
use_semantic_ranker = overrides.get("semantic_ranker") and has_text
# If retrieval mode includes vectors, compute an embedding for the query
vectors = []
if has_vector:
for field in vector_fields:
vector = (
await self.compute_text_embedding(q)</s>
|
tests.test_app/test_chat_with_history
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
dd7c1d2d17dd4c9b3909328693a936bc854e5a35
|
Upgrade to latest version of AI Chat Protocol (#1682)
|
<18>:<add> assert thought_contains_text(result["context"]["thoughts"][3], "performance review")
<del> assert thought_contains_text(result["choices"][0]["context"]["thoughts"][3], "performance review")
|
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_with_history(client, snapshot):
<0> response = await client.post(
<1> "/chat",
<2> json={
<3> "messages": [
<4> {"content": "What happens in a performance review?", "role": "user"},
<5> {
<6> "content": "During a performance review, employees will receive feedback on their performance over the past year, including both successes and areas for improvement. The feedback will be provided by the employee's supervisor and is intended to help the employee develop and grow in their role [employee_handbook-3.pdf]. The review is a two-way dialogue between the employee and their manager, so employees are encouraged to be honest and open during the process [employee_handbook-3.pdf]. The employee will also have the opportunity to discuss their goals and objectives for the upcoming year [employee_handbook-3.pdf]. A written summary of the performance review will be provided to the employee, which will include a rating of their performance, feedback, and goals and objectives for the upcoming year [employee_handbook-3.pdf].",
<7> "role": "assistant",
<8> },
<9> {"content": "Is dental covered?", "role": "user"},
<10> ],
<11> "context": {
<12> "overrides": {"retrieval_mode": "text"},
<13> },
<14> },
<15> )
<16> assert response.status_code == 200
<17> result = await response.get_json()
<18> assert thought_contains_text(result["choices"][0]["context"]["thoughts"][3], "performance review")
<19> snapshot.assert_match(json.dumps(result, indent=4), "result.json")
<20>
|
===========changed ref 0===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_stream_text(client, snapshot):
response = await client.post(
+ "/chat/stream",
- "/chat",
json={
- "stream": True,
"messages": [{"content": "What is the capital of France?", "role": "user"}],
"context": {
"overrides": {"retrieval_mode": "text"},
},
},
)
assert response.status_code == 200
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
===========changed ref 1===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_stream_text_filter(auth_client, snapshot):
response = await auth_client.post(
+ "/chat/stream",
- "/chat",
headers={"Authorization": "Bearer MockToken"},
json={
- "stream": True,
"messages": [{"content": "What is the capital of France?", "role": "user"}],
"context": {
"overrides": {
"retrieval_mode": "text",
"use_oid_security_filter": True,
"use_groups_security_filter": True,
"exclude_category": "excluded",
}
},
},
)
assert response.status_code == 200
assert (
auth_client.config[app.CONFIG_SEARCH_CLIENT].filter
== "category ne 'excluded' and (oids/any(g:search.in(g, 'OID_X')) or groups/any(g:search.in(g, 'GROUP_Y, GROUP_Z')))"
)
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
===========changed ref 2===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_chat_stream_request_must_be_json(client):
+ response = await client.post("/chat/stream")
+ assert response.status_code == 415
+ result = await response.get_json()
+ assert result["error"] == "request must be json"
+
===========changed ref 3===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_chat_stream_handle_exception(client, monkeypatch, snapshot, caplog):
+ monkeypatch.setattr(
+ "approaches.chatreadretrieveread.ChatReadRetrieveReadApproach.run_stream",
+ mock.Mock(side_effect=ZeroDivisionError("something bad happened")),
+ )
+
+ response = await client.post(
+ "/chat/stream",
+ json={"messages": [{"content": "What is the capital of France?", "role": "user"}]},
+ )
+ assert response.status_code == 500
+ result = await response.get_json()
+ assert "Exception in /chat: something bad happened" in caplog.text
+ snapshot.assert_match(json.dumps(result, indent=4), "result.json")
+
===========changed ref 4===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_handle_exception_contentsafety_streaming(client, monkeypatch, snapshot, caplog):
chat_client = client.app.config[app.CONFIG_OPENAI_CLIENT]
monkeypatch.setattr(chat_client.chat.completions, "create", mock.Mock(side_effect=filtered_response))
response = await client.post(
+ "/chat/stream",
- "/chat",
+ json={"messages": [{"content": "How do I do something bad?", "role": "user"}]},
- json={"messages": [{"content": "How do I do something bad?", "role": "user"}], "stream": True},
)
assert response.status_code == 200
assert "Exception while generating response stream: The response was filtered" in caplog.text
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
===========changed ref 5===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_handle_exception_streaming(client, monkeypatch, snapshot, caplog):
chat_client = client.app.config[app.CONFIG_OPENAI_CLIENT]
monkeypatch.setattr(
chat_client.chat.completions, "create", mock.Mock(side_effect=ZeroDivisionError("something bad happened"))
)
response = await client.post(
+ "/chat/stream",
- "/chat",
+ json={"messages": [{"content": "What is the capital of France?", "role": "user"}]},
- json={"messages": [{"content": "What is the capital of France?", "role": "user"}], "stream": True},
)
assert response.status_code == 200
assert "Exception while generating response stream: something bad happened" in caplog.text
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
===========changed ref 6===========
# module: app.backend.approaches.approach
class Approach(ABC):
+ def run_stream(
+ self,
+ messages: list[ChatCompletionMessageParam],
+ session_state: Any = None,
+ context: dict[str, Any] = {},
+ ) -> AsyncGenerator[dict[str, Any], None]:
+ raise NotImplementedError
+
===========changed ref 7===========
# module: app.backend.approaches.retrievethenreadvision
class RetrieveThenReadVisionApproach(Approach):
def run(
self,
messages: list[ChatCompletionMessageParam],
- stream: bool = False, # Stream is not used in this approach
session_state: Any = None,
context: dict[str, Any] = {},
+ ) -> dict[str, Any]:
- ) -> Union[dict[str, Any], AsyncGenerator[dict[str, Any], None]]:
q = messages[-1]["content"]
if not isinstance(q, str):
raise ValueError("The most recent message content must be a string.")
overrides = context.get("overrides", {})
auth_claims = context.get("auth_claims", {})
has_text = overrides.get("retrieval_mode") in ["text", "hybrid", None]
has_vector = overrides.get("retrieval_mode") in ["vectors", "hybrid", None]
vector_fields = overrides.get("vector_fields", ["embedding"])
include_gtpV_text = overrides.get("gpt4v_input") in ["textAndImages", "texts", None]
include_gtpV_images = overrides.get("gpt4v_input") in ["textAndImages", "images", None]
use_semantic_captions = True if overrides.get("semantic_captions") and has_text else False
top = overrides.get("top", 3)
minimum_search_score = overrides.get("minimum_search_score", 0.0)
minimum_reranker_score = overrides.get("minimum_reranker_score", 0.0)
filter = self.build_filter(overrides, auth_claims)
use_semantic_ranker = overrides.get("semantic_ranker") and has_text
# If retrieval mode includes vectors, compute an embedding for the query
vectors = []
if has_vector:
for field in vector_fields:
vector = (
await self.compute_text_embedding(q)</s>
|
tests.test_app/test_chat_with_long_history
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
dd7c1d2d17dd4c9b3909328693a936bc854e5a35
|
Upgrade to latest version of AI Chat Protocol (#1682)
|
<22>:<add> assert not thought_contains_text(result["context"]["thoughts"][3], "Is there a dress code?")
<del> assert not thought_contains_text(result["choices"][0]["context"]["thoughts"][3], "Is there a dress code?")
|
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_with_long_history(client, snapshot, caplog):
<0> """This test makes sure that the history is truncated to max tokens minus 1024."""
<1> caplog.set_level(logging.DEBUG)
<2> response = await client.post(
<3> "/chat",
<4> json={
<5> "messages": [
<6> {"role": "user", "content": "Is there a dress code?"}, # 9 tokens
<7> {
<8> "role": "assistant",
<9> "content": "Yes, there is a dress code at Contoso Electronics. Look sharp! [employee_handbook-1.pdf]"
<10> * 150,
<11> }, # 3900 tokens
<12> {"role": "user", "content": "What does a product manager do?"}, # 10 tokens
<13> ],
<14> "context": {
<15> "overrides": {"retrieval_mode": "text"},
<16> },
<17> },
<18> )
<19> assert response.status_code == 200
<20> result = await response.get_json()
<21> # Assert that it doesn't find the first message, since it wouldn't fit in the max tokens.
<22> assert not thought_contains_text(result["choices"][0]["context"]["thoughts"][3], "Is there a dress code?")
<23> assert "Reached max tokens" in caplog.text
<24> snapshot.assert_match(json.dumps(result, indent=4), "result.json")
<25>
|
===========changed ref 0===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_stream_text(client, snapshot):
response = await client.post(
+ "/chat/stream",
- "/chat",
json={
- "stream": True,
"messages": [{"content": "What is the capital of France?", "role": "user"}],
"context": {
"overrides": {"retrieval_mode": "text"},
},
},
)
assert response.status_code == 200
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
===========changed ref 1===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_stream_text_filter(auth_client, snapshot):
response = await auth_client.post(
+ "/chat/stream",
- "/chat",
headers={"Authorization": "Bearer MockToken"},
json={
- "stream": True,
"messages": [{"content": "What is the capital of France?", "role": "user"}],
"context": {
"overrides": {
"retrieval_mode": "text",
"use_oid_security_filter": True,
"use_groups_security_filter": True,
"exclude_category": "excluded",
}
},
},
)
assert response.status_code == 200
assert (
auth_client.config[app.CONFIG_SEARCH_CLIENT].filter
== "category ne 'excluded' and (oids/any(g:search.in(g, 'OID_X')) or groups/any(g:search.in(g, 'GROUP_Y, GROUP_Z')))"
)
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
===========changed ref 2===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_chat_stream_request_must_be_json(client):
+ response = await client.post("/chat/stream")
+ assert response.status_code == 415
+ result = await response.get_json()
+ assert result["error"] == "request must be json"
+
===========changed ref 3===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_with_history(client, snapshot):
response = await client.post(
"/chat",
json={
"messages": [
{"content": "What happens in a performance review?", "role": "user"},
{
"content": "During a performance review, employees will receive feedback on their performance over the past year, including both successes and areas for improvement. The feedback will be provided by the employee's supervisor and is intended to help the employee develop and grow in their role [employee_handbook-3.pdf]. The review is a two-way dialogue between the employee and their manager, so employees are encouraged to be honest and open during the process [employee_handbook-3.pdf]. The employee will also have the opportunity to discuss their goals and objectives for the upcoming year [employee_handbook-3.pdf]. A written summary of the performance review will be provided to the employee, which will include a rating of their performance, feedback, and goals and objectives for the upcoming year [employee_handbook-3.pdf].",
"role": "assistant",
},
{"content": "Is dental covered?", "role": "user"},
],
"context": {
"overrides": {"retrieval_mode": "text"},
},
},
)
assert response.status_code == 200
result = await response.get_json()
+ assert thought_contains_text(result["context"]["thoughts"][3], "performance review")
- assert thought_contains_text(result["choices"][0]["context"]["thoughts"][3], "performance review")
snapshot.assert_match(json.dumps(result, indent=4), "result.json")
===========changed ref 4===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_chat_stream_handle_exception(client, monkeypatch, snapshot, caplog):
+ monkeypatch.setattr(
+ "approaches.chatreadretrieveread.ChatReadRetrieveReadApproach.run_stream",
+ mock.Mock(side_effect=ZeroDivisionError("something bad happened")),
+ )
+
+ response = await client.post(
+ "/chat/stream",
+ json={"messages": [{"content": "What is the capital of France?", "role": "user"}]},
+ )
+ assert response.status_code == 500
+ result = await response.get_json()
+ assert "Exception in /chat: something bad happened" in caplog.text
+ snapshot.assert_match(json.dumps(result, indent=4), "result.json")
+
===========changed ref 5===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_handle_exception_contentsafety_streaming(client, monkeypatch, snapshot, caplog):
chat_client = client.app.config[app.CONFIG_OPENAI_CLIENT]
monkeypatch.setattr(chat_client.chat.completions, "create", mock.Mock(side_effect=filtered_response))
response = await client.post(
+ "/chat/stream",
- "/chat",
+ json={"messages": [{"content": "How do I do something bad?", "role": "user"}]},
- json={"messages": [{"content": "How do I do something bad?", "role": "user"}], "stream": True},
)
assert response.status_code == 200
assert "Exception while generating response stream: The response was filtered" in caplog.text
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
===========changed ref 6===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_handle_exception_streaming(client, monkeypatch, snapshot, caplog):
chat_client = client.app.config[app.CONFIG_OPENAI_CLIENT]
monkeypatch.setattr(
chat_client.chat.completions, "create", mock.Mock(side_effect=ZeroDivisionError("something bad happened"))
)
response = await client.post(
+ "/chat/stream",
- "/chat",
+ json={"messages": [{"content": "What is the capital of France?", "role": "user"}]},
- json={"messages": [{"content": "What is the capital of France?", "role": "user"}], "stream": True},
)
assert response.status_code == 200
assert "Exception while generating response stream: something bad happened" in caplog.text
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
===========changed ref 7===========
# module: app.backend.approaches.approach
class Approach(ABC):
+ def run_stream(
+ self,
+ messages: list[ChatCompletionMessageParam],
+ session_state: Any = None,
+ context: dict[str, Any] = {},
+ ) -> AsyncGenerator[dict[str, Any], None]:
+ raise NotImplementedError
+
|
tests.test_app/test_chat_stream_session_state_persists
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
dd7c1d2d17dd4c9b3909328693a936bc854e5a35
|
Upgrade to latest version of AI Chat Protocol (#1682)
|
<1>:<add> "/chat/stream",
<del> "/chat",
<7>:<del> "stream": True,
|
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_stream_session_state_persists(client, snapshot):
<0> response = await client.post(
<1> "/chat",
<2> json={
<3> "messages": [{"content": "What is the capital of France?", "role": "user"}],
<4> "context": {
<5> "overrides": {"retrieval_mode": "text"},
<6> },
<7> "stream": True,
<8> "session_state": {"conversation_id": 1234},
<9> },
<10> )
<11> assert response.status_code == 200
<12> result = await response.get_data()
<13> snapshot.assert_match(result, "result.jsonlines")
<14>
|
===========changed ref 0===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_stream_text(client, snapshot):
response = await client.post(
+ "/chat/stream",
- "/chat",
json={
- "stream": True,
"messages": [{"content": "What is the capital of France?", "role": "user"}],
"context": {
"overrides": {"retrieval_mode": "text"},
},
},
)
assert response.status_code == 200
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
===========changed ref 1===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_stream_text_filter(auth_client, snapshot):
response = await auth_client.post(
+ "/chat/stream",
- "/chat",
headers={"Authorization": "Bearer MockToken"},
json={
- "stream": True,
"messages": [{"content": "What is the capital of France?", "role": "user"}],
"context": {
"overrides": {
"retrieval_mode": "text",
"use_oid_security_filter": True,
"use_groups_security_filter": True,
"exclude_category": "excluded",
}
},
},
)
assert response.status_code == 200
assert (
auth_client.config[app.CONFIG_SEARCH_CLIENT].filter
== "category ne 'excluded' and (oids/any(g:search.in(g, 'OID_X')) or groups/any(g:search.in(g, 'GROUP_Y, GROUP_Z')))"
)
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
===========changed ref 2===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_with_long_history(client, snapshot, caplog):
"""This test makes sure that the history is truncated to max tokens minus 1024."""
caplog.set_level(logging.DEBUG)
response = await client.post(
"/chat",
json={
"messages": [
{"role": "user", "content": "Is there a dress code?"}, # 9 tokens
{
"role": "assistant",
"content": "Yes, there is a dress code at Contoso Electronics. Look sharp! [employee_handbook-1.pdf]"
* 150,
}, # 3900 tokens
{"role": "user", "content": "What does a product manager do?"}, # 10 tokens
],
"context": {
"overrides": {"retrieval_mode": "text"},
},
},
)
assert response.status_code == 200
result = await response.get_json()
# Assert that it doesn't find the first message, since it wouldn't fit in the max tokens.
+ assert not thought_contains_text(result["context"]["thoughts"][3], "Is there a dress code?")
- assert not thought_contains_text(result["choices"][0]["context"]["thoughts"][3], "Is there a dress code?")
assert "Reached max tokens" in caplog.text
snapshot.assert_match(json.dumps(result, indent=4), "result.json")
===========changed ref 3===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_chat_stream_request_must_be_json(client):
+ response = await client.post("/chat/stream")
+ assert response.status_code == 415
+ result = await response.get_json()
+ assert result["error"] == "request must be json"
+
===========changed ref 4===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_with_history(client, snapshot):
response = await client.post(
"/chat",
json={
"messages": [
{"content": "What happens in a performance review?", "role": "user"},
{
"content": "During a performance review, employees will receive feedback on their performance over the past year, including both successes and areas for improvement. The feedback will be provided by the employee's supervisor and is intended to help the employee develop and grow in their role [employee_handbook-3.pdf]. The review is a two-way dialogue between the employee and their manager, so employees are encouraged to be honest and open during the process [employee_handbook-3.pdf]. The employee will also have the opportunity to discuss their goals and objectives for the upcoming year [employee_handbook-3.pdf]. A written summary of the performance review will be provided to the employee, which will include a rating of their performance, feedback, and goals and objectives for the upcoming year [employee_handbook-3.pdf].",
"role": "assistant",
},
{"content": "Is dental covered?", "role": "user"},
],
"context": {
"overrides": {"retrieval_mode": "text"},
},
},
)
assert response.status_code == 200
result = await response.get_json()
+ assert thought_contains_text(result["context"]["thoughts"][3], "performance review")
- assert thought_contains_text(result["choices"][0]["context"]["thoughts"][3], "performance review")
snapshot.assert_match(json.dumps(result, indent=4), "result.json")
===========changed ref 5===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_chat_stream_handle_exception(client, monkeypatch, snapshot, caplog):
+ monkeypatch.setattr(
+ "approaches.chatreadretrieveread.ChatReadRetrieveReadApproach.run_stream",
+ mock.Mock(side_effect=ZeroDivisionError("something bad happened")),
+ )
+
+ response = await client.post(
+ "/chat/stream",
+ json={"messages": [{"content": "What is the capital of France?", "role": "user"}]},
+ )
+ assert response.status_code == 500
+ result = await response.get_json()
+ assert "Exception in /chat: something bad happened" in caplog.text
+ snapshot.assert_match(json.dumps(result, indent=4), "result.json")
+
===========changed ref 6===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_handle_exception_contentsafety_streaming(client, monkeypatch, snapshot, caplog):
chat_client = client.app.config[app.CONFIG_OPENAI_CLIENT]
monkeypatch.setattr(chat_client.chat.completions, "create", mock.Mock(side_effect=filtered_response))
response = await client.post(
+ "/chat/stream",
- "/chat",
+ json={"messages": [{"content": "How do I do something bad?", "role": "user"}]},
- json={"messages": [{"content": "How do I do something bad?", "role": "user"}], "stream": True},
)
assert response.status_code == 200
assert "Exception while generating response stream: The response was filtered" in caplog.text
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
|
tests.test_app/test_chat_followup
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
dd7c1d2d17dd4c9b3909328693a936bc854e5a35
|
Upgrade to latest version of AI Chat Protocol (#1682)
|
<11>:<add> assert result["context"]["followup_questions"][0] == "What is the capital of Spain?"
<del> assert result["choices"][0]["context"]["followup_questions"][0] == "What is the capital of Spain?"
|
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_followup(client, snapshot):
<0> response = await client.post(
<1> "/chat",
<2> json={
<3> "messages": [{"content": "What is the capital of France?", "role": "user"}],
<4> "context": {
<5> "overrides": {"suggest_followup_questions": True},
<6> },
<7> },
<8> )
<9> assert response.status_code == 200
<10> result = await response.get_json()
<11> assert result["choices"][0]["context"]["followup_questions"][0] == "What is the capital of Spain?"
<12>
<13> snapshot.assert_match(json.dumps(result, indent=4), "result.json")
<14>
|
===========changed ref 0===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_stream_session_state_persists(client, snapshot):
response = await client.post(
+ "/chat/stream",
- "/chat",
json={
"messages": [{"content": "What is the capital of France?", "role": "user"}],
"context": {
"overrides": {"retrieval_mode": "text"},
},
- "stream": True,
"session_state": {"conversation_id": 1234},
},
)
assert response.status_code == 200
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
===========changed ref 1===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_stream_text(client, snapshot):
response = await client.post(
+ "/chat/stream",
- "/chat",
json={
- "stream": True,
"messages": [{"content": "What is the capital of France?", "role": "user"}],
"context": {
"overrides": {"retrieval_mode": "text"},
},
},
)
assert response.status_code == 200
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
===========changed ref 2===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_stream_text_filter(auth_client, snapshot):
response = await auth_client.post(
+ "/chat/stream",
- "/chat",
headers={"Authorization": "Bearer MockToken"},
json={
- "stream": True,
"messages": [{"content": "What is the capital of France?", "role": "user"}],
"context": {
"overrides": {
"retrieval_mode": "text",
"use_oid_security_filter": True,
"use_groups_security_filter": True,
"exclude_category": "excluded",
}
},
},
)
assert response.status_code == 200
assert (
auth_client.config[app.CONFIG_SEARCH_CLIENT].filter
== "category ne 'excluded' and (oids/any(g:search.in(g, 'OID_X')) or groups/any(g:search.in(g, 'GROUP_Y, GROUP_Z')))"
)
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
===========changed ref 3===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_with_long_history(client, snapshot, caplog):
"""This test makes sure that the history is truncated to max tokens minus 1024."""
caplog.set_level(logging.DEBUG)
response = await client.post(
"/chat",
json={
"messages": [
{"role": "user", "content": "Is there a dress code?"}, # 9 tokens
{
"role": "assistant",
"content": "Yes, there is a dress code at Contoso Electronics. Look sharp! [employee_handbook-1.pdf]"
* 150,
}, # 3900 tokens
{"role": "user", "content": "What does a product manager do?"}, # 10 tokens
],
"context": {
"overrides": {"retrieval_mode": "text"},
},
},
)
assert response.status_code == 200
result = await response.get_json()
# Assert that it doesn't find the first message, since it wouldn't fit in the max tokens.
+ assert not thought_contains_text(result["context"]["thoughts"][3], "Is there a dress code?")
- assert not thought_contains_text(result["choices"][0]["context"]["thoughts"][3], "Is there a dress code?")
assert "Reached max tokens" in caplog.text
snapshot.assert_match(json.dumps(result, indent=4), "result.json")
===========changed ref 4===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_chat_stream_request_must_be_json(client):
+ response = await client.post("/chat/stream")
+ assert response.status_code == 415
+ result = await response.get_json()
+ assert result["error"] == "request must be json"
+
===========changed ref 5===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_with_history(client, snapshot):
response = await client.post(
"/chat",
json={
"messages": [
{"content": "What happens in a performance review?", "role": "user"},
{
"content": "During a performance review, employees will receive feedback on their performance over the past year, including both successes and areas for improvement. The feedback will be provided by the employee's supervisor and is intended to help the employee develop and grow in their role [employee_handbook-3.pdf]. The review is a two-way dialogue between the employee and their manager, so employees are encouraged to be honest and open during the process [employee_handbook-3.pdf]. The employee will also have the opportunity to discuss their goals and objectives for the upcoming year [employee_handbook-3.pdf]. A written summary of the performance review will be provided to the employee, which will include a rating of their performance, feedback, and goals and objectives for the upcoming year [employee_handbook-3.pdf].",
"role": "assistant",
},
{"content": "Is dental covered?", "role": "user"},
],
"context": {
"overrides": {"retrieval_mode": "text"},
},
},
)
assert response.status_code == 200
result = await response.get_json()
+ assert thought_contains_text(result["context"]["thoughts"][3], "performance review")
- assert thought_contains_text(result["choices"][0]["context"]["thoughts"][3], "performance review")
snapshot.assert_match(json.dumps(result, indent=4), "result.json")
===========changed ref 6===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_chat_stream_handle_exception(client, monkeypatch, snapshot, caplog):
+ monkeypatch.setattr(
+ "approaches.chatreadretrieveread.ChatReadRetrieveReadApproach.run_stream",
+ mock.Mock(side_effect=ZeroDivisionError("something bad happened")),
+ )
+
+ response = await client.post(
+ "/chat/stream",
+ json={"messages": [{"content": "What is the capital of France?", "role": "user"}]},
+ )
+ assert response.status_code == 500
+ result = await response.get_json()
+ assert "Exception in /chat: something bad happened" in caplog.text
+ snapshot.assert_match(json.dumps(result, indent=4), "result.json")
+
|
tests.test_app/test_chat_stream_followup
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
dd7c1d2d17dd4c9b3909328693a936bc854e5a35
|
Upgrade to latest version of AI Chat Protocol (#1682)
|
<1>:<add> "/chat/stream",
<del> "/chat",
<3>:<del> "stream": True,
|
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_stream_followup(client, snapshot):
<0> response = await client.post(
<1> "/chat",
<2> json={
<3> "stream": True,
<4> "messages": [{"content": "What is the capital of France?", "role": "user"}],
<5> "context": {
<6> "overrides": {"suggest_followup_questions": True},
<7> },
<8> },
<9> )
<10> assert response.status_code == 200
<11> result = await response.get_data()
<12> snapshot.assert_match(result, "result.jsonlines")
<13>
|
===========changed ref 0===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_stream_session_state_persists(client, snapshot):
response = await client.post(
+ "/chat/stream",
- "/chat",
json={
"messages": [{"content": "What is the capital of France?", "role": "user"}],
"context": {
"overrides": {"retrieval_mode": "text"},
},
- "stream": True,
"session_state": {"conversation_id": 1234},
},
)
assert response.status_code == 200
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
===========changed ref 1===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_followup(client, snapshot):
response = await client.post(
"/chat",
json={
"messages": [{"content": "What is the capital of France?", "role": "user"}],
"context": {
"overrides": {"suggest_followup_questions": True},
},
},
)
assert response.status_code == 200
result = await response.get_json()
+ assert result["context"]["followup_questions"][0] == "What is the capital of Spain?"
- assert result["choices"][0]["context"]["followup_questions"][0] == "What is the capital of Spain?"
snapshot.assert_match(json.dumps(result, indent=4), "result.json")
===========changed ref 2===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_stream_text(client, snapshot):
response = await client.post(
+ "/chat/stream",
- "/chat",
json={
- "stream": True,
"messages": [{"content": "What is the capital of France?", "role": "user"}],
"context": {
"overrides": {"retrieval_mode": "text"},
},
},
)
assert response.status_code == 200
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
===========changed ref 3===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_stream_text_filter(auth_client, snapshot):
response = await auth_client.post(
+ "/chat/stream",
- "/chat",
headers={"Authorization": "Bearer MockToken"},
json={
- "stream": True,
"messages": [{"content": "What is the capital of France?", "role": "user"}],
"context": {
"overrides": {
"retrieval_mode": "text",
"use_oid_security_filter": True,
"use_groups_security_filter": True,
"exclude_category": "excluded",
}
},
},
)
assert response.status_code == 200
assert (
auth_client.config[app.CONFIG_SEARCH_CLIENT].filter
== "category ne 'excluded' and (oids/any(g:search.in(g, 'OID_X')) or groups/any(g:search.in(g, 'GROUP_Y, GROUP_Z')))"
)
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
===========changed ref 4===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_with_long_history(client, snapshot, caplog):
"""This test makes sure that the history is truncated to max tokens minus 1024."""
caplog.set_level(logging.DEBUG)
response = await client.post(
"/chat",
json={
"messages": [
{"role": "user", "content": "Is there a dress code?"}, # 9 tokens
{
"role": "assistant",
"content": "Yes, there is a dress code at Contoso Electronics. Look sharp! [employee_handbook-1.pdf]"
* 150,
}, # 3900 tokens
{"role": "user", "content": "What does a product manager do?"}, # 10 tokens
],
"context": {
"overrides": {"retrieval_mode": "text"},
},
},
)
assert response.status_code == 200
result = await response.get_json()
# Assert that it doesn't find the first message, since it wouldn't fit in the max tokens.
+ assert not thought_contains_text(result["context"]["thoughts"][3], "Is there a dress code?")
- assert not thought_contains_text(result["choices"][0]["context"]["thoughts"][3], "Is there a dress code?")
assert "Reached max tokens" in caplog.text
snapshot.assert_match(json.dumps(result, indent=4), "result.json")
===========changed ref 5===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_chat_stream_request_must_be_json(client):
+ response = await client.post("/chat/stream")
+ assert response.status_code == 415
+ result = await response.get_json()
+ assert result["error"] == "request must be json"
+
===========changed ref 6===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_with_history(client, snapshot):
response = await client.post(
"/chat",
json={
"messages": [
{"content": "What happens in a performance review?", "role": "user"},
{
"content": "During a performance review, employees will receive feedback on their performance over the past year, including both successes and areas for improvement. The feedback will be provided by the employee's supervisor and is intended to help the employee develop and grow in their role [employee_handbook-3.pdf]. The review is a two-way dialogue between the employee and their manager, so employees are encouraged to be honest and open during the process [employee_handbook-3.pdf]. The employee will also have the opportunity to discuss their goals and objectives for the upcoming year [employee_handbook-3.pdf]. A written summary of the performance review will be provided to the employee, which will include a rating of their performance, feedback, and goals and objectives for the upcoming year [employee_handbook-3.pdf].",
"role": "assistant",
},
{"content": "Is dental covered?", "role": "user"},
],
"context": {
"overrides": {"retrieval_mode": "text"},
},
},
)
assert response.status_code == 200
result = await response.get_json()
+ assert thought_contains_text(result["context"]["thoughts"][3], "performance review")
- assert thought_contains_text(result["choices"][0]["context"]["thoughts"][3], "performance review")
snapshot.assert_match(json.dumps(result, indent=4), "result.json")
|
app.backend.approaches.chatapproach/ChatApproach.run_without_streaming
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
dd7c1d2d17dd4c9b3909328693a936bc854e5a35
|
Upgrade to latest version of AI Chat Protocol (#1682)
|
<5>:<add> chat_resp = chat_resp["choices"][0]
<add> chat_resp["context"] = extra_info
<del> chat_resp["choices"][0]["context"] = extra_info
<7>:<add> content, followup_questions = self.extract_followup_questions(chat_resp["message"]["content"])
<del> content, followup_questions = self.extract_followup_questions(chat_resp["choices"][0]["message"]["content"])
<8>:<add> chat_resp["message"]["content"] = content
<del> chat_resp["choices"][0]["message"]["content"] = content
<9>:<add> chat_resp["context"]["followup_questions"] = followup_questions
<del> chat_resp["choices"][0]["context"]["followup_questions"] = followup_questions
<10>:<add> chat_resp["session_state"] = session_state
<del> chat_resp["choices"][0]["session_state"] = session_state
|
# module: app.backend.approaches.chatapproach
class ChatApproach(Approach, ABC):
def run_without_streaming(
self,
messages: list[ChatCompletionMessageParam],
overrides: dict[str, Any],
auth_claims: dict[str, Any],
session_state: Any = None,
) -> dict[str, Any]:
<0> extra_info, chat_coroutine = await self.run_until_final_call(
<1> messages, overrides, auth_claims, should_stream=False
<2> )
<3> chat_completion_response: ChatCompletion = await chat_coroutine
<4> chat_resp = chat_completion_response.model_dump() # Convert to dict to make it JSON serializable
<5> chat_resp["choices"][0]["context"] = extra_info
<6> if overrides.get("suggest_followup_questions"):
<7> content, followup_questions = self.extract_followup_questions(chat_resp["choices"][0]["message"]["content"])
<8> chat_resp["choices"][0]["message"]["content"] = content
<9> chat_resp["choices"][0]["context"]["followup_questions"] = followup_questions
<10> chat_resp["choices"][0]["session_state"] = session_state
<11> return chat_resp
<12>
|
===========unchanged ref 0===========
at: app.backend.approaches.chatapproach.ChatApproach
query_prompt_few_shots: list[ChatCompletionMessageParam] = [
{"role": "user", "content": "How did crypto do last year?"},
{"role": "assistant", "content": "Summarize Cryptocurrency Market Dynamics from last year"},
{"role": "user", "content": "What are my health plans?"},
{"role": "assistant", "content": "Show available health plans"},
]
NO_RESPONSE = "0"
follow_up_questions_prompt_content = """Generate 3 very brief follow-up questions that the user would likely ask next.
Enclose the follow-up questions in double angle brackets. Example:
<<Are there exclusions for prescriptions?>>
<<Which pharmacies can be ordered from?>>
<<What is the limit for over-the-counter medication?>>
Do no repeat questions that have already been asked.
Make sure the last question ends with ">>".
"""
query_prompt_template = """Below is a history of the conversation so far, and a new question asked by the user that needs to be answered by searching in a knowledge base.
You have access to Azure AI Search index with 100's of documents.
Generate a search query based on the conversation and the new question.
Do not include cited source filenames and document names e.g info.txt or doc.pdf in the search query terms.
Do not include any text inside [] or <<>> in the search query terms.
Do not include any special characters like '+'.
If the question is not in English, translate the question to English before generating the search query.
If you cannot generate a search query, return just the number 0.
"""
run_until_final_call(messages, overrides, auth_claims, should_stream) -> tuple
extract_followup_questions(content: str)
===========unchanged ref 1===========
at: typing.Mapping
get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]
get(key: _KT) -> Optional[_VT_co]
===========changed ref 0===========
# module: app.backend.approaches.approach
class Approach(ABC):
+ def run_stream(
+ self,
+ messages: list[ChatCompletionMessageParam],
+ session_state: Any = None,
+ context: dict[str, Any] = {},
+ ) -> AsyncGenerator[dict[str, Any], None]:
+ raise NotImplementedError
+
===========changed ref 1===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_chat_stream_request_must_be_json(client):
+ response = await client.post("/chat/stream")
+ assert response.status_code == 415
+ result = await response.get_json()
+ assert result["error"] == "request must be json"
+
===========changed ref 2===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_stream_text(client, snapshot):
response = await client.post(
+ "/chat/stream",
- "/chat",
json={
- "stream": True,
"messages": [{"content": "What is the capital of France?", "role": "user"}],
"context": {
"overrides": {"retrieval_mode": "text"},
},
},
)
assert response.status_code == 200
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
===========changed ref 3===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_stream_followup(client, snapshot):
response = await client.post(
+ "/chat/stream",
- "/chat",
json={
- "stream": True,
"messages": [{"content": "What is the capital of France?", "role": "user"}],
"context": {
"overrides": {"suggest_followup_questions": True},
},
},
)
assert response.status_code == 200
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
===========changed ref 4===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_stream_session_state_persists(client, snapshot):
response = await client.post(
+ "/chat/stream",
- "/chat",
json={
"messages": [{"content": "What is the capital of France?", "role": "user"}],
"context": {
"overrides": {"retrieval_mode": "text"},
},
- "stream": True,
"session_state": {"conversation_id": 1234},
},
)
assert response.status_code == 200
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
===========changed ref 5===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_chat_stream_vision(client, snapshot):
+ response = await client.post(
+ "/chat/stream",
+ json={
+ "messages": [{"content": "Are interest rates high?", "role": "user"}],
+ "context": {
+ "overrides": {
+ "use_gpt4v": True,
+ "gpt4v_input": "textAndImages",
+ "vector_fields": ["embedding", "imageEmbedding"],
+ },
+ },
+ },
+ )
+ assert response.status_code == 200
+ result = await response.get_data()
+ snapshot.assert_match(result, "result.jsonlines")
+
===========changed ref 6===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_chat_stream_handle_exception(client, monkeypatch, snapshot, caplog):
+ monkeypatch.setattr(
+ "approaches.chatreadretrieveread.ChatReadRetrieveReadApproach.run_stream",
+ mock.Mock(side_effect=ZeroDivisionError("something bad happened")),
+ )
+
+ response = await client.post(
+ "/chat/stream",
+ json={"messages": [{"content": "What is the capital of France?", "role": "user"}]},
+ )
+ assert response.status_code == 500
+ result = await response.get_json()
+ assert "Exception in /chat: something bad happened" in caplog.text
+ snapshot.assert_match(json.dumps(result, indent=4), "result.json")
+
===========changed ref 7===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_followup(client, snapshot):
response = await client.post(
"/chat",
json={
"messages": [{"content": "What is the capital of France?", "role": "user"}],
"context": {
"overrides": {"suggest_followup_questions": True},
},
},
)
assert response.status_code == 200
result = await response.get_json()
+ assert result["context"]["followup_questions"][0] == "What is the capital of Spain?"
- assert result["choices"][0]["context"]["followup_questions"][0] == "What is the capital of Spain?"
snapshot.assert_match(json.dumps(result, indent=4), "result.json")
|
app.backend.approaches.chatapproach/ChatApproach.run_with_streaming
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
dd7c1d2d17dd4c9b3909328693a936bc854e5a35
|
Upgrade to latest version of AI Chat Protocol (#1682)
|
<3>:<del> yield {
<4>:<del> "choices": [
<5>:<del> {
<6>:<del> "delta": {"role": "assistant"},
<7>:<del> "context": extra_info,
<8>:<del> "session_state": session_state,
<9>:<del> "finish_reason": None,
<10>:<del> "index": 0,
<11>:<del> }
<12>:<del> ],
<13>:<del> "object": "chat.completion.chunk",
<14>:<del> }
<15>:<add> yield {"delta": {"role": "assistant"}, "context": extra_info, "session_state": session_state}
<22>:<add> completion = {"delta": event["choices"][0]["delta"]}
<23>:<add> content = completion["delta"].get("content")
<del> content = event["choices"][0]["delta"].get("content")
<29>:<add> completion["delta"]["content"] = earlier_content
<del> event["choices"][0]["delta"]["content"] = earlier_content
<30>:<add> yield completion
<del> yield event
|
# module: app.backend.approaches.chatapproach
class ChatApproach(Approach, ABC):
def run_with_streaming(
self,
messages: list[ChatCompletionMessageParam],
overrides: dict[str, Any],
auth_claims: dict[str, Any],
session_state: Any = None,
) -> AsyncGenerator[dict, None]:
<0> extra_info, chat_coroutine = await self.run_until_final_call(
<1> messages, overrides, auth_claims, should_stream=True
<2> )
<3> yield {
<4> "choices": [
<5> {
<6> "delta": {"role": "assistant"},
<7> "context": extra_info,
<8> "session_state": session_state,
<9> "finish_reason": None,
<10> "index": 0,
<11> }
<12> ],
<13> "object": "chat.completion.chunk",
<14> }
<15>
<16> followup_questions_started = False
<17> followup_content = ""
<18> async for event_chunk in await chat_coroutine:
<19> # "2023-07-01-preview" API version has a bug where first response has empty choices
<20> event = event_chunk.model_dump() # Convert pydantic model to dict
<21> if event["choices"]:
<22> # if event contains << and not >>, it is start of follow-up question, truncate
<23> content = event["choices"][0]["delta"].get("content")
<24> content = content or "" # content may either not exist in delta, or explicitly be None
<25> if overrides.get("suggest_followup_questions") and "<<" in content:
<26> followup_questions_started = True
<27> earlier_content = content[: content.index("<<")]
<28> if earlier_content:
<29> event["choices"][0]["delta"]["content"] = earlier_content
<30> yield event
<31> followup_content += content[content.index("<<") :]
<32> elif followup_questions_started:
<33> followup_content +=</s>
|
===========below chunk 0===========
# module: app.backend.approaches.chatapproach
class ChatApproach(Approach, ABC):
def run_with_streaming(
self,
messages: list[ChatCompletionMessageParam],
overrides: dict[str, Any],
auth_claims: dict[str, Any],
session_state: Any = None,
) -> AsyncGenerator[dict, None]:
# offset: 1
else:
yield event
if followup_content:
_, followup_questions = self.extract_followup_questions(followup_content)
yield {
"choices": [
{
"delta": {"role": "assistant"},
"context": {"followup_questions": followup_questions},
"finish_reason": None,
"index": 0,
}
],
"object": "chat.completion.chunk",
}
===========unchanged ref 0===========
at: app.backend.approaches.chatapproach.ChatApproach
run_until_final_call(messages, overrides, auth_claims, should_stream) -> tuple
extract_followup_questions(content: str)
run_without_streaming(messages: list[ChatCompletionMessageParam], overrides: dict[str, Any], auth_claims: dict[str, Any], session_state: Any=None) -> dict[str, Any]
run_without_streaming(self, messages: list[ChatCompletionMessageParam], overrides: dict[str, Any], auth_claims: dict[str, Any], session_state: Any=None) -> dict[str, Any]
at: approaches.approach.Approach
run(self, messages: list[ChatCompletionMessageParam], session_state: Any=None, context: dict[str, Any]={}) -> dict[str, Any]
run_stream(self, messages: list[ChatCompletionMessageParam], session_state: Any=None, context: dict[str, Any]={}) -> AsyncGenerator[dict[str, Any], None]
at: typing
AsyncGenerator = _alias(collections.abc.AsyncGenerator, 2)
at: typing.Mapping
get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]
get(key: _KT) -> Optional[_VT_co]
===========changed ref 0===========
# module: app.backend.approaches.chatapproach
class ChatApproach(Approach, ABC):
def run_without_streaming(
self,
messages: list[ChatCompletionMessageParam],
overrides: dict[str, Any],
auth_claims: dict[str, Any],
session_state: Any = None,
) -> dict[str, Any]:
extra_info, chat_coroutine = await self.run_until_final_call(
messages, overrides, auth_claims, should_stream=False
)
chat_completion_response: ChatCompletion = await chat_coroutine
chat_resp = chat_completion_response.model_dump() # Convert to dict to make it JSON serializable
+ chat_resp = chat_resp["choices"][0]
+ chat_resp["context"] = extra_info
- chat_resp["choices"][0]["context"] = extra_info
if overrides.get("suggest_followup_questions"):
+ content, followup_questions = self.extract_followup_questions(chat_resp["message"]["content"])
- content, followup_questions = self.extract_followup_questions(chat_resp["choices"][0]["message"]["content"])
+ chat_resp["message"]["content"] = content
- chat_resp["choices"][0]["message"]["content"] = content
+ chat_resp["context"]["followup_questions"] = followup_questions
- chat_resp["choices"][0]["context"]["followup_questions"] = followup_questions
+ chat_resp["session_state"] = session_state
- chat_resp["choices"][0]["session_state"] = session_state
return chat_resp
===========changed ref 1===========
# module: app.backend.approaches.approach
class Approach(ABC):
+ def run_stream(
+ self,
+ messages: list[ChatCompletionMessageParam],
+ session_state: Any = None,
+ context: dict[str, Any] = {},
+ ) -> AsyncGenerator[dict[str, Any], None]:
+ raise NotImplementedError
+
===========changed ref 2===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_chat_stream_request_must_be_json(client):
+ response = await client.post("/chat/stream")
+ assert response.status_code == 415
+ result = await response.get_json()
+ assert result["error"] == "request must be json"
+
===========changed ref 3===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_stream_text(client, snapshot):
response = await client.post(
+ "/chat/stream",
- "/chat",
json={
- "stream": True,
"messages": [{"content": "What is the capital of France?", "role": "user"}],
"context": {
"overrides": {"retrieval_mode": "text"},
},
},
)
assert response.status_code == 200
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
===========changed ref 4===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_stream_followup(client, snapshot):
response = await client.post(
+ "/chat/stream",
- "/chat",
json={
- "stream": True,
"messages": [{"content": "What is the capital of France?", "role": "user"}],
"context": {
"overrides": {"suggest_followup_questions": True},
},
},
)
assert response.status_code == 200
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
===========changed ref 5===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_stream_session_state_persists(client, snapshot):
response = await client.post(
+ "/chat/stream",
- "/chat",
json={
"messages": [{"content": "What is the capital of France?", "role": "user"}],
"context": {
"overrides": {"retrieval_mode": "text"},
},
- "stream": True,
"session_state": {"conversation_id": 1234},
},
)
assert response.status_code == 200
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
===========changed ref 6===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_chat_stream_vision(client, snapshot):
+ response = await client.post(
+ "/chat/stream",
+ json={
+ "messages": [{"content": "Are interest rates high?", "role": "user"}],
+ "context": {
+ "overrides": {
+ "use_gpt4v": True,
+ "gpt4v_input": "textAndImages",
+ "vector_fields": ["embedding", "imageEmbedding"],
+ },
+ },
+ },
+ )
+ assert response.status_code == 200
+ result = await response.get_data()
+ snapshot.assert_match(result, "result.jsonlines")
+
|
app.backend.approaches.chatapproach/ChatApproach.run
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
dd7c1d2d17dd4c9b3909328693a936bc854e5a35
|
Upgrade to latest version of AI Chat Protocol (#1682)
|
<2>:<add> return await self.run_without_streaming(messages, overrides, auth_claims, session_state)
<3>:<del> if stream is False:
<4>:<del> return await self.run_without_streaming(messages, overrides, auth_claims, session_state)
<5>:<del> else:
<6>:<del> return self.run_with_streaming(messages, overrides, auth_claims, session_state)
<7>:<del>
|
# module: app.backend.approaches.chatapproach
class ChatApproach(Approach, ABC):
def run(
self,
messages: list[ChatCompletionMessageParam],
- stream: bool = False,
session_state: Any = None,
context: dict[str, Any] = {},
+ ) -> dict[str, Any]:
- ) -> Union[dict[str, Any], AsyncGenerator[dict[str, Any], None]]:
<0> overrides = context.get("overrides", {})
<1> auth_claims = context.get("auth_claims", {})
<2>
<3> if stream is False:
<4> return await self.run_without_streaming(messages, overrides, auth_claims, session_state)
<5> else:
<6> return self.run_with_streaming(messages, overrides, auth_claims, session_state)
<7>
|
===========changed ref 0===========
# module: app.backend.approaches.chatapproach
class ChatApproach(Approach, ABC):
+ def run_stream(
+ self,
+ messages: list[ChatCompletionMessageParam],
+ session_state: Any = None,
+ context: dict[str, Any] = {},
+ ) -> AsyncGenerator[dict[str, Any], None]:
+ overrides = context.get("overrides", {})
+ auth_claims = context.get("auth_claims", {})
+ return self.run_with_streaming(messages, overrides, auth_claims, session_state)
+
===========changed ref 1===========
# module: app.backend.approaches.chatapproach
class ChatApproach(Approach, ABC):
def run_without_streaming(
self,
messages: list[ChatCompletionMessageParam],
overrides: dict[str, Any],
auth_claims: dict[str, Any],
session_state: Any = None,
) -> dict[str, Any]:
extra_info, chat_coroutine = await self.run_until_final_call(
messages, overrides, auth_claims, should_stream=False
)
chat_completion_response: ChatCompletion = await chat_coroutine
chat_resp = chat_completion_response.model_dump() # Convert to dict to make it JSON serializable
+ chat_resp = chat_resp["choices"][0]
+ chat_resp["context"] = extra_info
- chat_resp["choices"][0]["context"] = extra_info
if overrides.get("suggest_followup_questions"):
+ content, followup_questions = self.extract_followup_questions(chat_resp["message"]["content"])
- content, followup_questions = self.extract_followup_questions(chat_resp["choices"][0]["message"]["content"])
+ chat_resp["message"]["content"] = content
- chat_resp["choices"][0]["message"]["content"] = content
+ chat_resp["context"]["followup_questions"] = followup_questions
- chat_resp["choices"][0]["context"]["followup_questions"] = followup_questions
+ chat_resp["session_state"] = session_state
- chat_resp["choices"][0]["session_state"] = session_state
return chat_resp
===========changed ref 2===========
# module: app.backend.approaches.chatapproach
class ChatApproach(Approach, ABC):
def run_with_streaming(
self,
messages: list[ChatCompletionMessageParam],
overrides: dict[str, Any],
auth_claims: dict[str, Any],
session_state: Any = None,
) -> AsyncGenerator[dict, None]:
extra_info, chat_coroutine = await self.run_until_final_call(
messages, overrides, auth_claims, should_stream=True
)
- yield {
- "choices": [
- {
- "delta": {"role": "assistant"},
- "context": extra_info,
- "session_state": session_state,
- "finish_reason": None,
- "index": 0,
- }
- ],
- "object": "chat.completion.chunk",
- }
+ yield {"delta": {"role": "assistant"}, "context": extra_info, "session_state": session_state}
followup_questions_started = False
followup_content = ""
async for event_chunk in await chat_coroutine:
# "2023-07-01-preview" API version has a bug where first response has empty choices
event = event_chunk.model_dump() # Convert pydantic model to dict
if event["choices"]:
+ completion = {"delta": event["choices"][0]["delta"]}
# if event contains << and not >>, it is start of follow-up question, truncate
+ content = completion["delta"].get("content")
- content = event["choices"][0]["delta"].get("content")
content = content or "" # content may either not exist in delta, or explicitly be None
if overrides.get("suggest_followup_questions") and "<<" in content:
followup_questions_started = True
earlier_content = content[: content.index("<<")]
if earlier_content:
+ completion["delta"]["content"] = earlier_content</s>
===========changed ref 3===========
# module: app.backend.approaches.chatapproach
class ChatApproach(Approach, ABC):
def run_with_streaming(
self,
messages: list[ChatCompletionMessageParam],
overrides: dict[str, Any],
auth_claims: dict[str, Any],
session_state: Any = None,
) -> AsyncGenerator[dict, None]:
# offset: 1
<s>[: content.index("<<")]
if earlier_content:
+ completion["delta"]["content"] = earlier_content
- event["choices"][0]["delta"]["content"] = earlier_content
+ yield completion
- yield event
followup_content += content[content.index("<<") :]
elif followup_questions_started:
followup_content += content
else:
+ yield completion
- yield event
if followup_content:
_, followup_questions = self.extract_followup_questions(followup_content)
- yield {
- "choices": [
- {
- "delta": {"role": "assistant"},
+ yield {"delta": {"role": "assistant"}, "context": {"followup_questions": followup_questions}}
- "context": {"followup_questions": followup_questions},
- "finish_reason": None,
- "index": 0,
- }
- ],
- "object": "chat.completion.chunk",
- }
===========changed ref 4===========
# module: app.backend.approaches.approach
class Approach(ABC):
+ def run_stream(
+ self,
+ messages: list[ChatCompletionMessageParam],
+ session_state: Any = None,
+ context: dict[str, Any] = {},
+ ) -> AsyncGenerator[dict[str, Any], None]:
+ raise NotImplementedError
+
===========changed ref 5===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_chat_stream_request_must_be_json(client):
+ response = await client.post("/chat/stream")
+ assert response.status_code == 415
+ result = await response.get_json()
+ assert result["error"] == "request must be json"
+
===========changed ref 6===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_stream_text(client, snapshot):
response = await client.post(
+ "/chat/stream",
- "/chat",
json={
- "stream": True,
"messages": [{"content": "What is the capital of France?", "role": "user"}],
"context": {
"overrides": {"retrieval_mode": "text"},
},
},
)
assert response.status_code == 200
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
===========changed ref 7===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_stream_followup(client, snapshot):
response = await client.post(
+ "/chat/stream",
- "/chat",
json={
- "stream": True,
"messages": [{"content": "What is the capital of France?", "role": "user"}],
"context": {
"overrides": {"suggest_followup_questions": True},
},
},
)
assert response.status_code == 200
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
|
locustfile/ChatVisionUser.ask_question
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
dd7c1d2d17dd4c9b3909328693a936bc854e5a35
|
Upgrade to latest version of AI Chat Protocol (#1682)
|
<3>:<add> "/chat/stream",
<del> "/chat",
<11>:<del> "stream": True,
<34>:<add> "/chat/stream",
<del> "/chat",
<39>:<del> "stream": True,
|
# module: locustfile
class ChatVisionUser(HttpUser):
@task
def ask_question(self):
<0> self.client.get("/")
<1> time.sleep(5)
<2> self.client.post(
<3> "/chat",
<4> json={
<5> "messages": [
<6> {
<7> "content": "Can you identify any correlation between oil prices and stock market trends?",
<8> "role": "user",
<9> }
<10> ],
<11> "stream": True,
<12> "context": {
<13> "overrides": {
<14> "top": 3,
<15> "temperature": 0.3,
<16> "minimum_reranker_score": 0,
<17> "minimum_search_score": 0,
<18> "retrieval_mode": "hybrid",
<19> "semantic_ranker": True,
<20> "semantic_captions": False,
<21> "suggest_followup_questions": False,
<22> "use_oid_security_filter": False,
<23> "use_groups_security_filter": False,
<24> "vector_fields": ["embedding", "imageEmbedding"],
<25> "use_gpt4v": True,
<26> "gpt4v_input": "textAndImages",
<27> }
<28> },
<29> "session_state": None,
<30> },
<31> )
<32> time.sleep(5)
<33> self.client.post(
<34> "/chat",
<35> json={
<36> "messages": [
<37> {"content": "Compare the impact of interest rates and GDP in financial markets.", "role": "user"}
<38> ],
<39> "stream": True,
<40> "context": {
<41> "overrides": {
<42> "top": 3,
<43> "temperature": 0.3,
<44> "minimum_reranker_score": 0,
<45> "minimum_search_score": 0,
<46> "retrieval_mode": "hybrid",
<47> "semantic_ranker": True,
<48> "semantic_</s>
|
===========below chunk 0===========
# module: locustfile
class ChatVisionUser(HttpUser):
@task
def ask_question(self):
# offset: 1
"suggest_followup_questions": False,
"use_oid_security_filter": False,
"use_groups_security_filter": False,
"vector_fields": ["embedding", "imageEmbedding"],
"use_gpt4v": True,
"gpt4v_input": "textAndImages",
}
},
"session_state": None,
},
)
===========unchanged ref 0===========
at: locustfile.ChatVisionUser
wait_time = between(5, 20)
at: time
sleep(secs: float) -> None
===========changed ref 0===========
# module: app.backend.approaches.approach
class Approach(ABC):
+ def run_stream(
+ self,
+ messages: list[ChatCompletionMessageParam],
+ session_state: Any = None,
+ context: dict[str, Any] = {},
+ ) -> AsyncGenerator[dict[str, Any], None]:
+ raise NotImplementedError
+
===========changed ref 1===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_chat_stream_request_must_be_json(client):
+ response = await client.post("/chat/stream")
+ assert response.status_code == 415
+ result = await response.get_json()
+ assert result["error"] == "request must be json"
+
===========changed ref 2===========
# module: app.backend.approaches.chatapproach
class ChatApproach(Approach, ABC):
+ def run_stream(
+ self,
+ messages: list[ChatCompletionMessageParam],
+ session_state: Any = None,
+ context: dict[str, Any] = {},
+ ) -> AsyncGenerator[dict[str, Any], None]:
+ overrides = context.get("overrides", {})
+ auth_claims = context.get("auth_claims", {})
+ return self.run_with_streaming(messages, overrides, auth_claims, session_state)
+
===========changed ref 3===========
# module: app.backend.approaches.chatapproach
class ChatApproach(Approach, ABC):
def run(
self,
messages: list[ChatCompletionMessageParam],
- stream: bool = False,
session_state: Any = None,
context: dict[str, Any] = {},
+ ) -> dict[str, Any]:
- ) -> Union[dict[str, Any], AsyncGenerator[dict[str, Any], None]]:
overrides = context.get("overrides", {})
auth_claims = context.get("auth_claims", {})
+ return await self.run_without_streaming(messages, overrides, auth_claims, session_state)
- if stream is False:
- return await self.run_without_streaming(messages, overrides, auth_claims, session_state)
- else:
- return self.run_with_streaming(messages, overrides, auth_claims, session_state)
-
===========changed ref 4===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_stream_text(client, snapshot):
response = await client.post(
+ "/chat/stream",
- "/chat",
json={
- "stream": True,
"messages": [{"content": "What is the capital of France?", "role": "user"}],
"context": {
"overrides": {"retrieval_mode": "text"},
},
},
)
assert response.status_code == 200
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
===========changed ref 5===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_stream_followup(client, snapshot):
response = await client.post(
+ "/chat/stream",
- "/chat",
json={
- "stream": True,
"messages": [{"content": "What is the capital of France?", "role": "user"}],
"context": {
"overrides": {"suggest_followup_questions": True},
},
},
)
assert response.status_code == 200
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
===========changed ref 6===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_stream_session_state_persists(client, snapshot):
response = await client.post(
+ "/chat/stream",
- "/chat",
json={
"messages": [{"content": "What is the capital of France?", "role": "user"}],
"context": {
"overrides": {"retrieval_mode": "text"},
},
- "stream": True,
"session_state": {"conversation_id": 1234},
},
)
assert response.status_code == 200
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
===========changed ref 7===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_chat_stream_vision(client, snapshot):
+ response = await client.post(
+ "/chat/stream",
+ json={
+ "messages": [{"content": "Are interest rates high?", "role": "user"}],
+ "context": {
+ "overrides": {
+ "use_gpt4v": True,
+ "gpt4v_input": "textAndImages",
+ "vector_fields": ["embedding", "imageEmbedding"],
+ },
+ },
+ },
+ )
+ assert response.status_code == 200
+ result = await response.get_data()
+ snapshot.assert_match(result, "result.jsonlines")
+
===========changed ref 8===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_chat_stream_handle_exception(client, monkeypatch, snapshot, caplog):
+ monkeypatch.setattr(
+ "approaches.chatreadretrieveread.ChatReadRetrieveReadApproach.run_stream",
+ mock.Mock(side_effect=ZeroDivisionError("something bad happened")),
+ )
+
+ response = await client.post(
+ "/chat/stream",
+ json={"messages": [{"content": "What is the capital of France?", "role": "user"}]},
+ )
+ assert response.status_code == 500
+ result = await response.get_json()
+ assert "Exception in /chat: something bad happened" in caplog.text
+ snapshot.assert_match(json.dumps(result, indent=4), "result.json")
+
===========changed ref 9===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_followup(client, snapshot):
response = await client.post(
"/chat",
json={
"messages": [{"content": "What is the capital of France?", "role": "user"}],
"context": {
"overrides": {"suggest_followup_questions": True},
},
},
)
assert response.status_code == 200
result = await response.get_json()
+ assert result["context"]["followup_questions"][0] == "What is the capital of Spain?"
- assert result["choices"][0]["context"]["followup_questions"][0] == "What is the capital of Spain?"
snapshot.assert_match(json.dumps(result, indent=4), "result.json")
|
app.backend.approaches.retrievethenread/RetrieveThenReadApproach.run
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
dd7c1d2d17dd4c9b3909328693a936bc854e5a35
|
Upgrade to latest version of AI Chat Protocol (#1682)
|
# module: app.backend.approaches.retrievethenread
class RetrieveThenReadApproach(Approach):
def run(
self,
messages: list[ChatCompletionMessageParam],
- stream: bool = False, # Stream is not used in this approach
session_state: Any = None,
context: dict[str, Any] = {},
+ ) -> dict[str, Any]:
- ) -> Union[dict[str, Any], AsyncGenerator[dict[str, Any], None]]:
<0> q = messages[-1]["content"]
<1> if not isinstance(q, str):
<2> raise ValueError("The most recent message content must be a string.")
<3> overrides = context.get("overrides", {})
<4> auth_claims = context.get("auth_claims", {})
<5> has_text = overrides.get("retrieval_mode") in ["text", "hybrid", None]
<6> has_vector = overrides.get("retrieval_mode") in ["vectors", "hybrid", None]
<7> use_semantic_ranker = overrides.get("semantic_ranker") and has_text
<8>
<9> use_semantic_captions = True if overrides.get("semantic_captions") and has_text else False
<10> top = overrides.get("top", 3)
<11> minimum_search_score = overrides.get("minimum_search_score", 0.0)
<12> minimum_reranker_score = overrides.get("minimum_reranker_score", 0.0)
<13> filter = self.build_filter(overrides, auth_claims)
<14> # If retrieval mode includes vectors, compute an embedding for the query
<15> vectors: list[VectorQuery] = []
<16> if has_vector:
<17> vectors.append(await self.compute_text_embedding(q))
<18>
<19> # Only keep the text query if the retrieval mode uses text, otherwise drop it
<20> query_text = q if has_text else None
<21>
<22> results = await self.search(
<23> top,
<24> query_text,
<25> filter,
<26> vectors,
<27> use_sem</s>
|
===========below chunk 0===========
# module: app.backend.approaches.retrievethenread
class RetrieveThenReadApproach(Approach):
def run(
self,
messages: list[ChatCompletionMessageParam],
- stream: bool = False, # Stream is not used in this approach
session_state: Any = None,
context: dict[str, Any] = {},
+ ) -> dict[str, Any]:
- ) -> Union[dict[str, Any], AsyncGenerator[dict[str, Any], None]]:
# offset: 1
use_semantic_captions,
minimum_search_score,
minimum_reranker_score,
)
# Process results
sources_content = self.get_sources_content(results, use_semantic_captions, use_image_citation=False)
# Append user message
content = "\n".join(sources_content)
user_content = q + "\n" + f"Sources:\n {content}"
response_token_limit = 1024
updated_messages = build_messages(
model=self.chatgpt_model,
system_prompt=overrides.get("prompt_template", self.system_chat_template),
few_shots=[{"role": "user", "content": self.question}, {"role": "assistant", "content": self.answer}],
new_user_content=user_content,
max_tokens=self.chatgpt_token_limit - response_token_limit,
)
chat_completion = (
await self.openai_client.chat.completions.create(
# Azure OpenAI takes the deployment name as the model name
model=self.chatgpt_deployment if self.chatgpt_deployment else self.chatgpt_model,
messages=updated_messages,
temperature=overrides.get("temperature", 0.3),
max_tokens=response_token_limit,
n=1,
)
).model_dump()
data_points = {"text": sources_content}
extra_info = {
"data_points": data</s>
===========below chunk 1===========
# module: app.backend.approaches.retrievethenread
class RetrieveThenReadApproach(Approach):
def run(
self,
messages: list[ChatCompletionMessageParam],
- stream: bool = False, # Stream is not used in this approach
session_state: Any = None,
context: dict[str, Any] = {},
+ ) -> dict[str, Any]:
- ) -> Union[dict[str, Any], AsyncGenerator[dict[str, Any], None]]:
# offset: 2
<s>()
data_points = {"text": sources_content}
extra_info = {
"data_points": data_points,
"thoughts": [
ThoughtStep(
"Search using user query",
query_text,
{
"use_semantic_captions": use_semantic_captions,
"use_semantic_ranker": use_semantic_ranker,
"top": top,
"filter": filter,
"has_vector": has_vector,
},
),
ThoughtStep(
"Search results",
[result.serialize_for_results() for result in results],
),
ThoughtStep(
"Prompt to generate answer",
[str(message) for message in updated_messages],
(
{"model": self.chatgpt_model, "deployment": self.chatgpt_deployment}
if self.chatgpt_deployment
else {"model": self.chatgpt_model}
),
),
],
}
chat_completion["choices"][0]["context"] = extra_info
chat_completion["choices"][0]["session_state"] = session_state
return chat_completion
===========unchanged ref 0===========
at: app.backend.approaches.retrievethenread.RetrieveThenReadApproach
system_chat_template = (
"You are an intelligent assistant helping Contoso Inc employees with their healthcare plan questions and employee handbook questions. "
+ "Use 'you' to refer to the individual asking the questions even if they ask with 'I'. "
+ "Answer the following question using only the data provided in the sources below. "
+ "For tabular information return it as an html table. Do not return markdown format. "
+ "Each source has a name followed by colon and the actual information, always include the source name for each fact you use in the response. "
+ "If you cannot answer using the sources below, say you don't know. Use below example to answer"
)
question = """
'What is the deductible for the employee plan for a visit to Overlake in Bellevue?'
Sources:
info1.txt: deductibles depend on whether you are in-network or out-of-network. In-network deductibles are $500 for employee and $1000 for family. Out-of-network deductibles are $1000 for employee and $2000 for family.
info2.pdf: Overlake is in-network for the employee plan.
info3.pdf: Overlake is the name of the area that includes a park and ride near Bellevue.
info4.pdf: In-network institutions include Overlake, Swedish and others in the region
"""
answer = "In-network deductibles are $500 for employee and $1000 for family [info1.txt] and Overlake is in-network for the employee plan [info2.pdf][info4.pdf]."
at: app.backend.approaches.retrievethenread.RetrieveThenReadApproach.__init__
self.openai_client = openai_client
self.chatgpt_model = chatgpt_model
self.chatgpt_token_limit = get_token_limit(chatgpt_model)
===========unchanged ref 1===========
at: approaches.approach
ThoughtStep(title: str, description: Optional[Any], props: Optional[dict[str, Any]]=None)
at: approaches.approach.Approach
build_filter(overrides: dict[str, Any], auth_claims: dict[str, Any]) -> Optional[str]
search(top: int, query_text: Optional[str], filter: Optional[str], vectors: List[VectorQuery], use_semantic_ranker: bool, use_semantic_captions: bool, minimum_search_score: Optional[float], minimum_reranker_score: Optional[float]) -> List[Document]
get_sources_content(results: List[Document], use_semantic_captions: bool, use_image_citation: bool) -> list[str]
compute_text_embedding(q: str)
run(self, messages: list[ChatCompletionMessageParam], session_state: Any=None, context: dict[str, Any]={}) -> dict[str, Any]
at: typing.Mapping
get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]
get(key: _KT) -> Optional[_VT_co]
===========changed ref 0===========
# module: app.backend.approaches.approach
class Approach(ABC):
+ def run_stream(
+ self,
+ messages: list[ChatCompletionMessageParam],
+ session_state: Any = None,
+ context: dict[str, Any] = {},
+ ) -> AsyncGenerator[dict[str, Any], None]:
+ raise NotImplementedError
+
===========changed ref 1===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_chat_stream_request_must_be_json(client):
+ response = await client.post("/chat/stream")
+ assert response.status_code == 415
+ result = await response.get_json()
+ assert result["error"] == "request must be json"
+
|
|
app.backend.app/chat
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
dd7c1d2d17dd4c9b3909328693a936bc854e5a35
|
Upgrade to latest version of AI Chat Protocol (#1682)
|
<15>:<del> stream=request_json.get("stream", False),
<19>:<del> if isinstance(result, dict):
<20>:<add> return jsonify(result)
<del> return jsonify(result)
<21>:<del> else:
<22>:<del> response = await make_response(format_as_ndjson(result))
<23>:<del> response.timeout = None # type: ignore
<24>:<del> response.mimetype = "application/json-lines"
<25>:<del> return response
|
# module: app.backend.app
@bp.route("/chat", methods=["POST"])
@authenticated
async def chat(auth_claims: Dict[str, Any]):
<0> if not request.is_json:
<1> return jsonify({"error": "request must be json"}), 415
<2> request_json = await request.get_json()
<3> context = request_json.get("context", {})
<4> context["auth_claims"] = auth_claims
<5> try:
<6> use_gpt4v = context.get("overrides", {}).get("use_gpt4v", False)
<7> approach: Approach
<8> if use_gpt4v and CONFIG_CHAT_VISION_APPROACH in current_app.config:
<9> approach = cast(Approach, current_app.config[CONFIG_CHAT_VISION_APPROACH])
<10> else:
<11> approach = cast(Approach, current_app.config[CONFIG_CHAT_APPROACH])
<12>
<13> result = await approach.run(
<14> request_json["messages"],
<15> stream=request_json.get("stream", False),
<16> context=context,
<17> session_state=request_json.get("session_state"),
<18> )
<19> if isinstance(result, dict):
<20> return jsonify(result)
<21> else:
<22> response = await make_response(format_as_ndjson(result))
<23> response.timeout = None # type: ignore
<24> response.mimetype = "application/json-lines"
<25> return response
<26> except Exception as error:
<27> return error_response(error, "/chat")
<28>
|
===========unchanged ref 0===========
at: app.backend.app
bp = Blueprint("routes", __name__, static_folder="static")
format_as_ndjson(r: AsyncGenerator[dict, None]) -> AsyncGenerator[str, None]
at: approaches.approach
Approach(search_client: SearchClient, openai_client: AsyncOpenAI, auth_helper: AuthenticationHelper, query_language: Optional[str], query_speller: Optional[str], embedding_deployment: Optional[str], embedding_model: str, embedding_dimensions: int, openai_host: str, vision_endpoint: str, vision_token_provider: Callable[[], Awaitable[str]])
at: approaches.approach.Approach
run(messages: list[ChatCompletionMessageParam], session_state: Any=None, context: dict[str, Any]={}) -> dict[str, Any]
at: config
CONFIG_CHAT_VISION_APPROACH = "chat_vision_approach"
CONFIG_CHAT_APPROACH = "chat_approach"
at: decorators
authenticated(route_fn: Callable[[Dict[str, Any]], Any])
at: error
error_response(error: Exception, route: str, status_code: int=500)
at: typing
cast(typ: Type[_T], val: Any) -> _T
cast(typ: str, val: Any) -> Any
cast(typ: object, val: Any) -> Any
Dict = _alias(dict, 2, inst=False, name='Dict')
===========changed ref 0===========
# module: app.backend.approaches.approach
class Approach(ABC):
+ def run_stream(
+ self,
+ messages: list[ChatCompletionMessageParam],
+ session_state: Any = None,
+ context: dict[str, Any] = {},
+ ) -> AsyncGenerator[dict[str, Any], None]:
+ raise NotImplementedError
+
===========changed ref 1===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_chat_stream_request_must_be_json(client):
+ response = await client.post("/chat/stream")
+ assert response.status_code == 415
+ result = await response.get_json()
+ assert result["error"] == "request must be json"
+
===========changed ref 2===========
# module: app.backend.approaches.chatapproach
class ChatApproach(Approach, ABC):
+ def run_stream(
+ self,
+ messages: list[ChatCompletionMessageParam],
+ session_state: Any = None,
+ context: dict[str, Any] = {},
+ ) -> AsyncGenerator[dict[str, Any], None]:
+ overrides = context.get("overrides", {})
+ auth_claims = context.get("auth_claims", {})
+ return self.run_with_streaming(messages, overrides, auth_claims, session_state)
+
===========changed ref 3===========
# module: app.backend.approaches.chatapproach
class ChatApproach(Approach, ABC):
def run(
self,
messages: list[ChatCompletionMessageParam],
- stream: bool = False,
session_state: Any = None,
context: dict[str, Any] = {},
+ ) -> dict[str, Any]:
- ) -> Union[dict[str, Any], AsyncGenerator[dict[str, Any], None]]:
overrides = context.get("overrides", {})
auth_claims = context.get("auth_claims", {})
+ return await self.run_without_streaming(messages, overrides, auth_claims, session_state)
- if stream is False:
- return await self.run_without_streaming(messages, overrides, auth_claims, session_state)
- else:
- return self.run_with_streaming(messages, overrides, auth_claims, session_state)
-
===========changed ref 4===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_stream_text(client, snapshot):
response = await client.post(
+ "/chat/stream",
- "/chat",
json={
- "stream": True,
"messages": [{"content": "What is the capital of France?", "role": "user"}],
"context": {
"overrides": {"retrieval_mode": "text"},
},
},
)
assert response.status_code == 200
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
===========changed ref 5===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_stream_followup(client, snapshot):
response = await client.post(
+ "/chat/stream",
- "/chat",
json={
- "stream": True,
"messages": [{"content": "What is the capital of France?", "role": "user"}],
"context": {
"overrides": {"suggest_followup_questions": True},
},
},
)
assert response.status_code == 200
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
===========changed ref 6===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_stream_session_state_persists(client, snapshot):
response = await client.post(
+ "/chat/stream",
- "/chat",
json={
"messages": [{"content": "What is the capital of France?", "role": "user"}],
"context": {
"overrides": {"retrieval_mode": "text"},
},
- "stream": True,
"session_state": {"conversation_id": 1234},
},
)
assert response.status_code == 200
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
===========changed ref 7===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_chat_stream_vision(client, snapshot):
+ response = await client.post(
+ "/chat/stream",
+ json={
+ "messages": [{"content": "Are interest rates high?", "role": "user"}],
+ "context": {
+ "overrides": {
+ "use_gpt4v": True,
+ "gpt4v_input": "textAndImages",
+ "vector_fields": ["embedding", "imageEmbedding"],
+ },
+ },
+ },
+ )
+ assert response.status_code == 200
+ result = await response.get_data()
+ snapshot.assert_match(result, "result.jsonlines")
+
===========changed ref 8===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_chat_stream_handle_exception(client, monkeypatch, snapshot, caplog):
+ monkeypatch.setattr(
+ "approaches.chatreadretrieveread.ChatReadRetrieveReadApproach.run_stream",
+ mock.Mock(side_effect=ZeroDivisionError("something bad happened")),
+ )
+
+ response = await client.post(
+ "/chat/stream",
+ json={"messages": [{"content": "What is the capital of France?", "role": "user"}]},
+ )
+ assert response.status_code == 500
+ result = await response.get_json()
+ assert "Exception in /chat: something bad happened" in caplog.text
+ snapshot.assert_match(json.dumps(result, indent=4), "result.json")
+
|
tests.e2e/test_chat
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
dd7c1d2d17dd4c9b3909328693a936bc854e5a35
|
Upgrade to latest version of AI Chat Protocol (#1682)
|
<11>:<add> page.route("*/**/chat/stream", handle)
<del> page.route("*/**/chat", handle)
|
# module: tests.e2e
def test_chat(page: Page, live_server_url: str):
<0> # Set up a mock route to the /chat endpoint with streaming results
<1> def handle(route: Route):
<2> # Assert that session_state is specified in the request (None for now)
<3> session_state = route.request.post_data_json["session_state"]
<4> assert session_state is None
<5> # Read the JSONL from our snapshot results and return as the response
<6> f = open("tests/snapshots/test_app/test_chat_stream_text/client0/result.jsonlines")
<7> jsonl = f.read()
<8> f.close()
<9> route.fulfill(body=jsonl, status=200, headers={"Transfer-encoding": "Chunked"})
<10>
<11> page.route("*/**/chat", handle)
<12>
<13> # Check initial page state
<14> page.goto(live_server_url)
<15> expect(page).to_have_title("GPT + Enterprise data | Sample")
<16> expect(page.get_by_role("heading", name="Chat with your data")).to_be_visible()
<17> expect(page.get_by_role("button", name="Clear chat")).to_be_disabled()
<18> expect(page.get_by_role("button", name="Developer settings")).to_be_enabled()
<19>
<20> # Ask a question and wait for the message to appear
<21> page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").click()
<22> page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").fill(
<23> "Whats the dental plan?"
<24> )
<25> page.get_by_role("button", name="Submit question").click()
<26>
<27> expect(page.get_by_text("Whats the dental plan?")).to_be_visible()
<28> expect(page.get_by_text("The capital of France is Par</s>
|
===========below chunk 0===========
# module: tests.e2e
def test_chat(page: Page, live_server_url: str):
# offset: 1
expect(page.get_by_role("button", name="Clear chat")).to_be_enabled()
# Show the citation document
page.get_by_text("1. Benefit_Options-2.pdf").click()
expect(page.get_by_role("tab", name="Citation")).to_be_visible()
expect(page.get_by_title("Citation")).to_be_visible()
# Show the thought process
page.get_by_label("Show thought process").click()
expect(page.get_by_title("Thought process")).to_be_visible()
expect(page.get_by_text("Generated search query")).to_be_visible()
# Show the supporting content
page.get_by_label("Show supporting content").click()
expect(page.get_by_title("Supporting content")).to_be_visible()
expect(page.get_by_role("heading", name="Benefit_Options-2.pdf")).to_be_visible()
# Clear the chat
page.get_by_role("button", name="Clear chat").click()
expect(page.get_by_text("Whats the dental plan?")).not_to_be_visible()
expect(page.get_by_text("The capital of France is Paris.")).not_to_be_visible()
expect(page.get_by_role("button", name="Clear chat")).to_be_disabled()
===========unchanged ref 0===========
at: io.BufferedReader
read(self, size: Optional[int]=..., /) -> bytes
at: io.BufferedWriter
close(self) -> None
at: typing.IO
__slots__ = ()
close() -> None
read(n: int=...) -> AnyStr
===========changed ref 0===========
# module: app.backend.approaches.approach
class Approach(ABC):
+ def run_stream(
+ self,
+ messages: list[ChatCompletionMessageParam],
+ session_state: Any = None,
+ context: dict[str, Any] = {},
+ ) -> AsyncGenerator[dict[str, Any], None]:
+ raise NotImplementedError
+
===========changed ref 1===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_chat_stream_request_must_be_json(client):
+ response = await client.post("/chat/stream")
+ assert response.status_code == 415
+ result = await response.get_json()
+ assert result["error"] == "request must be json"
+
===========changed ref 2===========
# module: app.backend.approaches.chatapproach
class ChatApproach(Approach, ABC):
+ def run_stream(
+ self,
+ messages: list[ChatCompletionMessageParam],
+ session_state: Any = None,
+ context: dict[str, Any] = {},
+ ) -> AsyncGenerator[dict[str, Any], None]:
+ overrides = context.get("overrides", {})
+ auth_claims = context.get("auth_claims", {})
+ return self.run_with_streaming(messages, overrides, auth_claims, session_state)
+
===========changed ref 3===========
# module: app.backend.approaches.chatapproach
class ChatApproach(Approach, ABC):
def run(
self,
messages: list[ChatCompletionMessageParam],
- stream: bool = False,
session_state: Any = None,
context: dict[str, Any] = {},
+ ) -> dict[str, Any]:
- ) -> Union[dict[str, Any], AsyncGenerator[dict[str, Any], None]]:
overrides = context.get("overrides", {})
auth_claims = context.get("auth_claims", {})
+ return await self.run_without_streaming(messages, overrides, auth_claims, session_state)
- if stream is False:
- return await self.run_without_streaming(messages, overrides, auth_claims, session_state)
- else:
- return self.run_with_streaming(messages, overrides, auth_claims, session_state)
-
===========changed ref 4===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_stream_text(client, snapshot):
response = await client.post(
+ "/chat/stream",
- "/chat",
json={
- "stream": True,
"messages": [{"content": "What is the capital of France?", "role": "user"}],
"context": {
"overrides": {"retrieval_mode": "text"},
},
},
)
assert response.status_code == 200
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
===========changed ref 5===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_stream_followup(client, snapshot):
response = await client.post(
+ "/chat/stream",
- "/chat",
json={
- "stream": True,
"messages": [{"content": "What is the capital of France?", "role": "user"}],
"context": {
"overrides": {"suggest_followup_questions": True},
},
},
)
assert response.status_code == 200
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
===========changed ref 6===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_stream_session_state_persists(client, snapshot):
response = await client.post(
+ "/chat/stream",
- "/chat",
json={
"messages": [{"content": "What is the capital of France?", "role": "user"}],
"context": {
"overrides": {"retrieval_mode": "text"},
},
- "stream": True,
"session_state": {"conversation_id": 1234},
},
)
assert response.status_code == 200
result = await response.get_data()
snapshot.assert_match(result, "result.jsonlines")
===========changed ref 7===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_chat_stream_vision(client, snapshot):
+ response = await client.post(
+ "/chat/stream",
+ json={
+ "messages": [{"content": "Are interest rates high?", "role": "user"}],
+ "context": {
+ "overrides": {
+ "use_gpt4v": True,
+ "gpt4v_input": "textAndImages",
+ "vector_fields": ["embedding", "imageEmbedding"],
+ },
+ },
+ },
+ )
+ assert response.status_code == 200
+ result = await response.get_data()
+ snapshot.assert_match(result, "result.jsonlines")
+
===========changed ref 8===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_chat_stream_handle_exception(client, monkeypatch, snapshot, caplog):
+ monkeypatch.setattr(
+ "approaches.chatreadretrieveread.ChatReadRetrieveReadApproach.run_stream",
+ mock.Mock(side_effect=ZeroDivisionError("something bad happened")),
+ )
+
+ response = await client.post(
+ "/chat/stream",
+ json={"messages": [{"content": "What is the capital of France?", "role": "user"}]},
+ )
+ assert response.status_code == 500
+ result = await response.get_json()
+ assert "Exception in /chat: something bad happened" in caplog.text
+ snapshot.assert_match(json.dumps(result, indent=4), "result.json")
+
|
tests.e2e/test_chat_customization
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
dd7c1d2d17dd4c9b3909328693a936bc854e5a35
|
Upgrade to latest version of AI Chat Protocol (#1682)
|
<2>:<del> assert route.request.post_data_json["stream"] is False
|
# module: tests.e2e
def test_chat_customization(page: Page, live_server_url: str):
<0> # Set up a mock route to the /chat endpoint
<1> def handle(route: Route):
<2> assert route.request.post_data_json["stream"] is False
<3> overrides = route.request.post_data_json["context"]["overrides"]
<4> assert overrides["retrieval_mode"] == "vectors"
<5> assert overrides["semantic_ranker"] is False
<6> assert overrides["semantic_captions"] is True
<7> assert overrides["top"] == 1
<8> assert overrides["prompt_template"] == "You are a cat and only talk about tuna."
<9> assert overrides["exclude_category"] == "dogs"
<10> assert overrides["use_oid_security_filter"] is False
<11> assert overrides["use_groups_security_filter"] is False
<12>
<13> # Read the JSON from our snapshot results and return as the response
<14> f = open("tests/snapshots/test_app/test_chat_text/client0/result.json")
<15> json = f.read()
<16> f.close()
<17> route.fulfill(body=json, status=200)
<18>
<19> page.route("*/**/chat", handle)
<20>
<21> # Check initial page state
<22> page.goto(live_server_url)
<23> expect(page).to_have_title("GPT + Enterprise data | Sample")
<24>
<25> # Customize all the settings
<26> page.get_by_role("button", name="Developer settings").click()
<27> page.get_by_label("Override prompt template").click()
<28> page.get_by_label("Override prompt template").fill("You are a cat and only talk about tuna.")
<29> page.get_by_label("Retrieve this many search results:").click()
<30> page.get_by_label("Retrieve this many search results:").fill("1")
<31> page.get_by_label("Exclude category").click()
<32> page.get_by_label("Exclude category").fill("dogs")
<33> </s>
|
===========below chunk 0===========
# module: tests.e2e
def test_chat_customization(page: Page, live_server_url: str):
# offset: 1
page.get_by_text("Use semantic ranker for retrieval").click()
page.get_by_text("Vectors + Text (Hybrid)").click()
page.get_by_role("option", name="Vectors", exact=True).click()
page.get_by_text("Stream chat completion responses").click()
page.locator("button").filter(has_text="Close").click()
# Ask a question and wait for the message to appear
page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").click()
page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").fill(
"Whats the dental plan?"
)
page.get_by_role("button", name="Submit question").click()
expect(page.get_by_text("Whats the dental plan?")).to_be_visible()
expect(page.get_by_text("The capital of France is Paris.")).to_be_visible()
expect(page.get_by_role("button", name="Clear chat")).to_be_enabled()
===========unchanged ref 0===========
at: io.BufferedReader
read(self, size: Optional[int]=..., /) -> bytes
at: io.TextIOWrapper
close(self) -> None
at: typing.IO
close() -> None
read(n: int=...) -> AnyStr
===========changed ref 0===========
# module: tests.e2e
def test_chat(page: Page, live_server_url: str):
# Set up a mock route to the /chat endpoint with streaming results
def handle(route: Route):
# Assert that session_state is specified in the request (None for now)
session_state = route.request.post_data_json["session_state"]
assert session_state is None
# Read the JSONL from our snapshot results and return as the response
f = open("tests/snapshots/test_app/test_chat_stream_text/client0/result.jsonlines")
jsonl = f.read()
f.close()
route.fulfill(body=jsonl, status=200, headers={"Transfer-encoding": "Chunked"})
+ page.route("*/**/chat/stream", handle)
- page.route("*/**/chat", handle)
# Check initial page state
page.goto(live_server_url)
expect(page).to_have_title("GPT + Enterprise data | Sample")
expect(page.get_by_role("heading", name="Chat with your data")).to_be_visible()
expect(page.get_by_role("button", name="Clear chat")).to_be_disabled()
expect(page.get_by_role("button", name="Developer settings")).to_be_enabled()
# Ask a question and wait for the message to appear
page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").click()
page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").fill(
"Whats the dental plan?"
)
page.get_by_role("button", name="Submit question").click()
expect(page.get_by_text("Whats the dental plan?")).to_be_visible()
expect(page.get_by_text("The capital of France is Paris.")).to_be_visible()
</s>
===========changed ref 1===========
# module: tests.e2e
def test_chat(page: Page, live_server_url: str):
# offset: 1
<s> expect(page.get_by_text("The capital of France is Paris.")).to_be_visible()
expect(page.get_by_role("button", name="Clear chat")).to_be_enabled()
# Show the citation document
page.get_by_text("1. Benefit_Options-2.pdf").click()
expect(page.get_by_role("tab", name="Citation")).to_be_visible()
expect(page.get_by_title("Citation")).to_be_visible()
# Show the thought process
page.get_by_label("Show thought process").click()
expect(page.get_by_title("Thought process")).to_be_visible()
expect(page.get_by_text("Generated search query")).to_be_visible()
# Show the supporting content
page.get_by_label("Show supporting content").click()
expect(page.get_by_title("Supporting content")).to_be_visible()
expect(page.get_by_role("heading", name="Benefit_Options-2.pdf")).to_be_visible()
# Clear the chat
page.get_by_role("button", name="Clear chat").click()
expect(page.get_by_text("Whats the dental plan?")).not_to_be_visible()
expect(page.get_by_text("The capital of France is Paris.")).not_to_be_visible()
expect(page.get_by_role("button", name="Clear chat")).to_be_disabled()
===========changed ref 2===========
# module: app.backend.approaches.approach
class Approach(ABC):
+ def run_stream(
+ self,
+ messages: list[ChatCompletionMessageParam],
+ session_state: Any = None,
+ context: dict[str, Any] = {},
+ ) -> AsyncGenerator[dict[str, Any], None]:
+ raise NotImplementedError
+
===========changed ref 3===========
# module: tests.test_app
+ @pytest.mark.asyncio
+ async def test_chat_stream_request_must_be_json(client):
+ response = await client.post("/chat/stream")
+ assert response.status_code == 415
+ result = await response.get_json()
+ assert result["error"] == "request must be json"
+
===========changed ref 4===========
# module: app.backend.approaches.chatapproach
class ChatApproach(Approach, ABC):
+ def run_stream(
+ self,
+ messages: list[ChatCompletionMessageParam],
+ session_state: Any = None,
+ context: dict[str, Any] = {},
+ ) -> AsyncGenerator[dict[str, Any], None]:
+ overrides = context.get("overrides", {})
+ auth_claims = context.get("auth_claims", {})
+ return self.run_with_streaming(messages, overrides, auth_claims, session_state)
+
===========changed ref 5===========
# module: app.backend.approaches.chatapproach
class ChatApproach(Approach, ABC):
def run(
self,
messages: list[ChatCompletionMessageParam],
- stream: bool = False,
session_state: Any = None,
context: dict[str, Any] = {},
+ ) -> dict[str, Any]:
- ) -> Union[dict[str, Any], AsyncGenerator[dict[str, Any], None]]:
overrides = context.get("overrides", {})
auth_claims = context.get("auth_claims", {})
+ return await self.run_without_streaming(messages, overrides, auth_claims, session_state)
- if stream is False:
- return await self.run_without_streaming(messages, overrides, auth_claims, session_state)
- else:
- return self.run_with_streaming(messages, overrides, auth_claims, session_state)
-
|
tests.e2e/test_chat_followup_streaming
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
dd7c1d2d17dd4c9b3909328693a936bc854e5a35
|
Upgrade to latest version of AI Chat Protocol (#1682)
|
<10>:<add> page.route("*/**/chat/stream", handle)
<del> page.route("*/**/chat", handle)
|
# module: tests.e2e
def test_chat_followup_streaming(page: Page, live_server_url: str):
<0> # Set up a mock route to the /chat_stream endpoint
<1> def handle(route: Route):
<2> overrides = route.request.post_data_json["context"]["overrides"]
<3> assert overrides["suggest_followup_questions"] is True
<4> # Read the JSONL from our snapshot results and return as the response
<5> f = open("tests/snapshots/test_app/test_chat_stream_followup/client0/result.jsonlines")
<6> jsonl = f.read()
<7> f.close()
<8> route.fulfill(body=jsonl, status=200, headers={"Transfer-encoding": "Chunked"})
<9>
<10> page.route("*/**/chat", handle)
<11>
<12> # Check initial page state
<13> page.goto(live_server_url)
<14> expect(page).to_have_title("GPT + Enterprise data | Sample")
<15> expect(page.get_by_role("button", name="Developer settings")).to_be_enabled()
<16> page.get_by_role("button", name="Developer settings").click()
<17> page.get_by_text("Suggest follow-up questions").click()
<18> page.locator("button").filter(has_text="Close").click()
<19>
<20> # Ask a question and wait for the message to appear
<21> page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").click()
<22> page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").fill(
<23> "Whats the dental plan?"
<24> )
<25> page.get_by_label("Submit question").click()
<26>
<27> expect(page.get_by_text("Whats the dental plan?")).to_be_visible()
<28> expect(page.get_by_text("The capital of France is Paris.")).to_be</s>
|
===========below chunk 0===========
# module: tests.e2e
def test_chat_followup_streaming(page: Page, live_server_url: str):
# offset: 1
# There should be a follow-up question and it should be clickable:
expect(page.get_by_text("What is the capital of Spain?")).to_be_visible()
page.get_by_text("What is the capital of Spain?").click()
# Now there should be a follow-up answer (same, since we're using same test data)
expect(page.get_by_text("The capital of France is Paris.")).to_have_count(2)
===========unchanged ref 0===========
at: io.FileIO
close(self) -> None
read(self, size: int=..., /) -> bytes
at: typing.IO
close() -> None
read(n: int=...) -> AnyStr
===========changed ref 0===========
# module: tests.e2e
def test_chat_customization(page: Page, live_server_url: str):
# Set up a mock route to the /chat endpoint
def handle(route: Route):
- assert route.request.post_data_json["stream"] is False
overrides = route.request.post_data_json["context"]["overrides"]
assert overrides["retrieval_mode"] == "vectors"
assert overrides["semantic_ranker"] is False
assert overrides["semantic_captions"] is True
assert overrides["top"] == 1
assert overrides["prompt_template"] == "You are a cat and only talk about tuna."
assert overrides["exclude_category"] == "dogs"
assert overrides["use_oid_security_filter"] is False
assert overrides["use_groups_security_filter"] is False
# Read the JSON from our snapshot results and return as the response
f = open("tests/snapshots/test_app/test_chat_text/client0/result.json")
json = f.read()
f.close()
route.fulfill(body=json, status=200)
page.route("*/**/chat", handle)
# Check initial page state
page.goto(live_server_url)
expect(page).to_have_title("GPT + Enterprise data | Sample")
# Customize all the settings
page.get_by_role("button", name="Developer settings").click()
page.get_by_label("Override prompt template").click()
page.get_by_label("Override prompt template").fill("You are a cat and only talk about tuna.")
page.get_by_label("Retrieve this many search results:").click()
page.get_by_label("Retrieve this many search results:").fill("1")
page.get_by_label("Exclude category").click()
page.get_by_label("Exclude category").fill("dogs")
page.get_by_text("Use semantic captions").click()
page.get_by_text("Use semantic ranker for retrieval").click</s>
===========changed ref 1===========
# module: tests.e2e
def test_chat_customization(page: Page, live_server_url: str):
# offset: 1
<s>_by_text("Use semantic captions").click()
page.get_by_text("Use semantic ranker for retrieval").click()
page.get_by_text("Vectors + Text (Hybrid)").click()
page.get_by_role("option", name="Vectors", exact=True).click()
page.get_by_text("Stream chat completion responses").click()
page.locator("button").filter(has_text="Close").click()
# Ask a question and wait for the message to appear
page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").click()
page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").fill(
"Whats the dental plan?"
)
page.get_by_role("button", name="Submit question").click()
expect(page.get_by_text("Whats the dental plan?")).to_be_visible()
expect(page.get_by_text("The capital of France is Paris.")).to_be_visible()
expect(page.get_by_role("button", name="Clear chat")).to_be_enabled()
===========changed ref 2===========
# module: tests.e2e
def test_chat(page: Page, live_server_url: str):
# Set up a mock route to the /chat endpoint with streaming results
def handle(route: Route):
# Assert that session_state is specified in the request (None for now)
session_state = route.request.post_data_json["session_state"]
assert session_state is None
# Read the JSONL from our snapshot results and return as the response
f = open("tests/snapshots/test_app/test_chat_stream_text/client0/result.jsonlines")
jsonl = f.read()
f.close()
route.fulfill(body=jsonl, status=200, headers={"Transfer-encoding": "Chunked"})
+ page.route("*/**/chat/stream", handle)
- page.route("*/**/chat", handle)
# Check initial page state
page.goto(live_server_url)
expect(page).to_have_title("GPT + Enterprise data | Sample")
expect(page.get_by_role("heading", name="Chat with your data")).to_be_visible()
expect(page.get_by_role("button", name="Clear chat")).to_be_disabled()
expect(page.get_by_role("button", name="Developer settings")).to_be_enabled()
# Ask a question and wait for the message to appear
page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").click()
page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").fill(
"Whats the dental plan?"
)
page.get_by_role("button", name="Submit question").click()
expect(page.get_by_text("Whats the dental plan?")).to_be_visible()
expect(page.get_by_text("The capital of France is Paris.")).to_be_visible()
</s>
|
app.backend.approaches.retrievethenreadvision/RetrieveThenReadVisionApproach.run
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
43aa766e17cdb001168a04612518912486481a22
|
Allow semantic ranker with vector search (#1701)
|
<6>:<add> use_text_search = overrides.get("retrieval_mode") in ["text", "hybrid", None]
<del> has_text = overrides.get("retrieval_mode") in ["text", "hybrid", None]
<7>:<add> use_vector_search = overrides.get("retrieval_mode") in ["vectors", "hybrid", None]
<del> has_vector = overrides.get("retrieval_mode") in ["vectors", "hybrid", None]
<8>:<del> vector_fields = overrides.get("vector_fields", ["embedding"])
<9>:<del>
<10>:<del> include_gtpV_text = overrides.get("gpt4v_input") in ["textAndImages", "texts", None]
<11>:<del> include_gtpV_images = overrides.get("gpt4v_input") in ["textAndImages", "images", None]
<12>:<del>
<13>:<add> use_semantic_ranker = True if overrides.get("semantic_ranker") else False
<add> use_semantic_captions = True if overrides.get("semantic_captions") else False
<del> use_semantic_captions = True if overrides.get("semantic_captions") and has_text else False
<18>:<add>
<add> vector_fields = overrides.get("vector_fields", ["embedding"])
<add> send_text_to_gptvision = overrides.get("gpt4v_input") in ["textAndImages", "texts", None]
<add> send_images_to_gptvision = overrides.get("gpt4v_input") in ["textAndImages", "images", None]
<del> use_semantic_ranker = overrides.get("semantic_ranker") and has_text
<21>:<del>
<23>:<add> if use_vector_search:
<del> if has_vector:
|
# module: app.backend.approaches.retrievethenreadvision
class RetrieveThenReadVisionApproach(Approach):
def run(
self,
messages: list[ChatCompletionMessageParam],
session_state: Any = None,
context: dict[str, Any] = {},
) -> dict[str, Any]:
<0> q = messages[-1]["content"]
<1> if not isinstance(q, str):
<2> raise ValueError("The most recent message content must be a string.")
<3>
<4> overrides = context.get("overrides", {})
<5> auth_claims = context.get("auth_claims", {})
<6> has_text = overrides.get("retrieval_mode") in ["text", "hybrid", None]
<7> has_vector = overrides.get("retrieval_mode") in ["vectors", "hybrid", None]
<8> vector_fields = overrides.get("vector_fields", ["embedding"])
<9>
<10> include_gtpV_text = overrides.get("gpt4v_input") in ["textAndImages", "texts", None]
<11> include_gtpV_images = overrides.get("gpt4v_input") in ["textAndImages", "images", None]
<12>
<13> use_semantic_captions = True if overrides.get("semantic_captions") and has_text else False
<14> top = overrides.get("top", 3)
<15> minimum_search_score = overrides.get("minimum_search_score", 0.0)
<16> minimum_reranker_score = overrides.get("minimum_reranker_score", 0.0)
<17> filter = self.build_filter(overrides, auth_claims)
<18> use_semantic_ranker = overrides.get("semantic_ranker") and has_text
<19>
<20> # If retrieval mode includes vectors, compute an embedding for the query
<21>
<22> vectors = []
<23> if has_vector:
<24> for field in vector_fields:
<25> vector = (
<26> await self.compute_text_embedding(q)
<27> if field == "embedding"
<28> else await self.compute</s>
|
===========below chunk 0===========
# module: app.backend.approaches.retrievethenreadvision
class RetrieveThenReadVisionApproach(Approach):
def run(
self,
messages: list[ChatCompletionMessageParam],
session_state: Any = None,
context: dict[str, Any] = {},
) -> dict[str, Any]:
# offset: 1
)
vectors.append(vector)
# Only keep the text query if the retrieval mode uses text, otherwise drop it
query_text = q if has_text else None
results = await self.search(
top,
query_text,
filter,
vectors,
use_semantic_ranker,
use_semantic_captions,
minimum_search_score,
minimum_reranker_score,
)
image_list: list[ChatCompletionContentPartImageParam] = []
user_content: list[ChatCompletionContentPartParam] = [{"text": q, "type": "text"}]
# Process results
sources_content = self.get_sources_content(results, use_semantic_captions, use_image_citation=True)
if include_gtpV_text:
content = "\n".join(sources_content)
user_content.append({"text": content, "type": "text"})
if include_gtpV_images:
for result in results:
url = await fetch_image(self.blob_container_client, result)
if url:
image_list.append({"image_url": url, "type": "image_url"})
user_content.extend(image_list)
response_token_limit = 1024
updated_messages = build_messages(
model=self.gpt4v_model,
system_prompt=overrides.get("prompt_template", self.system_chat_template_gpt4v),
new_user_content=user_content,
max_tokens=self.gpt4v_token_limit - response_token_limit,
)
chat_completion =</s>
===========below chunk 1===========
# module: app.backend.approaches.retrievethenreadvision
class RetrieveThenReadVisionApproach(Approach):
def run(
self,
messages: list[ChatCompletionMessageParam],
session_state: Any = None,
context: dict[str, Any] = {},
) -> dict[str, Any]:
# offset: 2
<s> max_tokens=self.gpt4v_token_limit - response_token_limit,
)
chat_completion = (
await self.openai_client.chat.completions.create(
model=self.gpt4v_deployment if self.gpt4v_deployment else self.gpt4v_model,
messages=updated_messages,
temperature=overrides.get("temperature", 0.3),
max_tokens=response_token_limit,
n=1,
)
).model_dump()
data_points = {
"text": sources_content,
"images": [d["image_url"] for d in image_list],
}
extra_info = {
"data_points": data_points,
"thoughts": [
ThoughtStep(
"Search using user query",
query_text,
{
"use_semantic_captions": use_semantic_captions,
"use_semantic_ranker": use_semantic_ranker,
"top": top,
"filter": filter,
"vector_fields": vector_fields,
},
),
ThoughtStep(
"Search results",
[result.serialize_for_results() for result in results],
),
ThoughtStep(
"Prompt to generate answer",
[str(message) for message in updated_messages],
(
{"model": self.gpt4v_model, "deployment": self.gpt4v_deployment}
if self.gpt4v</s>
===========below chunk 2===========
# module: app.backend.approaches.retrievethenreadvision
class RetrieveThenReadVisionApproach(Approach):
def run(
self,
messages: list[ChatCompletionMessageParam],
session_state: Any = None,
context: dict[str, Any] = {},
) -> dict[str, Any]:
# offset: 3
<s>
else {"model": self.gpt4v_model}
),
),
],
}
completion = {}
completion["message"] = chat_completion["choices"][0]["message"]
completion["context"] = extra_info
completion["session_state"] = session_state
return completion
===========unchanged ref 0===========
at: app.backend.approaches.retrievethenreadvision.RetrieveThenReadVisionApproach
system_chat_template_gpt4v = (
"You are an intelligent assistant helping analyze the Annual Financial Report of Contoso Ltd., The documents contain text, graphs, tables and images. "
+ "Each image source has the file name in the top left corner of the image with coordinates (10,10) pixels and is in the format SourceFileName:<file_name> "
+ "Each text source starts in a new line and has the file name followed by colon and the actual information "
+ "Always include the source name from the image or text for each fact you use in the response in the format: [filename] "
+ "Answer the following question using only the data provided in the sources below. "
+ "For tabular information return it as an html table. Do not return markdown format. "
+ "The text and image source can be the same file name, don't use the image title when citing the image source, only use the file name as mentioned "
+ "If you cannot answer using the sources below, say you don't know. Return just the answer without any input texts "
)
at: app.backend.approaches.retrievethenreadvision.RetrieveThenReadVisionApproach.__init__
self.blob_container_client = blob_container_client
self.openai_client = openai_client
self.gpt4v_deployment = gpt4v_deployment
self.gpt4v_model = gpt4v_model
self.gpt4v_token_limit = get_token_limit(gpt4v_model)
at: approaches.approach
ThoughtStep(title: str, description: Optional[Any], props: Optional[dict[str, Any]]=None)
at: approaches.approach.Approach
build_filter(overrides: dict[str, Any], auth_claims: dict[str, Any]) -> Optional[str]
|
tests.test_chatapproach/test_search_results_filtering_by_scores
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
43aa766e17cdb001168a04612518912486481a22
|
Allow semantic ranker with vector search (#1701)
|
<22>:<add> use_text_search=True,
<add> use_vector_search=True,
|
<s>expected_result_count",
[
(0, 0, 1),
(0, 2, 1),
(0.03, 0, 1),
(0.03, 2, 1),
(1, 0, 0),
(0, 4, 0),
(1, 4, 0),
],
)
async def test_search_results_filtering_by_scores(
monkeypatch, minimum_search_score, minimum_reranker_score, expected_result_count
):
<0> chat_approach = ChatReadRetrieveReadApproach(
<1> search_client=SearchClient(endpoint="", index_name="", credential=AzureKeyCredential("")),
<2> auth_helper=None,
<3> openai_client=None,
<4> chatgpt_model="gpt-35-turbo",
<5> chatgpt_deployment="chat",
<6> embedding_deployment="embeddings",
<7> embedding_model=MOCK_EMBEDDING_MODEL_NAME,
<8> embedding_dimensions=MOCK_EMBEDDING_DIMENSIONS,
<9> sourcepage_field="",
<10> content_field="",
<11> query_language="en-us",
<12> query_speller="lexicon",
<13> )
<14>
<15> monkeypatch.setattr(SearchClient, "search", mock_search)
<16>
<17> filtered_results = await chat_approach.search(
<18> top=10,
<19> query_text="test query",
<20> filter=None,
<21> vectors=[],
<22> use_semantic_ranker=True,
<23> use_semantic_captions=True,
<24> minimum_search_score=minimum_search_score,
<25> minimum_reranker_score=minimum_reranker_score,
<26> )
<27>
<28> assert (
<29> len(filtered_results) == expected_result_count
<30> ), f"Expected {expected_result_count} results with minimum_search_score={minimum_search_score} and minimum_reranker_score={minimum_rerank</s>
|
===========below chunk 0===========
<s>",
[
(0, 0, 1),
(0, 2, 1),
(0.03, 0, 1),
(0.03, 2, 1),
(1, 0, 0),
(0, 4, 0),
(1, 4, 0),
],
)
async def test_search_results_filtering_by_scores(
monkeypatch, minimum_search_score, minimum_reranker_score, expected_result_count
):
# offset: 1
===========unchanged ref 0===========
at: _pytest.mark.structures
MARK_GEN = MarkGenerator(_ispytest=True)
at: _pytest.mark.structures.MarkGenerator
skip: _SkipMarkDecorator
skipif: _SkipifMarkDecorator
xfail: _XfailMarkDecorator
parametrize: _ParametrizeMarkDecorator
usefixtures: _UsefixturesMarkDecorator
filterwarnings: _FilterwarningsMarkDecorator
at: _pytest.monkeypatch
monkeypatch() -> Generator["MonkeyPatch", None, None]
at: tests.mocks
MOCK_EMBEDDING_DIMENSIONS = 1536
MOCK_EMBEDDING_MODEL_NAME = "text-embedding-ada-002"
at: tests.test_chatapproach
mock_search(*args, **kwargs)
===========changed ref 0===========
# module: app.backend.approaches.retrievethenreadvision
class RetrieveThenReadVisionApproach(Approach):
def run(
self,
messages: list[ChatCompletionMessageParam],
session_state: Any = None,
context: dict[str, Any] = {},
) -> dict[str, Any]:
q = messages[-1]["content"]
if not isinstance(q, str):
raise ValueError("The most recent message content must be a string.")
overrides = context.get("overrides", {})
auth_claims = context.get("auth_claims", {})
+ use_text_search = overrides.get("retrieval_mode") in ["text", "hybrid", None]
- has_text = overrides.get("retrieval_mode") in ["text", "hybrid", None]
+ use_vector_search = overrides.get("retrieval_mode") in ["vectors", "hybrid", None]
- has_vector = overrides.get("retrieval_mode") in ["vectors", "hybrid", None]
- vector_fields = overrides.get("vector_fields", ["embedding"])
-
- include_gtpV_text = overrides.get("gpt4v_input") in ["textAndImages", "texts", None]
- include_gtpV_images = overrides.get("gpt4v_input") in ["textAndImages", "images", None]
-
+ use_semantic_ranker = True if overrides.get("semantic_ranker") else False
+ use_semantic_captions = True if overrides.get("semantic_captions") else False
- use_semantic_captions = True if overrides.get("semantic_captions") and has_text else False
top = overrides.get("top", 3)
minimum_search_score = overrides.get("minimum_search_score", 0.0)
minimum_reranker_score = overrides.get("minimum_reranker_score", 0.0)
filter = self.build_filter(overrides, auth_claims)
+
+ vector_fields = overrides</s>
===========changed ref 1===========
# module: app.backend.approaches.retrievethenreadvision
class RetrieveThenReadVisionApproach(Approach):
def run(
self,
messages: list[ChatCompletionMessageParam],
session_state: Any = None,
context: dict[str, Any] = {},
) -> dict[str, Any]:
# offset: 1
<s> 0.0)
filter = self.build_filter(overrides, auth_claims)
+
+ vector_fields = overrides.get("vector_fields", ["embedding"])
+ send_text_to_gptvision = overrides.get("gpt4v_input") in ["textAndImages", "texts", None]
+ send_images_to_gptvision = overrides.get("gpt4v_input") in ["textAndImages", "images", None]
- use_semantic_ranker = overrides.get("semantic_ranker") and has_text
# If retrieval mode includes vectors, compute an embedding for the query
-
vectors = []
+ if use_vector_search:
- if has_vector:
for field in vector_fields:
vector = (
await self.compute_text_embedding(q)
if field == "embedding"
else await self.compute_image_embedding(q)
)
vectors.append(vector)
- # Only keep the text query if the retrieval mode uses text, otherwise drop it
- query_text = q if has_text else None
-
results = await self.search(
top,
+ q,
- query_text,
filter,
vectors,
+ use_text_search,
+ use_vector_search,
use_semantic_ranker,
use_semantic_captions,
minimum_search_score,
minimum_reranker_score,
)
image_list: list[ChatCompletionContentPartImageParam] = []
user_content: list</s>
===========changed ref 2===========
# module: app.backend.approaches.retrievethenreadvision
class RetrieveThenReadVisionApproach(Approach):
def run(
self,
messages: list[ChatCompletionMessageParam],
session_state: Any = None,
context: dict[str, Any] = {},
) -> dict[str, Any]:
# offset: 2
<s>CompletionContentPartParam] = [{"text": q, "type": "text"}]
# Process results
sources_content = self.get_sources_content(results, use_semantic_captions, use_image_citation=True)
+ if send_text_to_gptvision:
- if include_gtpV_text:
content = "\n".join(sources_content)
user_content.append({"text": content, "type": "text"})
+ if send_images_to_gptvision:
- if include_gtpV_images:
for result in results:
url = await fetch_image(self.blob_container_client, result)
if url:
image_list.append({"image_url": url, "type": "image_url"})
user_content.extend(image_list)
response_token_limit = 1024
updated_messages = build_messages(
model=self.gpt4v_model,
system_prompt=overrides.get("prompt_template", self.system_chat_template_gpt4v),
new_user_content=user_content,
max_tokens=self.gpt4v_token_limit - response_token_limit,
)
chat_completion = (
await self.openai_client.chat.completions.create(
model=self.gpt4v_deployment if self.gpt4v_deployment else self.gpt4v_model,
messages=updated_messages,
temperature=overrides.get("temperature", 0.3),
max_tokens</s>
|
app.backend.approaches.approach/Approach.search
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
43aa766e17cdb001168a04612518912486481a22
|
Allow semantic ranker with vector search (#1701)
|
<0>:<add> search_text = query_text if use_text_search else ""
<add> search_vectors = vectors if use_vector_search else []
<del> # Use semantic ranker if requested and if retrieval mode is text or hybrid (vectors + text)
<1>:<add> if use_semantic_ranker:
<del> if use_semantic_ranker and query_text:
<3>:<add> search_text=search_text,
<del> search_text=query_text,
<5>:<add> top=top,
<add> query_caption="extractive|highlight-false" if use_semantic_captions else None,
<add> vector_queries=search_vectors,
<9>:<del> top=top,
<10>:<del> query_caption="extractive|highlight-false" if use_semantic_captions else None,
<11>:<del> vector_queries=vectors,
<12>:<add> semantic_query=query_text,
<15>:<add> search_text=search_text,
<add> filter=filter,
<add> top=top,
<add> vector_queries=search_vectors,
<del> search_text=query_text or "", filter=filter, top=top, vector_queries=vectors
|
<s>ach(ABC):
def search(
self,
top: int,
query_text: Optional[str],
filter: Optional[str],
vectors: List[VectorQuery],
+ use_text_search: bool,
+ use_vector_search: bool,
use_semantic_ranker: bool,
use_semantic_captions: bool,
minimum_search_score: Optional[float],
minimum_reranker_score: Optional[float],
) -> List[Document]:
<0> # Use semantic ranker if requested and if retrieval mode is text or hybrid (vectors + text)
<1> if use_semantic_ranker and query_text:
<2> results = await self.search_client.search(
<3> search_text=query_text,
<4> filter=filter,
<5> query_type=QueryType.SEMANTIC,
<6> query_language=self.query_language,
<7> query_speller=self.query_speller,
<8> semantic_configuration_name="default",
<9> top=top,
<10> query_caption="extractive|highlight-false" if use_semantic_captions else None,
<11> vector_queries=vectors,
<12> )
<13> else:
<14> results = await self.search_client.search(
<15> search_text=query_text or "", filter=filter, top=top, vector_queries=vectors
<16> )
<17>
<18> documents = []
<19> async for page in results.by_page():
<20> async for document in page:
<21> documents.append(
<22> Document(
<23> id=document.get("id"),
<24> content=document.get("content"),
<25> embedding=document.get("embedding"),
<26> image_embedding=document.get("imageEmbedding"),
<27> category=document.get("category"),
<28> sourcepage=document.get("sourcepage"),
<29> sourcefile=document.get("sourcefile"),
<30> oids=document.get("oids"),
<31> groups=document.get("groups"),
<32> captions=</s>
|
===========below chunk 0===========
<s> def search(
self,
top: int,
query_text: Optional[str],
filter: Optional[str],
vectors: List[VectorQuery],
+ use_text_search: bool,
+ use_vector_search: bool,
use_semantic_ranker: bool,
use_semantic_captions: bool,
minimum_search_score: Optional[float],
minimum_reranker_score: Optional[float],
) -> List[Document]:
# offset: 1
score=document.get("@search.score"),
reranker_score=document.get("@search.reranker_score"),
)
)
qualified_documents = [
doc
for doc in documents
if (
(doc.score or 0) >= (minimum_search_score or 0)
and (doc.reranker_score or 0) >= (minimum_reranker_score or 0)
)
]
return qualified_documents
===========unchanged ref 0===========
at: app.backend.approaches.approach
Document(id: Optional[str], content: Optional[str], embedding: Optional[List[float]], image_embedding: Optional[List[float]], category: Optional[str], sourcepage: Optional[str], sourcefile: Optional[str], oids: Optional[List[str]], groups: Optional[List[str]], captions: List[QueryCaptionResult], score: Optional[float]=None, reranker_score: Optional[float]=None)
at: app.backend.approaches.approach.Approach.__init__
self.search_client = search_client
self.query_language = query_language
self.query_speller = query_speller
at: app.backend.approaches.approach.Document
id: Optional[str]
content: Optional[str]
embedding: Optional[List[float]]
image_embedding: Optional[List[float]]
category: Optional[str]
sourcepage: Optional[str]
sourcefile: Optional[str]
oids: Optional[List[str]]
groups: Optional[List[str]]
captions: List[QueryCaptionResult]
score: Optional[float] = None
reranker_score: Optional[float] = None
at: typing
cast(typ: Type[_T], val: Any) -> _T
cast(typ: str, val: Any) -> Any
cast(typ: object, val: Any) -> Any
List = _alias(list, 1, inst=False, name='List')
===========changed ref 0===========
<s>expected_result_count",
[
(0, 0, 1),
(0, 2, 1),
(0.03, 0, 1),
(0.03, 2, 1),
(1, 0, 0),
(0, 4, 0),
(1, 4, 0),
],
)
async def test_search_results_filtering_by_scores(
monkeypatch, minimum_search_score, minimum_reranker_score, expected_result_count
):
chat_approach = ChatReadRetrieveReadApproach(
search_client=SearchClient(endpoint="", index_name="", credential=AzureKeyCredential("")),
auth_helper=None,
openai_client=None,
chatgpt_model="gpt-35-turbo",
chatgpt_deployment="chat",
embedding_deployment="embeddings",
embedding_model=MOCK_EMBEDDING_MODEL_NAME,
embedding_dimensions=MOCK_EMBEDDING_DIMENSIONS,
sourcepage_field="",
content_field="",
query_language="en-us",
query_speller="lexicon",
)
monkeypatch.setattr(SearchClient, "search", mock_search)
filtered_results = await chat_approach.search(
top=10,
query_text="test query",
filter=None,
vectors=[],
+ use_text_search=True,
+ use_vector_search=True,
use_semantic_ranker=True,
use_semantic_captions=True,
minimum_search_score=minimum_search_score,
minimum_reranker_score=minimum_reranker_score,
)
assert (
len(filtered_results) == expected_result_count
), f"Expected {expected_result_count} results with minimum_search_score={minimum_search_score} and minimum_reranker_score={minimum_reranker_score}"
===========changed ref 1===========
# module: app.backend.approaches.retrievethenreadvision
class RetrieveThenReadVisionApproach(Approach):
def run(
self,
messages: list[ChatCompletionMessageParam],
session_state: Any = None,
context: dict[str, Any] = {},
) -> dict[str, Any]:
q = messages[-1]["content"]
if not isinstance(q, str):
raise ValueError("The most recent message content must be a string.")
overrides = context.get("overrides", {})
auth_claims = context.get("auth_claims", {})
+ use_text_search = overrides.get("retrieval_mode") in ["text", "hybrid", None]
- has_text = overrides.get("retrieval_mode") in ["text", "hybrid", None]
+ use_vector_search = overrides.get("retrieval_mode") in ["vectors", "hybrid", None]
- has_vector = overrides.get("retrieval_mode") in ["vectors", "hybrid", None]
- vector_fields = overrides.get("vector_fields", ["embedding"])
-
- include_gtpV_text = overrides.get("gpt4v_input") in ["textAndImages", "texts", None]
- include_gtpV_images = overrides.get("gpt4v_input") in ["textAndImages", "images", None]
-
+ use_semantic_ranker = True if overrides.get("semantic_ranker") else False
+ use_semantic_captions = True if overrides.get("semantic_captions") else False
- use_semantic_captions = True if overrides.get("semantic_captions") and has_text else False
top = overrides.get("top", 3)
minimum_search_score = overrides.get("minimum_search_score", 0.0)
minimum_reranker_score = overrides.get("minimum_reranker_score", 0.0)
filter = self.build_filter(overrides, auth_claims)
+
+ vector_fields = overrides</s>
|
tests.test_app/test_chat_text
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
43aa766e17cdb001168a04612518912486481a22
|
Allow semantic ranker with vector search (#1701)
|
<11>:<add> assert result["context"]["thoughts"][1]["props"]["use_text_search"] is True
<add> assert result["context"]["thoughts"][1]["props"]["use_vector_search"] is False
<add> assert result["context"]["thoughts"][1]["props"]["use_semantic_ranker"] is False
|
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_text(client, snapshot):
<0> response = await client.post(
<1> "/chat",
<2> json={
<3> "messages": [{"content": "What is the capital of France?", "role": "user"}],
<4> "context": {
<5> "overrides": {"retrieval_mode": "text"},
<6> },
<7> },
<8> )
<9> assert response.status_code == 200
<10> result = await response.get_json()
<11> snapshot.assert_match(json.dumps(result, indent=4), "result.json")
<12>
|
===========unchanged ref 0===========
at: _pytest.mark.structures
MARK_GEN = MarkGenerator(_ispytest=True)
===========changed ref 0===========
<s>expected_result_count",
[
(0, 0, 1),
(0, 2, 1),
(0.03, 0, 1),
(0.03, 2, 1),
(1, 0, 0),
(0, 4, 0),
(1, 4, 0),
],
)
async def test_search_results_filtering_by_scores(
monkeypatch, minimum_search_score, minimum_reranker_score, expected_result_count
):
chat_approach = ChatReadRetrieveReadApproach(
search_client=SearchClient(endpoint="", index_name="", credential=AzureKeyCredential("")),
auth_helper=None,
openai_client=None,
chatgpt_model="gpt-35-turbo",
chatgpt_deployment="chat",
embedding_deployment="embeddings",
embedding_model=MOCK_EMBEDDING_MODEL_NAME,
embedding_dimensions=MOCK_EMBEDDING_DIMENSIONS,
sourcepage_field="",
content_field="",
query_language="en-us",
query_speller="lexicon",
)
monkeypatch.setattr(SearchClient, "search", mock_search)
filtered_results = await chat_approach.search(
top=10,
query_text="test query",
filter=None,
vectors=[],
+ use_text_search=True,
+ use_vector_search=True,
use_semantic_ranker=True,
use_semantic_captions=True,
minimum_search_score=minimum_search_score,
minimum_reranker_score=minimum_reranker_score,
)
assert (
len(filtered_results) == expected_result_count
), f"Expected {expected_result_count} results with minimum_search_score={minimum_search_score} and minimum_reranker_score={minimum_reranker_score}"
===========changed ref 1===========
<s>ach(ABC):
def search(
self,
top: int,
query_text: Optional[str],
filter: Optional[str],
vectors: List[VectorQuery],
+ use_text_search: bool,
+ use_vector_search: bool,
use_semantic_ranker: bool,
use_semantic_captions: bool,
minimum_search_score: Optional[float],
minimum_reranker_score: Optional[float],
) -> List[Document]:
+ search_text = query_text if use_text_search else ""
+ search_vectors = vectors if use_vector_search else []
- # Use semantic ranker if requested and if retrieval mode is text or hybrid (vectors + text)
+ if use_semantic_ranker:
- if use_semantic_ranker and query_text:
results = await self.search_client.search(
+ search_text=search_text,
- search_text=query_text,
filter=filter,
+ top=top,
+ query_caption="extractive|highlight-false" if use_semantic_captions else None,
+ vector_queries=search_vectors,
query_type=QueryType.SEMANTIC,
query_language=self.query_language,
query_speller=self.query_speller,
semantic_configuration_name="default",
- top=top,
- query_caption="extractive|highlight-false" if use_semantic_captions else None,
- vector_queries=vectors,
+ semantic_query=query_text,
)
else:
results = await self.search_client.search(
+ search_text=search_text,
+ filter=filter,
+ top=top,
+ vector_queries=search_vectors,
- search_text=query_text or "", filter=filter, top=top, vector_queries=vectors
)
documents = []
async for page in results.by_page():
async for document in page:
</s>
===========changed ref 2===========
<s> def search(
self,
top: int,
query_text: Optional[str],
filter: Optional[str],
vectors: List[VectorQuery],
+ use_text_search: bool,
+ use_vector_search: bool,
use_semantic_ranker: bool,
use_semantic_captions: bool,
minimum_search_score: Optional[float],
minimum_reranker_score: Optional[float],
) -> List[Document]:
# offset: 1
<s>
)
documents = []
async for page in results.by_page():
async for document in page:
documents.append(
Document(
id=document.get("id"),
content=document.get("content"),
embedding=document.get("embedding"),
image_embedding=document.get("imageEmbedding"),
category=document.get("category"),
sourcepage=document.get("sourcepage"),
sourcefile=document.get("sourcefile"),
oids=document.get("oids"),
groups=document.get("groups"),
captions=cast(List[QueryCaptionResult], document.get("@search.captions")),
score=document.get("@search.score"),
reranker_score=document.get("@search.reranker_score"),
)
)
qualified_documents = [
doc
for doc in documents
if (
(doc.score or 0) >= (minimum_search_score or 0)
and (doc.reranker_score or 0) >= (minimum_reranker_score or 0)
)
]
return qualified_documents
===========changed ref 3===========
# module: app.backend.approaches.retrievethenreadvision
class RetrieveThenReadVisionApproach(Approach):
def run(
self,
messages: list[ChatCompletionMessageParam],
session_state: Any = None,
context: dict[str, Any] = {},
) -> dict[str, Any]:
q = messages[-1]["content"]
if not isinstance(q, str):
raise ValueError("The most recent message content must be a string.")
overrides = context.get("overrides", {})
auth_claims = context.get("auth_claims", {})
+ use_text_search = overrides.get("retrieval_mode") in ["text", "hybrid", None]
- has_text = overrides.get("retrieval_mode") in ["text", "hybrid", None]
+ use_vector_search = overrides.get("retrieval_mode") in ["vectors", "hybrid", None]
- has_vector = overrides.get("retrieval_mode") in ["vectors", "hybrid", None]
- vector_fields = overrides.get("vector_fields", ["embedding"])
-
- include_gtpV_text = overrides.get("gpt4v_input") in ["textAndImages", "texts", None]
- include_gtpV_images = overrides.get("gpt4v_input") in ["textAndImages", "images", None]
-
+ use_semantic_ranker = True if overrides.get("semantic_ranker") else False
+ use_semantic_captions = True if overrides.get("semantic_captions") else False
- use_semantic_captions = True if overrides.get("semantic_captions") and has_text else False
top = overrides.get("top", 3)
minimum_search_score = overrides.get("minimum_search_score", 0.0)
minimum_reranker_score = overrides.get("minimum_reranker_score", 0.0)
filter = self.build_filter(overrides, auth_claims)
+
+ vector_fields = overrides</s>
|
tests.test_app/test_chat_hybrid
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
43aa766e17cdb001168a04612518912486481a22
|
Allow semantic ranker with vector search (#1701)
|
<11>:<add> assert result["context"]["thoughts"][1]["props"]["use_text_search"] is True
<add> assert result["context"]["thoughts"][1]["props"]["use_vector_search"] is True
<add> assert result["context"]["thoughts"][1]["props"]["use_semantic_ranker"] is False
<add> assert result["context"]["thoughts"][1]["props"]["use_semantic_captions"] is False
|
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_hybrid(client, snapshot):
<0> response = await client.post(
<1> "/chat",
<2> json={
<3> "messages": [{"content": "What is the capital of France?", "role": "user"}],
<4> "context": {
<5> "overrides": {"retrieval_mode": "hybrid"},
<6> },
<7> },
<8> )
<9> assert response.status_code == 200
<10> result = await response.get_json()
<11> snapshot.assert_match(json.dumps(result, indent=4), "result.json")
<12>
|
===========unchanged ref 0===========
at: _pytest.mark.structures
MARK_GEN = MarkGenerator(_ispytest=True)
at: json
dumps(obj: Any, *, skipkeys: bool=..., ensure_ascii: bool=..., check_circular: bool=..., allow_nan: bool=..., cls: Optional[Type[JSONEncoder]]=..., indent: Union[None, int, str]=..., separators: Optional[Tuple[str, str]]=..., default: Optional[Callable[[Any], Any]]=..., sort_keys: bool=..., **kwds: Any) -> str
at: tests.test_app.test_chat_prompt_template_concat
result = await response.get_json()
===========changed ref 0===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_text(client, snapshot):
response = await client.post(
"/chat",
json={
"messages": [{"content": "What is the capital of France?", "role": "user"}],
"context": {
"overrides": {"retrieval_mode": "text"},
},
},
)
assert response.status_code == 200
result = await response.get_json()
+ assert result["context"]["thoughts"][1]["props"]["use_text_search"] is True
+ assert result["context"]["thoughts"][1]["props"]["use_vector_search"] is False
+ assert result["context"]["thoughts"][1]["props"]["use_semantic_ranker"] is False
snapshot.assert_match(json.dumps(result, indent=4), "result.json")
===========changed ref 1===========
<s>expected_result_count",
[
(0, 0, 1),
(0, 2, 1),
(0.03, 0, 1),
(0.03, 2, 1),
(1, 0, 0),
(0, 4, 0),
(1, 4, 0),
],
)
async def test_search_results_filtering_by_scores(
monkeypatch, minimum_search_score, minimum_reranker_score, expected_result_count
):
chat_approach = ChatReadRetrieveReadApproach(
search_client=SearchClient(endpoint="", index_name="", credential=AzureKeyCredential("")),
auth_helper=None,
openai_client=None,
chatgpt_model="gpt-35-turbo",
chatgpt_deployment="chat",
embedding_deployment="embeddings",
embedding_model=MOCK_EMBEDDING_MODEL_NAME,
embedding_dimensions=MOCK_EMBEDDING_DIMENSIONS,
sourcepage_field="",
content_field="",
query_language="en-us",
query_speller="lexicon",
)
monkeypatch.setattr(SearchClient, "search", mock_search)
filtered_results = await chat_approach.search(
top=10,
query_text="test query",
filter=None,
vectors=[],
+ use_text_search=True,
+ use_vector_search=True,
use_semantic_ranker=True,
use_semantic_captions=True,
minimum_search_score=minimum_search_score,
minimum_reranker_score=minimum_reranker_score,
)
assert (
len(filtered_results) == expected_result_count
), f"Expected {expected_result_count} results with minimum_search_score={minimum_search_score} and minimum_reranker_score={minimum_reranker_score}"
===========changed ref 2===========
<s>ach(ABC):
def search(
self,
top: int,
query_text: Optional[str],
filter: Optional[str],
vectors: List[VectorQuery],
+ use_text_search: bool,
+ use_vector_search: bool,
use_semantic_ranker: bool,
use_semantic_captions: bool,
minimum_search_score: Optional[float],
minimum_reranker_score: Optional[float],
) -> List[Document]:
+ search_text = query_text if use_text_search else ""
+ search_vectors = vectors if use_vector_search else []
- # Use semantic ranker if requested and if retrieval mode is text or hybrid (vectors + text)
+ if use_semantic_ranker:
- if use_semantic_ranker and query_text:
results = await self.search_client.search(
+ search_text=search_text,
- search_text=query_text,
filter=filter,
+ top=top,
+ query_caption="extractive|highlight-false" if use_semantic_captions else None,
+ vector_queries=search_vectors,
query_type=QueryType.SEMANTIC,
query_language=self.query_language,
query_speller=self.query_speller,
semantic_configuration_name="default",
- top=top,
- query_caption="extractive|highlight-false" if use_semantic_captions else None,
- vector_queries=vectors,
+ semantic_query=query_text,
)
else:
results = await self.search_client.search(
+ search_text=search_text,
+ filter=filter,
+ top=top,
+ vector_queries=search_vectors,
- search_text=query_text or "", filter=filter, top=top, vector_queries=vectors
)
documents = []
async for page in results.by_page():
async for document in page:
</s>
===========changed ref 3===========
<s> def search(
self,
top: int,
query_text: Optional[str],
filter: Optional[str],
vectors: List[VectorQuery],
+ use_text_search: bool,
+ use_vector_search: bool,
use_semantic_ranker: bool,
use_semantic_captions: bool,
minimum_search_score: Optional[float],
minimum_reranker_score: Optional[float],
) -> List[Document]:
# offset: 1
<s>
)
documents = []
async for page in results.by_page():
async for document in page:
documents.append(
Document(
id=document.get("id"),
content=document.get("content"),
embedding=document.get("embedding"),
image_embedding=document.get("imageEmbedding"),
category=document.get("category"),
sourcepage=document.get("sourcepage"),
sourcefile=document.get("sourcefile"),
oids=document.get("oids"),
groups=document.get("groups"),
captions=cast(List[QueryCaptionResult], document.get("@search.captions")),
score=document.get("@search.score"),
reranker_score=document.get("@search.reranker_score"),
)
)
qualified_documents = [
doc
for doc in documents
if (
(doc.score or 0) >= (minimum_search_score or 0)
and (doc.reranker_score or 0) >= (minimum_reranker_score or 0)
)
]
return qualified_documents
|
tests.test_app/test_chat_vector
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
43aa766e17cdb001168a04612518912486481a22
|
Allow semantic ranker with vector search (#1701)
|
<5>:<add> "overrides": {"retrieval_mode": "vectors"},
<del> "overrides": {"retrieval_mode": "vector"},
<11>:<add> assert result["context"]["thoughts"][1]["props"]["use_text_search"] is False
<add> assert result["context"]["thoughts"][1]["props"]["use_vector_search"] is True
<add> assert result["context"]["thoughts"][1]["props"]["use_semantic_ranker"] is False
|
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_vector(client, snapshot):
<0> response = await client.post(
<1> "/chat",
<2> json={
<3> "messages": [{"content": "What is the capital of France?", "role": "user"}],
<4> "context": {
<5> "overrides": {"retrieval_mode": "vector"},
<6> },
<7> },
<8> )
<9> assert response.status_code == 200
<10> result = await response.get_json()
<11> snapshot.assert_match(json.dumps(result, indent=4), "result.json")
<12>
|
===========unchanged ref 0===========
at: _pytest.mark.structures
MARK_GEN = MarkGenerator(_ispytest=True)
at: json
dumps(obj: Any, *, skipkeys: bool=..., ensure_ascii: bool=..., check_circular: bool=..., allow_nan: bool=..., cls: Optional[Type[JSONEncoder]]=..., indent: Union[None, int, str]=..., separators: Optional[Tuple[str, str]]=..., default: Optional[Callable[[Any], Any]]=..., sort_keys: bool=..., **kwds: Any) -> str
at: tests.test_app.test_chat_hybrid
result = await response.get_json()
===========changed ref 0===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_hybrid(client, snapshot):
response = await client.post(
"/chat",
json={
"messages": [{"content": "What is the capital of France?", "role": "user"}],
"context": {
"overrides": {"retrieval_mode": "hybrid"},
},
},
)
assert response.status_code == 200
result = await response.get_json()
+ assert result["context"]["thoughts"][1]["props"]["use_text_search"] is True
+ assert result["context"]["thoughts"][1]["props"]["use_vector_search"] is True
+ assert result["context"]["thoughts"][1]["props"]["use_semantic_ranker"] is False
+ assert result["context"]["thoughts"][1]["props"]["use_semantic_captions"] is False
snapshot.assert_match(json.dumps(result, indent=4), "result.json")
===========changed ref 1===========
# module: tests.test_app
@pytest.mark.asyncio
async def test_chat_text(client, snapshot):
response = await client.post(
"/chat",
json={
"messages": [{"content": "What is the capital of France?", "role": "user"}],
"context": {
"overrides": {"retrieval_mode": "text"},
},
},
)
assert response.status_code == 200
result = await response.get_json()
+ assert result["context"]["thoughts"][1]["props"]["use_text_search"] is True
+ assert result["context"]["thoughts"][1]["props"]["use_vector_search"] is False
+ assert result["context"]["thoughts"][1]["props"]["use_semantic_ranker"] is False
snapshot.assert_match(json.dumps(result, indent=4), "result.json")
===========changed ref 2===========
<s>expected_result_count",
[
(0, 0, 1),
(0, 2, 1),
(0.03, 0, 1),
(0.03, 2, 1),
(1, 0, 0),
(0, 4, 0),
(1, 4, 0),
],
)
async def test_search_results_filtering_by_scores(
monkeypatch, minimum_search_score, minimum_reranker_score, expected_result_count
):
chat_approach = ChatReadRetrieveReadApproach(
search_client=SearchClient(endpoint="", index_name="", credential=AzureKeyCredential("")),
auth_helper=None,
openai_client=None,
chatgpt_model="gpt-35-turbo",
chatgpt_deployment="chat",
embedding_deployment="embeddings",
embedding_model=MOCK_EMBEDDING_MODEL_NAME,
embedding_dimensions=MOCK_EMBEDDING_DIMENSIONS,
sourcepage_field="",
content_field="",
query_language="en-us",
query_speller="lexicon",
)
monkeypatch.setattr(SearchClient, "search", mock_search)
filtered_results = await chat_approach.search(
top=10,
query_text="test query",
filter=None,
vectors=[],
+ use_text_search=True,
+ use_vector_search=True,
use_semantic_ranker=True,
use_semantic_captions=True,
minimum_search_score=minimum_search_score,
minimum_reranker_score=minimum_reranker_score,
)
assert (
len(filtered_results) == expected_result_count
), f"Expected {expected_result_count} results with minimum_search_score={minimum_search_score} and minimum_reranker_score={minimum_reranker_score}"
===========changed ref 3===========
<s>ach(ABC):
def search(
self,
top: int,
query_text: Optional[str],
filter: Optional[str],
vectors: List[VectorQuery],
+ use_text_search: bool,
+ use_vector_search: bool,
use_semantic_ranker: bool,
use_semantic_captions: bool,
minimum_search_score: Optional[float],
minimum_reranker_score: Optional[float],
) -> List[Document]:
+ search_text = query_text if use_text_search else ""
+ search_vectors = vectors if use_vector_search else []
- # Use semantic ranker if requested and if retrieval mode is text or hybrid (vectors + text)
+ if use_semantic_ranker:
- if use_semantic_ranker and query_text:
results = await self.search_client.search(
+ search_text=search_text,
- search_text=query_text,
filter=filter,
+ top=top,
+ query_caption="extractive|highlight-false" if use_semantic_captions else None,
+ vector_queries=search_vectors,
query_type=QueryType.SEMANTIC,
query_language=self.query_language,
query_speller=self.query_speller,
semantic_configuration_name="default",
- top=top,
- query_caption="extractive|highlight-false" if use_semantic_captions else None,
- vector_queries=vectors,
+ semantic_query=query_text,
)
else:
results = await self.search_client.search(
+ search_text=search_text,
+ filter=filter,
+ top=top,
+ vector_queries=search_vectors,
- search_text=query_text or "", filter=filter, top=top, vector_queries=vectors
)
documents = []
async for page in results.by_page():
async for document in page:
</s>
|
app.backend.approaches.retrievethenread/RetrieveThenReadApproach.run
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
43aa766e17cdb001168a04612518912486481a22
|
Allow semantic ranker with vector search (#1701)
|
<5>:<add> use_text_search = overrides.get("retrieval_mode") in ["text", "hybrid", None]
<del> has_text = overrides.get("retrieval_mode") in ["text", "hybrid", None]
<6>:<add> use_vector_search = overrides.get("retrieval_mode") in ["vectors", "hybrid", None]
<del> has_vector = overrides.get("retrieval_mode") in ["vectors", "hybrid", None]
<7>:<add> use_semantic_ranker = True if overrides.get("semantic_ranker") else False
<del> use_semantic_ranker = overrides.get("semantic_ranker") and has_text
<8>:<del>
<9>:<add> use_semantic_captions = True if overrides.get("semantic_captions") else False
<del> use_semantic_captions = True if overrides.get("semantic_captions") and has_text else False
<14>:<add>
<16>:<add> if use_vector_search:
<del> if has_vector:
<18>:<del>
<19>:<del> # Only keep the text query if the retrieval mode uses text, otherwise drop it
<20>:<del> query_text = q if has_text else None
<24>:<add> q,
<del> query_text,
<27>:<add> use_text_search,
<add> use_vector_search,
|
# module: app.backend.approaches.retrievethenread
class RetrieveThenReadApproach(Approach):
def run(
self,
messages: list[ChatCompletionMessageParam],
session_state: Any = None,
context: dict[str, Any] = {},
) -> dict[str, Any]:
<0> q = messages[-1]["content"]
<1> if not isinstance(q, str):
<2> raise ValueError("The most recent message content must be a string.")
<3> overrides = context.get("overrides", {})
<4> auth_claims = context.get("auth_claims", {})
<5> has_text = overrides.get("retrieval_mode") in ["text", "hybrid", None]
<6> has_vector = overrides.get("retrieval_mode") in ["vectors", "hybrid", None]
<7> use_semantic_ranker = overrides.get("semantic_ranker") and has_text
<8>
<9> use_semantic_captions = True if overrides.get("semantic_captions") and has_text else False
<10> top = overrides.get("top", 3)
<11> minimum_search_score = overrides.get("minimum_search_score", 0.0)
<12> minimum_reranker_score = overrides.get("minimum_reranker_score", 0.0)
<13> filter = self.build_filter(overrides, auth_claims)
<14> # If retrieval mode includes vectors, compute an embedding for the query
<15> vectors: list[VectorQuery] = []
<16> if has_vector:
<17> vectors.append(await self.compute_text_embedding(q))
<18>
<19> # Only keep the text query if the retrieval mode uses text, otherwise drop it
<20> query_text = q if has_text else None
<21>
<22> results = await self.search(
<23> top,
<24> query_text,
<25> filter,
<26> vectors,
<27> use_semantic_ranker,
<28> use_semantic_captions,
<29> minimum_search_score,
<30> minimum_reranker_score,
<31> )
<32>
</s>
|
===========below chunk 0===========
# module: app.backend.approaches.retrievethenread
class RetrieveThenReadApproach(Approach):
def run(
self,
messages: list[ChatCompletionMessageParam],
session_state: Any = None,
context: dict[str, Any] = {},
) -> dict[str, Any]:
# offset: 1
sources_content = self.get_sources_content(results, use_semantic_captions, use_image_citation=False)
# Append user message
content = "\n".join(sources_content)
user_content = q + "\n" + f"Sources:\n {content}"
response_token_limit = 1024
updated_messages = build_messages(
model=self.chatgpt_model,
system_prompt=overrides.get("prompt_template", self.system_chat_template),
few_shots=[{"role": "user", "content": self.question}, {"role": "assistant", "content": self.answer}],
new_user_content=user_content,
max_tokens=self.chatgpt_token_limit - response_token_limit,
)
chat_completion = (
await self.openai_client.chat.completions.create(
# Azure OpenAI takes the deployment name as the model name
model=self.chatgpt_deployment if self.chatgpt_deployment else self.chatgpt_model,
messages=updated_messages,
temperature=overrides.get("temperature", 0.3),
max_tokens=response_token_limit,
n=1,
)
).model_dump()
data_points = {"text": sources_content}
extra_info = {
"data_points": data_points,
"thoughts": [
ThoughtStep(
"Search using user query",
query_text,
{
"use_semantic_captions": use_semantic_captions,
"use_semantic_ranker": use_semantic_ranker,
"top": top,
</s>
===========below chunk 1===========
# module: app.backend.approaches.retrievethenread
class RetrieveThenReadApproach(Approach):
def run(
self,
messages: list[ChatCompletionMessageParam],
session_state: Any = None,
context: dict[str, Any] = {},
) -> dict[str, Any]:
# offset: 2
<s>captions,
"use_semantic_ranker": use_semantic_ranker,
"top": top,
"filter": filter,
"has_vector": has_vector,
},
),
ThoughtStep(
"Search results",
[result.serialize_for_results() for result in results],
),
ThoughtStep(
"Prompt to generate answer",
[str(message) for message in updated_messages],
(
{"model": self.chatgpt_model, "deployment": self.chatgpt_deployment}
if self.chatgpt_deployment
else {"model": self.chatgpt_model}
),
),
],
}
completion = {}
completion["message"] = chat_completion["choices"][0]["message"]
completion["context"] = extra_info
completion["session_state"] = session_state
return completion
===========unchanged ref 0===========
at: app.backend.approaches.retrievethenread.RetrieveThenReadApproach
system_chat_template = (
"You are an intelligent assistant helping Contoso Inc employees with their healthcare plan questions and employee handbook questions. "
+ "Use 'you' to refer to the individual asking the questions even if they ask with 'I'. "
+ "Answer the following question using only the data provided in the sources below. "
+ "For tabular information return it as an html table. Do not return markdown format. "
+ "Each source has a name followed by colon and the actual information, always include the source name for each fact you use in the response. "
+ "If you cannot answer using the sources below, say you don't know. Use below example to answer"
)
question = """
'What is the deductible for the employee plan for a visit to Overlake in Bellevue?'
Sources:
info1.txt: deductibles depend on whether you are in-network or out-of-network. In-network deductibles are $500 for employee and $1000 for family. Out-of-network deductibles are $1000 for employee and $2000 for family.
info2.pdf: Overlake is in-network for the employee plan.
info3.pdf: Overlake is the name of the area that includes a park and ride near Bellevue.
info4.pdf: In-network institutions include Overlake, Swedish and others in the region
"""
answer = "In-network deductibles are $500 for employee and $1000 for family [info1.txt] and Overlake is in-network for the employee plan [info2.pdf][info4.pdf]."
at: app.backend.approaches.retrievethenread.RetrieveThenReadApproach.__init__
self.chatgpt_deployment = chatgpt_deployment
self.openai_client = openai_client
self.chatgpt_model = chatgpt_model
===========unchanged ref 1===========
self.chatgpt_token_limit = get_token_limit(chatgpt_model)
at: approaches.approach
ThoughtStep(title: str, description: Optional[Any], props: Optional[dict[str, Any]]=None)
at: approaches.approach.Approach
build_filter(overrides: dict[str, Any], auth_claims: dict[str, Any]) -> Optional[str]
search(top: int, query_text: Optional[str], filter: Optional[str], vectors: List[VectorQuery], use_text_search: bool, use_vector_search: bool, use_semantic_ranker: bool, use_semantic_captions: bool, minimum_search_score: Optional[float], minimum_reranker_score: Optional[float]) -> List[Document]
get_sources_content(results: List[Document], use_semantic_captions: bool, use_image_citation: bool) -> list[str]
compute_text_embedding(q: str)
run(self, messages: list[ChatCompletionMessageParam], session_state: Any=None, context: dict[str, Any]={}) -> dict[str, Any]
at: approaches.approach.Document
id: Optional[str]
content: Optional[str]
embedding: Optional[List[float]]
image_embedding: Optional[List[float]]
category: Optional[str]
sourcepage: Optional[str]
sourcefile: Optional[str]
oids: Optional[List[str]]
groups: Optional[List[str]]
captions: List[QueryCaptionResult]
score: Optional[float] = None
reranker_score: Optional[float] = None
serialize_for_results() -> dict[str, Any]
at: typing.Mapping
get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]
get(key: _KT) -> Optional[_VT_co]
|
tests.test_app_config/minimal_env
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
28536f612eeb486d6ff67a20aaf42395a2eb22f6
|
Support use of AzureOpenAI proxy by prepdocs (#1760)
|
<5>:<add> monkeypatch.setenv("AZURE_OPENAI_SERVICE", "test-openai-service")
|
# module: tests.test_app_config
@pytest.fixture
def minimal_env(monkeypatch):
<0> with mock.patch.dict(os.environ, clear=True):
<1> monkeypatch.setenv("AZURE_STORAGE_ACCOUNT", "test-storage-account")
<2> monkeypatch.setenv("AZURE_STORAGE_CONTAINER", "test-storage-container")
<3> monkeypatch.setenv("AZURE_SEARCH_INDEX", "test-search-index")
<4> monkeypatch.setenv("AZURE_SEARCH_SERVICE", "test-search-service")
<5> monkeypatch.setenv("AZURE_OPENAI_CHATGPT_MODEL", "gpt-35-turbo")
<6> yield
<7>
| |
app.backend.prepdocs/setup_embeddings_service
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
28536f612eeb486d6ff67a20aaf42395a2eb22f6
|
Support use of AzureOpenAI proxy by prepdocs (#1760)
|
<10>:<add> open_ai_custom_url=openai_custom_url,
|
<s>: AsyncTokenCredential,
openai_host: str,
openai_model_name: str,
openai_service: Union[str, None],
+ openai_custom_url: Union[str, None],
openai_deployment: Union[str, None],
openai_dimensions: int,
openai_key: Union[str, None],
openai_org: Union[str, None],
disable_vectors: bool = False,
disable_batch_vectors: bool = False,
):
<0> if disable_vectors:
<1> logger.info("Not setting up embeddings service")
<2> return None
<3>
<4> if openai_host != "openai":
<5> azure_open_ai_credential: Union[AsyncTokenCredential, AzureKeyCredential] = (
<6> azure_credential if openai_key is None else AzureKeyCredential(openai_key)
<7> )
<8> return AzureOpenAIEmbeddingService(
<9> open_ai_service=openai_service,
<10> open_ai_deployment=openai_deployment,
<11> open_ai_model_name=openai_model_name,
<12> open_ai_dimensions=openai_dimensions,
<13> credential=azure_open_ai_credential,
<14> disable_batch=disable_batch_vectors,
<15> )
<16> else:
<17> if openai_key is None:
<18> raise ValueError("OpenAI key is required when using the non-Azure OpenAI API")
<19> return OpenAIEmbeddingService(
<20> open_ai_model_name=openai_model_name,
<21> open_ai_dimensions=openai_dimensions,
<22> credential=openai_key,
<23> organization=openai_org,
<24> disable_batch=disable_batch_vectors,
<25> )
<26>
|
===========unchanged ref 0===========
at: app.backend.prepdocs
logger = logging.getLogger("ingester")
at: logging.Logger
info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
at: prepdocslib.embeddings
AzureOpenAIEmbeddingService(open_ai_service: Union[str, None], open_ai_deployment: Union[str, None], open_ai_model_name: str, open_ai_dimensions: int, credential: Union[AsyncTokenCredential, AzureKeyCredential], open_ai_custom_url: Union[str, None]=None, disable_batch: bool=False)
OpenAIEmbeddingService(open_ai_model_name: str, open_ai_dimensions: int, credential: str, organization: Optional[str]=None, disable_batch: bool=False)
===========changed ref 0===========
# module: tests.test_app_config
@pytest.fixture
def minimal_env(monkeypatch):
with mock.patch.dict(os.environ, clear=True):
monkeypatch.setenv("AZURE_STORAGE_ACCOUNT", "test-storage-account")
monkeypatch.setenv("AZURE_STORAGE_CONTAINER", "test-storage-container")
monkeypatch.setenv("AZURE_SEARCH_INDEX", "test-search-index")
monkeypatch.setenv("AZURE_SEARCH_SERVICE", "test-search-service")
+ monkeypatch.setenv("AZURE_OPENAI_SERVICE", "test-openai-service")
monkeypatch.setenv("AZURE_OPENAI_CHATGPT_MODEL", "gpt-35-turbo")
yield
|
app.backend.prepdocslib.embeddings/AzureOpenAIEmbeddingService.__init__
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
28536f612eeb486d6ff67a20aaf42395a2eb22f6
|
Support use of AzureOpenAI proxy by prepdocs (#1760)
|
<2>:<add> if open_ai_service:
<add> self.open_ai_endpoint = f"https://{open_ai_service}.openai.azure.com"
<add> elif open_ai_custom_url:
<add> self.open_ai_endpoint = open_ai_custom_url
<add> else:
<add> raise ValueError("Either open_ai_service or open_ai_custom_url must be provided")
|
<s>.embeddings
class AzureOpenAIEmbeddingService(OpenAIEmbeddings):
def __init__(
self,
open_ai_service: Union[str, None],
open_ai_deployment: Union[str, None],
open_ai_model_name: str,
open_ai_dimensions: int,
credential: Union[AsyncTokenCredential, AzureKeyCredential],
+ open_ai_custom_url: Union[str, None] = None,
disable_batch: bool = False,
):
<0> super().__init__(open_ai_model_name, open_ai_dimensions, disable_batch)
<1> self.open_ai_service = open_ai_service
<2> self.open_ai_deployment = open_ai_deployment
<3> self.credential = credential
<4>
|
===========unchanged ref 0===========
at: app.backend.prepdocslib.embeddings.OpenAIEmbeddings
SUPPORTED_BATCH_AOAI_MODEL = {
"text-embedding-ada-002": {"token_limit": 8100, "max_batch_size": 16},
"text-embedding-3-small": {"token_limit": 8100, "max_batch_size": 16},
"text-embedding-3-large": {"token_limit": 8100, "max_batch_size": 16},
}
SUPPORTED_DIMENSIONS_MODEL = {
"text-embedding-ada-002": False,
"text-embedding-3-small": True,
"text-embedding-3-large": True,
}
__init__(self, open_ai_model_name: str, open_ai_dimensions: int, disable_batch: bool=False)
__init__(open_ai_model_name: str, open_ai_dimensions: int, disable_batch: bool=False)
===========changed ref 0===========
# module: tests.test_app_config
@pytest.fixture
def minimal_env(monkeypatch):
with mock.patch.dict(os.environ, clear=True):
monkeypatch.setenv("AZURE_STORAGE_ACCOUNT", "test-storage-account")
monkeypatch.setenv("AZURE_STORAGE_CONTAINER", "test-storage-container")
monkeypatch.setenv("AZURE_SEARCH_INDEX", "test-search-index")
monkeypatch.setenv("AZURE_SEARCH_SERVICE", "test-search-service")
+ monkeypatch.setenv("AZURE_OPENAI_SERVICE", "test-openai-service")
monkeypatch.setenv("AZURE_OPENAI_CHATGPT_MODEL", "gpt-35-turbo")
yield
===========changed ref 1===========
<s>: AsyncTokenCredential,
openai_host: str,
openai_model_name: str,
openai_service: Union[str, None],
+ openai_custom_url: Union[str, None],
openai_deployment: Union[str, None],
openai_dimensions: int,
openai_key: Union[str, None],
openai_org: Union[str, None],
disable_vectors: bool = False,
disable_batch_vectors: bool = False,
):
if disable_vectors:
logger.info("Not setting up embeddings service")
return None
if openai_host != "openai":
azure_open_ai_credential: Union[AsyncTokenCredential, AzureKeyCredential] = (
azure_credential if openai_key is None else AzureKeyCredential(openai_key)
)
return AzureOpenAIEmbeddingService(
open_ai_service=openai_service,
+ open_ai_custom_url=openai_custom_url,
open_ai_deployment=openai_deployment,
open_ai_model_name=openai_model_name,
open_ai_dimensions=openai_dimensions,
credential=azure_open_ai_credential,
disable_batch=disable_batch_vectors,
)
else:
if openai_key is None:
raise ValueError("OpenAI key is required when using the non-Azure OpenAI API")
return OpenAIEmbeddingService(
open_ai_model_name=openai_model_name,
open_ai_dimensions=openai_dimensions,
credential=openai_key,
organization=openai_org,
disable_batch=disable_batch_vectors,
)
===========changed ref 2===========
# module: app.backend.prepdocs
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Prepare documents by extracting content from PDFs, splitting content into sections, uploading to blob storage, and indexing in a search index.",
epilog="Example: prepdocs.py '.\\data\*' --storageaccount myaccount --container mycontainer --searchservice mysearch --index myindex -v",
)
parser.add_argument("files", nargs="?", help="Files to be processed")
parser.add_argument(
"--datalakestorageaccount", required=False, help="Optional. Azure Data Lake Storage Gen2 Account name"
)
parser.add_argument(
"--datalakefilesystem",
required=False,
default="gptkbcontainer",
help="Optional. Azure Data Lake Storage Gen2 filesystem name",
)
parser.add_argument(
"--datalakepath",
required=False,
help="Optional. Azure Data Lake Storage Gen2 filesystem path containing files to index. If omitted, index the entire filesystem",
)
parser.add_argument(
"--datalakekey", required=False, help="Optional. Use this key when authenticating to Azure Data Lake Gen2"
)
parser.add_argument(
"--useacls", action="store_true", help="Store ACLs from Azure Data Lake Gen2 Filesystem in the search index"
)
parser.add_argument(
"--category", help="Value for the category field in the search index for all sections indexed in this run"
)
parser.add_argument(
"--skipblobs", action="store_true", help="Skip uploading individual pages to Azure Blob Storage"
)
parser.add_argument("--storageaccount", help="Azure Blob Storage account name")
parser.add_argument("--container", help="Azure Blob Storage container name")
parser.add_argument("--storageresourcegroup", help="Azure blob storage resource group")
parser.add_argument(
"--storagekey",
required=False,
help="Optional. Use this Azure Blob</s>
===========changed ref 3===========
# module: app.backend.prepdocs
# offset: 1
<s>
parser.add_argument(
"--storagekey",
required=False,
help="Optional. Use this Azure Blob Storage account key instead of the current user identity to login (use az login to set current user for Azure)",
)
parser.add_argument(
"--tenantid", required=False, help="Optional. Use this to define the Azure directory where to authenticate)"
)
parser.add_argument(
"--subscriptionid",
required=False,
help="Optional. Use this to define managed identity connection string in integrated vectorization",
)
parser.add_argument(
"--searchservice",
help="Name of the Azure AI Search service where content should be indexed (must exist already)",
)
parser.add_argument(
"--searchserviceassignedid",
required=False,
help="Search service system assigned Identity (Managed identity) (used for integrated vectorization)",
)
parser.add_argument(
"--index",
help="Name of the Azure AI Search index where content should be indexed (will be created if it doesn't exist)",
)
parser.add_argument(
"--searchkey",
required=False,
help="Optional. Use this Azure AI Search account key instead of the current user identity to login (use az login to set current user for Azure)",
)
parser.add_argument(
"--searchanalyzername",
required=False,
default="en.microsoft",
help="Optional. Name of the Azure AI Search analyzer to use for the content field in the index",
)
parser.add_argument("--openaihost", help="Host of the API used to compute embeddings ('azure' or 'openai')")
parser.add_argument("--openaiservice", help="Name of the Azure OpenAI service used to compute embeddings")
parser.add_argument(
"--openaideployment",
help="Name of the Azure</s>
|
app.backend.prepdocslib.embeddings/AzureOpenAIEmbeddingService.create_client
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
28536f612eeb486d6ff67a20aaf42395a2eb22f6
|
Support use of AzureOpenAI proxy by prepdocs (#1760)
|
<15>:<add> azure_endpoint=self.open_ai_endpoint,
<del> azure_endpoint=f"https://{self.open_ai_service}.openai.azure.com",
|
# module: app.backend.prepdocslib.embeddings
class AzureOpenAIEmbeddingService(OpenAIEmbeddings):
def create_client(self) -> AsyncOpenAI:
<0> class AuthArgs(TypedDict, total=False):
<1> api_key: str
<2> azure_ad_token_provider: Callable[[], Union[str, Awaitable[str]]]
<3>
<4> auth_args = AuthArgs()
<5> if isinstance(self.credential, AzureKeyCredential):
<6> auth_args["api_key"] = self.credential.key
<7> elif isinstance(self.credential, AsyncTokenCredential):
<8> auth_args["azure_ad_token_provider"] = get_bearer_token_provider(
<9> self.credential, "https://cognitiveservices.azure.com/.default"
<10> )
<11> else:
<12> raise TypeError("Invalid credential type")
<13>
<14> return AsyncAzureOpenAI(
<15> azure_endpoint=f"https://{self.open_ai_service}.openai.azure.com",
<16> azure_deployment=self.open_ai_deployment,
<17> api_version="2023-05-15",
<18> **auth_args,
<19> )
<20>
|
===========unchanged ref 0===========
at: app.backend.prepdocslib.embeddings.OpenAIEmbeddings
create_client(self) -> AsyncOpenAI
at: typing
Awaitable = _alias(collections.abc.Awaitable, 1)
Callable = _CallableType(collections.abc.Callable, 2)
===========changed ref 0===========
<s>.embeddings
class AzureOpenAIEmbeddingService(OpenAIEmbeddings):
def __init__(
self,
open_ai_service: Union[str, None],
open_ai_deployment: Union[str, None],
open_ai_model_name: str,
open_ai_dimensions: int,
credential: Union[AsyncTokenCredential, AzureKeyCredential],
+ open_ai_custom_url: Union[str, None] = None,
disable_batch: bool = False,
):
super().__init__(open_ai_model_name, open_ai_dimensions, disable_batch)
self.open_ai_service = open_ai_service
+ if open_ai_service:
+ self.open_ai_endpoint = f"https://{open_ai_service}.openai.azure.com"
+ elif open_ai_custom_url:
+ self.open_ai_endpoint = open_ai_custom_url
+ else:
+ raise ValueError("Either open_ai_service or open_ai_custom_url must be provided")
self.open_ai_deployment = open_ai_deployment
self.credential = credential
===========changed ref 1===========
# module: tests.test_app_config
@pytest.fixture
def minimal_env(monkeypatch):
with mock.patch.dict(os.environ, clear=True):
monkeypatch.setenv("AZURE_STORAGE_ACCOUNT", "test-storage-account")
monkeypatch.setenv("AZURE_STORAGE_CONTAINER", "test-storage-container")
monkeypatch.setenv("AZURE_SEARCH_INDEX", "test-search-index")
monkeypatch.setenv("AZURE_SEARCH_SERVICE", "test-search-service")
+ monkeypatch.setenv("AZURE_OPENAI_SERVICE", "test-openai-service")
monkeypatch.setenv("AZURE_OPENAI_CHATGPT_MODEL", "gpt-35-turbo")
yield
===========changed ref 2===========
<s>: AsyncTokenCredential,
openai_host: str,
openai_model_name: str,
openai_service: Union[str, None],
+ openai_custom_url: Union[str, None],
openai_deployment: Union[str, None],
openai_dimensions: int,
openai_key: Union[str, None],
openai_org: Union[str, None],
disable_vectors: bool = False,
disable_batch_vectors: bool = False,
):
if disable_vectors:
logger.info("Not setting up embeddings service")
return None
if openai_host != "openai":
azure_open_ai_credential: Union[AsyncTokenCredential, AzureKeyCredential] = (
azure_credential if openai_key is None else AzureKeyCredential(openai_key)
)
return AzureOpenAIEmbeddingService(
open_ai_service=openai_service,
+ open_ai_custom_url=openai_custom_url,
open_ai_deployment=openai_deployment,
open_ai_model_name=openai_model_name,
open_ai_dimensions=openai_dimensions,
credential=azure_open_ai_credential,
disable_batch=disable_batch_vectors,
)
else:
if openai_key is None:
raise ValueError("OpenAI key is required when using the non-Azure OpenAI API")
return OpenAIEmbeddingService(
open_ai_model_name=openai_model_name,
open_ai_dimensions=openai_dimensions,
credential=openai_key,
organization=openai_org,
disable_batch=disable_batch_vectors,
)
===========changed ref 3===========
# module: app.backend.prepdocs
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Prepare documents by extracting content from PDFs, splitting content into sections, uploading to blob storage, and indexing in a search index.",
epilog="Example: prepdocs.py '.\\data\*' --storageaccount myaccount --container mycontainer --searchservice mysearch --index myindex -v",
)
parser.add_argument("files", nargs="?", help="Files to be processed")
parser.add_argument(
"--datalakestorageaccount", required=False, help="Optional. Azure Data Lake Storage Gen2 Account name"
)
parser.add_argument(
"--datalakefilesystem",
required=False,
default="gptkbcontainer",
help="Optional. Azure Data Lake Storage Gen2 filesystem name",
)
parser.add_argument(
"--datalakepath",
required=False,
help="Optional. Azure Data Lake Storage Gen2 filesystem path containing files to index. If omitted, index the entire filesystem",
)
parser.add_argument(
"--datalakekey", required=False, help="Optional. Use this key when authenticating to Azure Data Lake Gen2"
)
parser.add_argument(
"--useacls", action="store_true", help="Store ACLs from Azure Data Lake Gen2 Filesystem in the search index"
)
parser.add_argument(
"--category", help="Value for the category field in the search index for all sections indexed in this run"
)
parser.add_argument(
"--skipblobs", action="store_true", help="Skip uploading individual pages to Azure Blob Storage"
)
parser.add_argument("--storageaccount", help="Azure Blob Storage account name")
parser.add_argument("--container", help="Azure Blob Storage container name")
parser.add_argument("--storageresourcegroup", help="Azure blob storage resource group")
parser.add_argument(
"--storagekey",
required=False,
help="Optional. Use this Azure Blob</s>
===========changed ref 4===========
# module: app.backend.prepdocs
# offset: 1
<s>
parser.add_argument(
"--storagekey",
required=False,
help="Optional. Use this Azure Blob Storage account key instead of the current user identity to login (use az login to set current user for Azure)",
)
parser.add_argument(
"--tenantid", required=False, help="Optional. Use this to define the Azure directory where to authenticate)"
)
parser.add_argument(
"--subscriptionid",
required=False,
help="Optional. Use this to define managed identity connection string in integrated vectorization",
)
parser.add_argument(
"--searchservice",
help="Name of the Azure AI Search service where content should be indexed (must exist already)",
)
parser.add_argument(
"--searchserviceassignedid",
required=False,
help="Search service system assigned Identity (Managed identity) (used for integrated vectorization)",
)
parser.add_argument(
"--index",
help="Name of the Azure AI Search index where content should be indexed (will be created if it doesn't exist)",
)
parser.add_argument(
"--searchkey",
required=False,
help="Optional. Use this Azure AI Search account key instead of the current user identity to login (use az login to set current user for Azure)",
)
parser.add_argument(
"--searchanalyzername",
required=False,
default="en.microsoft",
help="Optional. Name of the Azure AI Search analyzer to use for the content field in the index",
)
parser.add_argument("--openaihost", help="Host of the API used to compute embeddings ('azure' or 'openai')")
parser.add_argument("--openaiservice", help="Name of the Azure OpenAI service used to compute embeddings")
parser.add_argument(
"--openaideployment",
help="Name of the Azure</s>
|
tests.e2e/run_server
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
28536f612eeb486d6ff67a20aaf42395a2eb22f6
|
Support use of AzureOpenAI proxy by prepdocs (#1760)
|
<13>:<add> "AZURE_OPENAI_SERVICE": "test-openai-service",
|
# module: tests.e2e
def run_server(port: int):
<0> with mock.patch.dict(
<1> os.environ,
<2> {
<3> "AZURE_STORAGE_ACCOUNT": "test-storage-account",
<4> "AZURE_STORAGE_CONTAINER": "test-storage-container",
<5> "AZURE_STORAGE_RESOURCE_GROUP": "test-storage-rg",
<6> "AZURE_SUBSCRIPTION_ID": "test-storage-subid",
<7> "USE_SPEECH_INPUT_BROWSER": "false",
<8> "USE_SPEECH_OUTPUT_AZURE": "false",
<9> "AZURE_SEARCH_INDEX": "test-search-index",
<10> "AZURE_SEARCH_SERVICE": "test-search-service",
<11> "AZURE_SPEECH_SERVICE_ID": "test-id",
<12> "AZURE_SPEECH_SERVICE_LOCATION": "eastus",
<13> "AZURE_OPENAI_CHATGPT_MODEL": "gpt-35-turbo",
<14> },
<15> clear=True,
<16> ):
<17> uvicorn.run(app.create_app(), port=port)
<18>
|
===========changed ref 0===========
<s>.embeddings
class AzureOpenAIEmbeddingService(OpenAIEmbeddings):
def __init__(
self,
open_ai_service: Union[str, None],
open_ai_deployment: Union[str, None],
open_ai_model_name: str,
open_ai_dimensions: int,
credential: Union[AsyncTokenCredential, AzureKeyCredential],
+ open_ai_custom_url: Union[str, None] = None,
disable_batch: bool = False,
):
super().__init__(open_ai_model_name, open_ai_dimensions, disable_batch)
self.open_ai_service = open_ai_service
+ if open_ai_service:
+ self.open_ai_endpoint = f"https://{open_ai_service}.openai.azure.com"
+ elif open_ai_custom_url:
+ self.open_ai_endpoint = open_ai_custom_url
+ else:
+ raise ValueError("Either open_ai_service or open_ai_custom_url must be provided")
self.open_ai_deployment = open_ai_deployment
self.credential = credential
===========changed ref 1===========
# module: tests.test_app_config
@pytest.fixture
def minimal_env(monkeypatch):
with mock.patch.dict(os.environ, clear=True):
monkeypatch.setenv("AZURE_STORAGE_ACCOUNT", "test-storage-account")
monkeypatch.setenv("AZURE_STORAGE_CONTAINER", "test-storage-container")
monkeypatch.setenv("AZURE_SEARCH_INDEX", "test-search-index")
monkeypatch.setenv("AZURE_SEARCH_SERVICE", "test-search-service")
+ monkeypatch.setenv("AZURE_OPENAI_SERVICE", "test-openai-service")
monkeypatch.setenv("AZURE_OPENAI_CHATGPT_MODEL", "gpt-35-turbo")
yield
===========changed ref 2===========
# module: app.backend.prepdocslib.embeddings
class AzureOpenAIEmbeddingService(OpenAIEmbeddings):
def create_client(self) -> AsyncOpenAI:
class AuthArgs(TypedDict, total=False):
api_key: str
azure_ad_token_provider: Callable[[], Union[str, Awaitable[str]]]
auth_args = AuthArgs()
if isinstance(self.credential, AzureKeyCredential):
auth_args["api_key"] = self.credential.key
elif isinstance(self.credential, AsyncTokenCredential):
auth_args["azure_ad_token_provider"] = get_bearer_token_provider(
self.credential, "https://cognitiveservices.azure.com/.default"
)
else:
raise TypeError("Invalid credential type")
return AsyncAzureOpenAI(
+ azure_endpoint=self.open_ai_endpoint,
- azure_endpoint=f"https://{self.open_ai_service}.openai.azure.com",
azure_deployment=self.open_ai_deployment,
api_version="2023-05-15",
**auth_args,
)
===========changed ref 3===========
<s>: AsyncTokenCredential,
openai_host: str,
openai_model_name: str,
openai_service: Union[str, None],
+ openai_custom_url: Union[str, None],
openai_deployment: Union[str, None],
openai_dimensions: int,
openai_key: Union[str, None],
openai_org: Union[str, None],
disable_vectors: bool = False,
disable_batch_vectors: bool = False,
):
if disable_vectors:
logger.info("Not setting up embeddings service")
return None
if openai_host != "openai":
azure_open_ai_credential: Union[AsyncTokenCredential, AzureKeyCredential] = (
azure_credential if openai_key is None else AzureKeyCredential(openai_key)
)
return AzureOpenAIEmbeddingService(
open_ai_service=openai_service,
+ open_ai_custom_url=openai_custom_url,
open_ai_deployment=openai_deployment,
open_ai_model_name=openai_model_name,
open_ai_dimensions=openai_dimensions,
credential=azure_open_ai_credential,
disable_batch=disable_batch_vectors,
)
else:
if openai_key is None:
raise ValueError("OpenAI key is required when using the non-Azure OpenAI API")
return OpenAIEmbeddingService(
open_ai_model_name=openai_model_name,
open_ai_dimensions=openai_dimensions,
credential=openai_key,
organization=openai_org,
disable_batch=disable_batch_vectors,
)
===========changed ref 4===========
# module: app.backend.prepdocs
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Prepare documents by extracting content from PDFs, splitting content into sections, uploading to blob storage, and indexing in a search index.",
epilog="Example: prepdocs.py '.\\data\*' --storageaccount myaccount --container mycontainer --searchservice mysearch --index myindex -v",
)
parser.add_argument("files", nargs="?", help="Files to be processed")
parser.add_argument(
"--datalakestorageaccount", required=False, help="Optional. Azure Data Lake Storage Gen2 Account name"
)
parser.add_argument(
"--datalakefilesystem",
required=False,
default="gptkbcontainer",
help="Optional. Azure Data Lake Storage Gen2 filesystem name",
)
parser.add_argument(
"--datalakepath",
required=False,
help="Optional. Azure Data Lake Storage Gen2 filesystem path containing files to index. If omitted, index the entire filesystem",
)
parser.add_argument(
"--datalakekey", required=False, help="Optional. Use this key when authenticating to Azure Data Lake Gen2"
)
parser.add_argument(
"--useacls", action="store_true", help="Store ACLs from Azure Data Lake Gen2 Filesystem in the search index"
)
parser.add_argument(
"--category", help="Value for the category field in the search index for all sections indexed in this run"
)
parser.add_argument(
"--skipblobs", action="store_true", help="Skip uploading individual pages to Azure Blob Storage"
)
parser.add_argument("--storageaccount", help="Azure Blob Storage account name")
parser.add_argument("--container", help="Azure Blob Storage container name")
parser.add_argument("--storageresourcegroup", help="Azure blob storage resource group")
parser.add_argument(
"--storagekey",
required=False,
help="Optional. Use this Azure Blob</s>
|
tests.e2e/test_home
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
1603e94b021ea64f15ce7cb87ce1de42904d556d
|
CSS changes for responsive design (#1646)
|
<1>:<add> expect(page).to_have_title("Azure OpenAI + AI Search")
<del> expect(page).to_have_title("GPT + Enterprise data | Sample")
|
# module: tests.e2e
def test_home(page: Page, live_server_url: str):
<0> page.goto(live_server_url)
<1> expect(page).to_have_title("GPT + Enterprise data | Sample")
<2>
|
===========unchanged ref 0===========
at: _pytest.fixtures
fixture(fixture_function: FixtureFunction, *, scope: "Union[_ScopeName, Callable[[str, Config], _ScopeName]]"=..., params: Optional[Iterable[object]]=..., autouse: bool=..., ids: Optional[
Union[Sequence[Optional[object]], Callable[[Any], Optional[object]]]
]=..., name: Optional[str]=...) -> FixtureFunction
fixture(fixture_function: None=..., *, scope: "Union[_ScopeName, Callable[[str, Config], _ScopeName]]"=..., params: Optional[Iterable[object]]=..., autouse: bool=..., ids: Optional[
Union[Sequence[Optional[object]], Callable[[Any], Optional[object]]]
]=..., name: Optional[str]=None) -> FixtureFunctionMarker
|
tests.e2e/test_chat
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
1603e94b021ea64f15ce7cb87ce1de42904d556d
|
CSS changes for responsive design (#1646)
|
<0>:<add> page = sized_page
<add>
<15>:<add> expect(page).to_have_title("Azure OpenAI + AI Search")
<del> expect(page).to_have_title("GPT + Enterprise data | Sample")
|
# module: tests.e2e
+ def test_chat(sized_page: Page, live_server_url: str):
- def test_chat(page: Page, live_server_url: str):
<0> # Set up a mock route to the /chat endpoint with streaming results
<1> def handle(route: Route):
<2> # Assert that session_state is specified in the request (None for now)
<3> session_state = route.request.post_data_json["session_state"]
<4> assert session_state is None
<5> # Read the JSONL from our snapshot results and return as the response
<6> f = open("tests/snapshots/test_app/test_chat_stream_text/client0/result.jsonlines")
<7> jsonl = f.read()
<8> f.close()
<9> route.fulfill(body=jsonl, status=200, headers={"Transfer-encoding": "Chunked"})
<10>
<11> page.route("*/**/chat/stream", handle)
<12>
<13> # Check initial page state
<14> page.goto(live_server_url)
<15> expect(page).to_have_title("GPT + Enterprise data | Sample")
<16> expect(page.get_by_role("heading", name="Chat with your data")).to_be_visible()
<17> expect(page.get_by_role("button", name="Clear chat")).to_be_disabled()
<18> expect(page.get_by_role("button", name="Developer settings")).to_be_enabled()
<19>
<20> # Ask a question and wait for the message to appear
<21> page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").click()
<22> page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").fill(
<23> "Whats the dental plan?"
<24> )
<25> page.get_by_role("button", name="Submit question").click()
<26>
<27> expect(page.get_by_text("Whats the dental plan?")).to</s>
|
===========below chunk 0===========
# module: tests.e2e
+ def test_chat(sized_page: Page, live_server_url: str):
- def test_chat(page: Page, live_server_url: str):
# offset: 1
expect(page.get_by_text("The capital of France is Paris.")).to_be_visible()
expect(page.get_by_role("button", name="Clear chat")).to_be_enabled()
# Show the citation document
page.get_by_text("1. Benefit_Options-2.pdf").click()
expect(page.get_by_role("tab", name="Citation")).to_be_visible()
expect(page.get_by_title("Citation")).to_be_visible()
# Show the thought process
page.get_by_label("Show thought process").click()
expect(page.get_by_title("Thought process")).to_be_visible()
expect(page.get_by_text("Generated search query")).to_be_visible()
# Show the supporting content
page.get_by_label("Show supporting content").click()
expect(page.get_by_title("Supporting content")).to_be_visible()
expect(page.get_by_role("heading", name="Benefit_Options-2.pdf")).to_be_visible()
# Clear the chat
page.get_by_role("button", name="Clear chat").click()
expect(page.get_by_text("Whats the dental plan?")).not_to_be_visible()
expect(page.get_by_text("The capital of France is Paris.")).not_to_be_visible()
expect(page.get_by_role("button", name="Clear chat")).to_be_disabled()
===========unchanged ref 0===========
at: io.BufferedReader
close(self) -> None
at: io.FileIO
read(self, size: int=..., /) -> bytes
at: typing.IO
__slots__ = ()
close() -> None
read(n: int=...) -> AnyStr
===========changed ref 0===========
# module: tests.e2e
+ @pytest.fixture(params=[(480, 800), (600, 1024), (768, 1024), (992, 1024), (1024, 768)])
+ def sized_page(page: Page, request):
+ size = request.param
+ page.set_viewport_size({"width": size[0], "height": size[1]})
+ yield page
+
===========changed ref 1===========
# module: tests.e2e
def test_home(page: Page, live_server_url: str):
page.goto(live_server_url)
+ expect(page).to_have_title("Azure OpenAI + AI Search")
- expect(page).to_have_title("GPT + Enterprise data | Sample")
|
tests.e2e/test_chat_customization
|
Modified
|
Azure-Samples~azure-search-openai-demo
|
1603e94b021ea64f15ce7cb87ce1de42904d556d
|
CSS changes for responsive design (#1646)
|
<22>:<add> expect(page).to_have_title("Azure OpenAI + AI Search")
<del> expect(page).to_have_title("GPT + Enterprise data | Sample")
|
# module: tests.e2e
def test_chat_customization(page: Page, live_server_url: str):
<0> # Set up a mock route to the /chat endpoint
<1> def handle(route: Route):
<2> overrides = route.request.post_data_json["context"]["overrides"]
<3> assert overrides["retrieval_mode"] == "vectors"
<4> assert overrides["semantic_ranker"] is False
<5> assert overrides["semantic_captions"] is True
<6> assert overrides["top"] == 1
<7> assert overrides["prompt_template"] == "You are a cat and only talk about tuna."
<8> assert overrides["exclude_category"] == "dogs"
<9> assert overrides["use_oid_security_filter"] is False
<10> assert overrides["use_groups_security_filter"] is False
<11>
<12> # Read the JSON from our snapshot results and return as the response
<13> f = open("tests/snapshots/test_app/test_chat_text/client0/result.json")
<14> json = f.read()
<15> f.close()
<16> route.fulfill(body=json, status=200)
<17>
<18> page.route("*/**/chat", handle)
<19>
<20> # Check initial page state
<21> page.goto(live_server_url)
<22> expect(page).to_have_title("GPT + Enterprise data | Sample")
<23>
<24> # Customize all the settings
<25> page.get_by_role("button", name="Developer settings").click()
<26> page.get_by_label("Override prompt template").click()
<27> page.get_by_label("Override prompt template").fill("You are a cat and only talk about tuna.")
<28> page.get_by_label("Retrieve this many search results:").click()
<29> page.get_by_label("Retrieve this many search results:").fill("1")
<30> page.get_by_label("Exclude category").click()
<31> page.get_by_label("Exclude category").fill("dogs")
<32> page.get_by_text("Use semantic captions").click()
<33> </s>
|
===========below chunk 0===========
# module: tests.e2e
def test_chat_customization(page: Page, live_server_url: str):
# offset: 1
page.get_by_text("Vectors + Text (Hybrid)").click()
page.get_by_role("option", name="Vectors", exact=True).click()
page.get_by_text("Stream chat completion responses").click()
page.locator("button").filter(has_text="Close").click()
# Ask a question and wait for the message to appear
page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").click()
page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").fill(
"Whats the dental plan?"
)
page.get_by_role("button", name="Submit question").click()
expect(page.get_by_text("Whats the dental plan?")).to_be_visible()
expect(page.get_by_text("The capital of France is Paris.")).to_be_visible()
expect(page.get_by_role("button", name="Clear chat")).to_be_enabled()
===========unchanged ref 0===========
at: io.BufferedWriter
read(self, size: Optional[int]=..., /) -> bytes
at: io.FileIO
close(self) -> None
at: tests.e2e.test_chat
page = sized_page
at: typing.IO
close() -> None
read(n: int=...) -> AnyStr
===========changed ref 0===========
# module: tests.e2e
+ @pytest.fixture(params=[(480, 800), (600, 1024), (768, 1024), (992, 1024), (1024, 768)])
+ def sized_page(page: Page, request):
+ size = request.param
+ page.set_viewport_size({"width": size[0], "height": size[1]})
+ yield page
+
===========changed ref 1===========
# module: tests.e2e
def test_home(page: Page, live_server_url: str):
page.goto(live_server_url)
+ expect(page).to_have_title("Azure OpenAI + AI Search")
- expect(page).to_have_title("GPT + Enterprise data | Sample")
===========changed ref 2===========
# module: tests.e2e
+ def test_chat(sized_page: Page, live_server_url: str):
- def test_chat(page: Page, live_server_url: str):
+ page = sized_page
+
# Set up a mock route to the /chat endpoint with streaming results
def handle(route: Route):
# Assert that session_state is specified in the request (None for now)
session_state = route.request.post_data_json["session_state"]
assert session_state is None
# Read the JSONL from our snapshot results and return as the response
f = open("tests/snapshots/test_app/test_chat_stream_text/client0/result.jsonlines")
jsonl = f.read()
f.close()
route.fulfill(body=jsonl, status=200, headers={"Transfer-encoding": "Chunked"})
page.route("*/**/chat/stream", handle)
# Check initial page state
page.goto(live_server_url)
+ expect(page).to_have_title("Azure OpenAI + AI Search")
- expect(page).to_have_title("GPT + Enterprise data | Sample")
expect(page.get_by_role("heading", name="Chat with your data")).to_be_visible()
expect(page.get_by_role("button", name="Clear chat")).to_be_disabled()
expect(page.get_by_role("button", name="Developer settings")).to_be_enabled()
# Ask a question and wait for the message to appear
page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").click()
page.get_by_placeholder("Type a new question (e.g. does my plan cover annual eye exams?)").fill(
"Whats the dental plan?"
)
page.get_by_role("button", name="Submit question").click()
expect(page.get_by_text("Whats the dental</s>
===========changed ref 3===========
# module: tests.e2e
+ def test_chat(sized_page: Page, live_server_url: str):
- def test_chat(page: Page, live_server_url: str):
# offset: 1
<s>role("button", name="Submit question").click()
expect(page.get_by_text("Whats the dental plan?")).to_be_visible()
expect(page.get_by_text("The capital of France is Paris.")).to_be_visible()
expect(page.get_by_role("button", name="Clear chat")).to_be_enabled()
# Show the citation document
page.get_by_text("1. Benefit_Options-2.pdf").click()
expect(page.get_by_role("tab", name="Citation")).to_be_visible()
expect(page.get_by_title("Citation")).to_be_visible()
# Show the thought process
page.get_by_label("Show thought process").click()
expect(page.get_by_title("Thought process")).to_be_visible()
expect(page.get_by_text("Generated search query")).to_be_visible()
# Show the supporting content
page.get_by_label("Show supporting content").click()
expect(page.get_by_title("Supporting content")).to_be_visible()
expect(page.get_by_role("heading", name="Benefit_Options-2.pdf")).to_be_visible()
# Clear the chat
page.get_by_role("button", name="Clear chat").click()
expect(page.get_by_text("Whats the dental plan?")).not_to_be_visible()
expect(page.get_by_text("The capital of France is Paris.")).not_to_be_visible()
expect(page.get
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.