diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 3a19de41..4c9a9b6e 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -29,11 +29,18 @@ "extensions": [ "ms-python.python", "ms-python.vscode-pylance", + "ms-python.vscode-python-envs", "charliermarsh.ruff", "mtxr.sqltools", "mtxr.sqltools-driver-pg", + "esbenp.prettier-vscode", + "mechatroner.rainbow-csv", "ms-vscode.vscode-node-azure-pack", - "esbenp.prettier-vscode" + "esbenp.prettier-vscode", + "twixes.pypi-assistant", + "ms-python.vscode-python-envs", + "teamsdevapp.vscode-ai-foundry", + "ms-windows-ai-studio.windows-ai-studio" ], // Set *default* container specific settings.json values on container create. "settings": { diff --git a/.env.sample b/.env.sample index ee58dcf2..44517fd1 100644 --- a/.env.sample +++ b/.env.sample @@ -37,8 +37,7 @@ OLLAMA_EMBED_MODEL=nomic-embed-text OLLAMA_EMBEDDING_COLUMN=embedding_nomic # Needed for GitHub Models: GITHUB_TOKEN=YOUR-GITHUB-TOKEN -GITHUB_BASE_URL=https://models.inference.ai.azure.com -GITHUB_MODEL=gpt-4o -GITHUB_EMBED_MODEL=text-embedding-3-large +GITHUB_MODEL=openai/gpt-4o +GITHUB_EMBED_MODEL=openai/text-embedding-3-large GITHUB_EMBED_DIMENSIONS=1024 GITHUB_EMBEDDING_COLUMN=embedding_3l diff --git a/.github/workflows/app-tests.yaml b/.github/workflows/app-tests.yaml index 0c59b5a2..3c1ca9c5 100644 --- a/.github/workflows/app-tests.yaml +++ b/.github/workflows/app-tests.yaml @@ -28,10 +28,8 @@ jobs: fail-fast: false matrix: os: ["ubuntu-latest", "macos-latest-xlarge", "macos-13", "windows-latest"] - python_version: ["3.9", "3.10", "3.11", "3.12"] + python_version: ["3.10", "3.11", "3.12"] exclude: - - os: macos-latest-xlarge - python_version: "3.9" - os: macos-latest-xlarge python_version: "3.10" env: @@ -123,7 +121,7 @@ jobs: key: mypy${{ matrix.os }}-${{ matrix.python_version }}-${{ hashFiles('requirements-dev.txt', 'src/backend/requirements.txt', 'src/backend/pyproject.toml') }} - name: Run MyPy - run: python3 -m mypy . + run: python3 -m mypy . --python-version ${{ matrix.python_version }} - name: Run Pytest run: python3 -m pytest -s -vv --cov --cov-fail-under=85 diff --git a/.github/workflows/azure-dev.yaml b/.github/workflows/azure-dev.yaml index 46c1c9eb..e0e3afb4 100644 --- a/.github/workflows/azure-dev.yaml +++ b/.github/workflows/azure-dev.yaml @@ -49,7 +49,6 @@ jobs: node-version: 20 - name: Log in with Azure (Federated Credentials) - if: ${{ env.AZURE_CLIENT_ID != '' }} run: | azd auth login ` --client-id "$Env:AZURE_CLIENT_ID" ` diff --git a/.github/workflows/evaluate.yaml b/.github/workflows/evaluate.yaml index 04e88bbc..b9aa40f4 100644 --- a/.github/workflows/evaluate.yaml +++ b/.github/workflows/evaluate.yaml @@ -91,21 +91,7 @@ jobs: - name: Install azd uses: Azure/setup-azd@v2.1.0 - - name: Login to Azure - uses: azure/login@v2 - with: - client-id: ${{ env.AZURE_CLIENT_ID }} - tenant-id: ${{ env.AZURE_TENANT_ID }} - subscription-id: ${{ env.AZURE_SUBSCRIPTION_ID }} - - - name: Set az account - uses: azure/CLI@v2 - with: - inlineScript: | - az account set --subscription ${{env.AZURE_SUBSCRIPTION_ID}} - - name: Log in with Azure (Federated Credentials) - if: ${{ env.AZURE_CLIENT_ID != '' }} run: | azd auth login ` --client-id "$Env:AZURE_CLIENT_ID" ` diff --git a/.gitignore b/.gitignore index 0381fcc3..01d8adf3 100644 --- a/.gitignore +++ b/.gitignore @@ -149,3 +149,6 @@ static/ # Playwright test trace test-results/ + +# Test virtual environments +test_venv*/ diff --git a/.vscode/launch.json b/.vscode/launch.json index 4c233e69..d6c07eaf 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -21,6 +21,14 @@ "module": "uvicorn", "args": ["fastapi_app:create_app", "--factory", "--reload"], "justMyCode": false + }, + { + "name": "Python: Current File", + "type": "debugpy", + "request": "launch", + "program": "${file}", + "console": "integratedTerminal", + "justMyCode": false } ], "compounds": [ diff --git a/README.md b/README.md index 53635a83..0415ca58 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,7 @@ A related option is VS Code Dev Containers, which will open the project in your * [Azure Developer CLI (azd)](https://aka.ms/install-azd) * [Node.js 18+](https://nodejs.org/download/) - * [Python 3.9+](https://www.python.org/downloads/) + * [Python 3.10+](https://www.python.org/downloads/) * [PostgreSQL 14+](https://www.postgresql.org/download/) * [pgvector](https://github.com/pgvector/pgvector) * [Docker Desktop](https://www.docker.com/products/docker-desktop/) diff --git a/docs/images/redteam_dashboard.png b/docs/images/redteam_dashboard.png new file mode 100644 index 00000000..639f90b4 Binary files /dev/null and b/docs/images/redteam_dashboard.png differ diff --git a/docs/images/redteam_logs.png b/docs/images/redteam_logs.png new file mode 100644 index 00000000..91422927 Binary files /dev/null and b/docs/images/redteam_logs.png differ diff --git a/docs/safety_evaluation.md b/docs/safety_evaluation.md index 0535acf1..4eb4028e 100644 --- a/docs/safety_evaluation.md +++ b/docs/safety_evaluation.md @@ -1,17 +1,17 @@ # Evaluating RAG answer safety -When deploying a RAG app to production, you should evaluate the safety of the answers generated by the RAG flow. This is important to ensure that the answers are appropriate and do not contain any harmful or sensitive content. This project includes scripts that use Azure AI services to simulate an adversarial user and evaluate the safety of the answers generated in response to those adversarial queries. +When deploying a RAG app to production, you should evaluate the safety of the answers generated by the RAG flow. This is important to ensure that the answers are appropriate and do not contain any harmful or sensitive content. This project includes scripts that use the [azure-ai-evaluation SDK](https://pypi.org/project/azure-ai-evaluation/#history) to perform an [automated safety scan with an AI Red Teaming agent](https://learn.microsoft.com/azure/ai-foundry/how-to/develop/run-scans-ai-red-teaming-agent). * [Deploy an Azure AI project](#deploy-an-azure-ai-project) * [Setup the evaluation environment](#setup-the-evaluation-environment) -* [Simulate and evaluate adversarial users](#simulate-and-evaluate-adversarial-users) -* [Review the safety evaluation results](#review-the-safety-evaluation-results) +* [Run red teaming agent](#run-red-teaming-agent) +* [Review the red teaming results](#review-the-red-teaming-results) ## Deploy an Azure AI project -In order to use the adversarial simulator and safety evaluators, you need an Azure AI project inside an Azure AI Hub. +In order to use the Red Teaming agent, you need an Azure AI project inside Azure AI Foundry. -1. Run this command to tell `azd` to provision an Azure AI project and hub: +1. Run this command to tell `azd` to provision an Azure AI project: ```shell azd env set USE_AI_PROJECT true @@ -45,63 +45,62 @@ In order to use the adversarial simulator and safety evaluators, you need an Azu .evalenv\Scripts\activate ``` -1. Install the dependencies for the safety evaluation script: +3. Install the dependencies for the safety evaluation script: ```bash pip install uv uv pip install -r evals/requirements.txt ``` -## Simulate and evaluate adversarial users +## Run the red teaming agent -Run the following command to simulate adversarial queries and evaluate the safety of the answers generated in response to those queries: +To run the red teaming agent, you need to have the RAG app running at a deployed URL or local URL. Consult the main README for deployment instructions local server instructions. + +In the same terminal where you activated `.evalenv`, run this command to perform a red teaming scan: ```shell -python evals/safety_evaluation.py --target_url --max_simulations +python evals/safety_evaluation.py --target_url --questions_per_category ``` -* `--target_url`: The target URL for the callback. Default is `http://127.0.0.1:8000/chat`, so make sure that the RAG app is running locally. If you are running the RAG app in a different environment, set this to the correct URL. -* `--max_simulations`: The maximum number of simulated user queries. Default is `200`. The higher the number, the longer the evaluation will take. The default of `200` simulations will take about 25 minutes to run, which includes both the time to generate the simulated data and the time to evaluate it. - -## Review the safety evaluation results - -That command will generate a report in `safety_results.json`. -Results will look like this: - -```json -{ - "hate_unfairness": { - "low_count": 20, - "score_total": 8, - "mean_score": 0.4, - "low_rate": 1.0 - }, - "sexual": { - "low_count": 20, - "score_total": 9, - "mean_score": 0.45, - "low_rate": 1.0 - }, - "violence": { - "low_count": 20, - "score_total": 9, - "mean_score": 0.45, - "low_rate": 1.0 - }, - "self_harm": { - "low_count": 20, - "score_total": 10, - "mean_score": 0.5, - "low_rate": 1.0 - } -} -``` +* `--target_url`: The target URL for the callback. Default is `http://127.0.0.1:8000/chat`, which assumes the RAG app is running locally. If you want to scan a deployed app instead, set this to `https://DEPLOYEDURL/chat`. +* `--questions_per_category`: The number of questions per risk category to ask during the scan. There are four risk categories (`hate_unfairness`, `sexual`, `violence`, and `self_harm`). The default is 5 questions per category, but you can decrease this number to 1 for test runs, or increase it for a more thorough evaluation. Note that the total questions asked will be higher, as the red teaming agent is configured to try [multiple attack strategies](https://learn.microsoft.com/azure/ai-foundry/how-to/develop/run-scans-ai-red-teaming-agent#supported-attack-strategies), where it transforms the original question in different ways. + +## Review the red teaming results + +That command will save results both in Azure AI Foundry and in the local `evals/redteams` directory. + +### Review results in Azure AI Foundry + +Navigate from the URL in the terminal output to the results in Azure AI Foundry. +First you'll see overall attack metrics: + +![Red Teaming Agent Results](images/redteam_dashboard.png) + +Then you can dig into the data and see the questions and answers received from your app: + +![Red Teaming Agent Results](images/redteam_logs.png) + +Note that the questions are intentionally adversarial, so you should mentally prepare for that before looking at the results. The goal is to see if your app can handle these adversarial queries and provide safe answers. Even if your scan results in a 0% attack success rate, you should still review the questions and answers to ensure that you're happy with the way your app responds to these adversarial queries. + +Learn more in the [Red Teaming Agent documentation](https://learn.microsoft.com/azure/ai-foundry/how-to/develop/run-scans-ai-red-teaming-agent#viewing-your-results-in-azure-ai-foundry-project). + +## Review results locally + +In addition to the results in Azure AI Foundry, you can also review the results locally in the `evals/redteams` directory. The results are saved in JSON format. + +Each file in this directory corresponds to a single red teaming scan, and contains the following fields: + +* `scorecard`: A summary of the scan results, including the attack success rate and the number of questions asked. +* `parameters`: The parameters used for the scan, including the risk categories and attack strategies. +* `attack_details`: A list of the questions asked during the scan, along with the answers received from your app. +* `studio_url`: A link to the Azure AI Foundry studio where you can view the results in more detail. -The ideal score is `low_rate` of 1.0 and `mean_score` of 0.0. The `low_rate` indicates the fraction of answers that were reported as "Low" or "Very low" by an evaluator. The `mean_score` is the average score of all the answers, where 0 is a very safe answer and 7 is a very unsafe answer. +Learn more in the [Red Teaming Agent documentation](https://learn.microsoft.com/en-us/azure/ai-foundry/how-to/develop/run-scans-ai-red-teaming-agent#results-from-your-automated-scans). ## Resources -To learn more about the Azure AI services used in this project, look through the script and reference the following documentation: +To learn more about the red team scanning, look through the script, documentation, and videos below: -* [Generate simulated data for evaluation](https://learn.microsoft.com/azure/ai-studio/how-to/develop/simulator-interaction-data) -* [Evaluate with the Azure AI Evaluation SDK](https://learn.microsoft.com/azure/ai-studio/how-to/develop/evaluate-sdk) +* [safety_evaluation.py](/evals/safety_evaluation.py) +* [Run automated safety scans with AI Red Teaming Agent](https://learn.microsoft.com/azure/ai-foundry/how-to/develop/run-scans-ai-red-teaming-agent) +* [Build 2025: Red-teaming Demo](https://www.youtube.com/watch?v=sZzcSX7BFVA) diff --git a/evals/redteams/.gitkeep b/evals/redteams/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/evals/requirements.txt b/evals/requirements.txt index ef8aea4d..a5a311ad 100644 --- a/evals/requirements.txt +++ b/evals/requirements.txt @@ -1,4 +1,4 @@ -git+https://github.com/Azure-Samples/ai-rag-chat-evaluator/@2025-02-06b -azure-ai-evaluation +git+https://github.com/Azure-Samples/ai-rag-chat-evaluator/@2025-06-02 +azure-ai-evaluation[redteam]>=1.8.0 rich dotenv-azd diff --git a/evals/safety_evaluation.py b/evals/safety_evaluation.py index 18fc404f..acf9b015 100644 --- a/evals/safety_evaluation.py +++ b/evals/safety_evaluation.py @@ -1,123 +1,87 @@ import argparse import asyncio -import json +import datetime import logging import os import pathlib -from enum import Enum +import sys +from typing import Optional import requests -from azure.ai.evaluation import AzureAIProject, ContentSafetyEvaluator -from azure.ai.evaluation.simulator import ( - AdversarialScenario, - AdversarialSimulator, - SupportedLanguages, -) +from azure.ai.evaluation.red_team import AttackStrategy, RedTeam, RiskCategory from azure.identity import AzureDeveloperCliCredential from dotenv_azd import load_azd_env -from rich.logging import RichHandler -from rich.progress import track - -logger = logging.getLogger("ragapp") root_dir = pathlib.Path(__file__).parent -class HarmSeverityLevel(Enum): - """Harm severity levels reported by the Azure AI Evaluator service. - These constants have been copied from the azure-ai-evaluation package, - where they're currently in a private module. - """ - - VeryLow = "Very low" - Low = "Low" - Medium = "Medium" - High = "High" - - def get_azure_credential(): AZURE_TENANT_ID = os.getenv("AZURE_TENANT_ID") if AZURE_TENANT_ID: - logger.info("Setting up Azure credential using AzureDeveloperCliCredential with tenant_id %s", AZURE_TENANT_ID) + print("Setting up Azure credential using AzureDeveloperCliCredential with tenant_id %s", AZURE_TENANT_ID) azure_credential = AzureDeveloperCliCredential(tenant_id=AZURE_TENANT_ID, process_timeout=60) else: - logger.info("Setting up Azure credential using AzureDeveloperCliCredential for home tenant") + print("Setting up Azure credential using AzureDeveloperCliCredential for home tenant") azure_credential = AzureDeveloperCliCredential(process_timeout=60) return azure_credential -async def callback( - messages: dict, +def callback( + question: str, target_url: str = "http://127.0.0.1:8000/chat", ): - messages_list = messages["messages"] - query = messages_list[-1]["content"] headers = {"Content-Type": "application/json"} body = { - "messages": [{"content": query, "role": "user"}], + "messages": [{"content": question, "role": "user"}], "stream": False, - "context": {"overrides": {"use_advanced_flow": True, "top": 3, "retrieval_mode": "hybrid", "temperature": 0.3}}, + "context": { + "overrides": {"use_advanced_flow": False, "top": 3, "retrieval_mode": "hybrid", "temperature": 0.3} + }, } url = target_url r = requests.post(url, headers=headers, json=body) response = r.json() if "error" in response: - message = {"content": response["error"], "role": "assistant"} + return f"Error received: {response['error']}" else: - message = response["message"] - return {"messages": messages_list + [message]} - - -async def run_simulator(target_url: str, max_simulations: int): - credential = get_azure_credential() - azure_ai_project: AzureAIProject = { - "subscription_id": os.environ["AZURE_SUBSCRIPTION_ID"], - "resource_group_name": os.environ["AZURE_RESOURCE_GROUP"], - "project_name": os.environ["AZURE_AI_PROJECT"], - } - - # Simulate single-turn question-and-answering against the app - scenario = AdversarialScenario.ADVERSARIAL_QA - adversarial_simulator = AdversarialSimulator(azure_ai_project=azure_ai_project, credential=credential) - - outputs = await adversarial_simulator( - scenario=scenario, - target=lambda messages, stream=False, session_state=None, context=None: callback(messages, target_url), - max_simulation_results=max_simulations, - language=SupportedLanguages.English, # Match this to your app language - randomization_seed=1, # For more consistent results, use a fixed seed + return response["message"]["content"] + + +async def run_redteaming(target_url: str, questions_per_category: int = 1, scan_name: Optional[str] = None): + AZURE_AI_FOUNDRY = os.getenv("AZURE_AI_FOUNDRY") + AZURE_AI_PROJECT = os.getenv("AZURE_AI_PROJECT") + model_red_team = RedTeam( + azure_ai_project=f"https://{AZURE_AI_FOUNDRY}.services.ai.azure.com/api/projects/{AZURE_AI_PROJECT}", + credential=get_azure_credential(), + risk_categories=[ + RiskCategory.Violence, + RiskCategory.HateUnfairness, + RiskCategory.Sexual, + RiskCategory.SelfHarm, + ], + num_objectives=questions_per_category, ) - # Run safety evaluation on the outputs and save the scores - # Do not save the outputs, as they may contain disturbing content - evaluators = ["hate_unfairness", "sexual", "violence", "self_harm"] - summary_scores = { - evaluator: {"low_count": 0, "score_total": 0.0, "mean_score": 0.0, "low_rate": 0.0} for evaluator in evaluators - } - for output in track(outputs, description="Evaluating simulated responses..."): - query = output["messages"][0]["content"] - answer = output["messages"][1]["content"] - safety_eval = ContentSafetyEvaluator(credential=credential, azure_ai_project=azure_ai_project) - eval_score = safety_eval(query=query, response=answer) - for evaluator in evaluators: - severity_level = HarmSeverityLevel(eval_score[evaluator]) - if severity_level == HarmSeverityLevel.VeryLow or severity_level == HarmSeverityLevel.Low.name: - summary_scores[evaluator]["low_count"] += 1 - else: - logger.info(f"Failing score from:\nQ: {query}\nA: {answer}\n{evaluator} score: {eval_score}") - numeric_severity_score = eval_score[f"{evaluator}_score"] - if isinstance(numeric_severity_score, float) or isinstance(numeric_severity_score, int): - summary_scores[evaluator]["score_total"] += numeric_severity_score - - # Compute the overall statistics - for evaluator in evaluators: - if len(outputs) > 0: - summary_scores[evaluator]["mean_score"] = summary_scores[evaluator]["score_total"] / len(outputs) - summary_scores[evaluator]["low_rate"] = summary_scores[evaluator]["low_count"] / len(outputs) - - # Save summary scores - with open(root_dir / "safety_results.json", "w") as f: - json.dump(summary_scores, f, indent=2) + if scan_name is None: + timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + scan_name = f"Safety evaluation {timestamp}" + + await model_red_team.scan( + scan_name=scan_name, + output_path=f"{root_dir}/redteams/{scan_name}.json", + attack_strategies=[ + AttackStrategy.Baseline, + # Easy Complexity: + AttackStrategy.Morse, + AttackStrategy.UnicodeConfusable, + AttackStrategy.Url, + # Moderate Complexity: + AttackStrategy.Tense, + # Difficult Complexity: + AttackStrategy.Compose([AttackStrategy.Tense, AttackStrategy.Url]), + ], + target=lambda query: callback(query, target_url), + ) if __name__ == "__main__": @@ -126,14 +90,17 @@ async def run_simulator(target_url: str, max_simulations: int): "--target_url", type=str, default="http://127.0.0.1:8000/chat", help="Target URL for the callback." ) parser.add_argument( - "--max_simulations", type=int, default=200, help="Maximum number of simulations (question/response pairs)." + "--questions_per_category", + type=int, + default=5, + help="Number of questions per risk category to ask during the scan.", ) + parser.add_argument("--scan_name", type=str, default=None, help="Name of the safety evaluation (optional).") args = parser.parse_args() - logging.basicConfig( - level=logging.WARNING, format="%(message)s", datefmt="[%X]", handlers=[RichHandler(rich_tracebacks=True)] - ) - logger.setLevel(logging.INFO) load_azd_env() - - asyncio.run(run_simulator(args.target_url, args.max_simulations)) + try: + asyncio.run(run_redteaming(args.target_url, args.questions_per_category, args.scan_name)) + except Exception: + logging.exception("Unhandled exception in safety evaluation") + sys.exit(1) diff --git a/infra/core/ai/ai-environment.bicep b/infra/core/ai/ai-environment.bicep deleted file mode 100644 index 56c705d1..00000000 --- a/infra/core/ai/ai-environment.bicep +++ /dev/null @@ -1,46 +0,0 @@ -@minLength(1) -@description('Primary location for all resources') -param location string - -@description('The AI Hub resource name.') -param hubName string -@description('The AI Project resource name.') -param projectName string -@description('The Storage Account resource ID.') -param storageAccountId string = '' -@description('The Application Insights resource ID.') -param applicationInsightsId string = '' -@description('The Azure Search resource name.') -param searchServiceName string = '' -@description('The Azure Search connection name.') -param searchConnectionName string = '' -param tags object = {} - -module hub './hub.bicep' = { - name: 'hub' - params: { - location: location - tags: tags - name: hubName - displayName: hubName - storageAccountId: storageAccountId - containerRegistryId: null - applicationInsightsId: applicationInsightsId - aiSearchName: searchServiceName - aiSearchConnectionName: searchConnectionName - } -} - -module project './project.bicep' = { - name: 'project' - params: { - location: location - tags: tags - name: projectName - displayName: projectName - hubName: hub.outputs.name - } -} - - -output projectName string = project.outputs.name diff --git a/infra/core/ai/ai-foundry.bicep b/infra/core/ai/ai-foundry.bicep new file mode 100644 index 00000000..cc787a77 --- /dev/null +++ b/infra/core/ai/ai-foundry.bicep @@ -0,0 +1,117 @@ +@minLength(1) +@description('Primary location for all resources') +param location string + +@description('The AI Foundry resource name.') +param foundryName string + +@description('The AI Project resource name.') +param projectName string = foundryName + +param projectDescription string = '' +param projectDisplayName string = projectName + +@description('The Storage Account resource name.') +param storageAccountName string + +param principalId string +param principalType string + +param tags object = {} + +// Step 1: Create an AI Foundry resource +resource account 'Microsoft.CognitiveServices/accounts@2025-04-01-preview' = { + name: foundryName + location: location + tags: tags + sku: { + name: 'S0' + } + kind: 'AIServices' + identity: { + type: 'SystemAssigned' + } + properties: { + allowProjectManagement: true + customSubDomainName: toLower(foundryName) + networkAcls: { + defaultAction: 'Allow' + virtualNetworkRules: [] + ipRules: [] + } + publicNetworkAccess: 'Enabled' + disableLocalAuth: false + } +} + +// Step 2: Create an AI Foundry project +resource project 'Microsoft.CognitiveServices/accounts/projects@2025-04-01-preview' = { + parent: account + name: projectName + location: location + tags: tags + identity: { + type: 'SystemAssigned' + } + properties: { + description: projectDescription + displayName: projectDisplayName + } +} + +// Step 4: Create a storage account, needed for evaluations +resource storageAccount 'Microsoft.Storage/storageAccounts@2022-09-01' existing = { + name: storageAccountName +} + +// Create a storage account connection for the foundry resource +resource storageAccountConnection 'Microsoft.CognitiveServices/accounts/connections@2025-04-01-preview' = { + parent: account + name: 'default-storage' + properties: { + authType: 'AAD' + category: 'AzureStorageAccount' + isSharedToAll: true + target: storageAccount.properties.primaryEndpoints.blob + metadata: { + ApiType: 'Azure' + ResourceId: storageAccount.id + } + } +} + +// Assign a role to the project's managed identity for the storage account +resource storageRoleAssignment 'Microsoft.Authorization/roleAssignments@2022-04-01' = { + name: guid(storageAccount.id, 'Storage Blob Data Contributor', project.name) + scope: storageAccount + properties: { + roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', 'ba92f5b4-2d11-453d-a403-e96b0029c9fe') // Storage Blob Data Contributor + principalId: project.identity.principalId + principalType: 'ServicePrincipal' + } +} + +// Assign a role to the calling user for the AI Foundry project (needed for projects (including agents) API) +resource projectRoleAssignment 'Microsoft.Authorization/roleAssignments@2022-04-01' = { + name: guid(project.id, 'Azure AI User', principalId) + scope: project + properties: { + roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '53ca6127-db72-4b80-b1b0-d745d6d5456d') // Azure AI User + principalId: principalId + principalType: 'User' + } +} + +// Assign a role to the calling user for the AI Foundry account (needed for Azure OpenAI API) +resource accountRoleAssignment 'Microsoft.Authorization/roleAssignments@2022-04-01' = { + name: guid(account.id, 'Azure AI User', principalId) + scope: account + properties: { + roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '53ca6127-db72-4b80-b1b0-d745d6d5456d') // Azure AI User + principalId: principalId + principalType: 'User' + } +} + +output foundryName string = account.name +output projectName string = project.name diff --git a/infra/core/ai/hub.bicep b/infra/core/ai/hub.bicep deleted file mode 100644 index fd9f68bb..00000000 --- a/infra/core/ai/hub.bicep +++ /dev/null @@ -1,78 +0,0 @@ -@description('The AI Foundry Hub Resource name') -param name string -@description('The display name of the AI Foundry Hub Resource') -param displayName string = name -@description('The storage account ID to use for the AI Foundry Hub Resource') -param storageAccountId string = '' - -@description('The application insights ID to use for the AI Foundry Hub Resource') -param applicationInsightsId string = '' -@description('The container registry ID to use for the AI Foundry Hub Resource') -param containerRegistryId string = '' - -@description('The Azure Cognitive Search service name to use for the AI Foundry Hub Resource') -param aiSearchName string = '' -@description('The Azure Cognitive Search service connection name to use for the AI Foundry Hub Resource') -param aiSearchConnectionName string = '' - - -@description('The SKU name to use for the AI Foundry Hub Resource') -param skuName string = 'Basic' -@description('The SKU tier to use for the AI Foundry Hub Resource') -@allowed(['Basic', 'Free', 'Premium', 'Standard']) -param skuTier string = 'Basic' -@description('The public network access setting to use for the AI Foundry Hub Resource') -@allowed(['Enabled','Disabled']) -param publicNetworkAccess string = 'Enabled' - -param location string = resourceGroup().location -param tags object = {} - -resource hub 'Microsoft.MachineLearningServices/workspaces@2024-07-01-preview' = { - name: name - location: location - tags: tags - sku: { - name: skuName - tier: skuTier - } - kind: 'Hub' - identity: { - type: 'SystemAssigned' - } - properties: { - friendlyName: displayName - storageAccount: !empty(storageAccountId) ? storageAccountId : null - applicationInsights: !empty(applicationInsightsId) ? applicationInsightsId : null - containerRegistry: !empty(containerRegistryId) ? containerRegistryId : null - hbiWorkspace: false - managedNetwork: { - isolationMode: 'Disabled' - } - v1LegacyMode: false - publicNetworkAccess: publicNetworkAccess - } - - resource searchConnection 'connections' = - if (!empty(aiSearchName)) { - name: aiSearchConnectionName - properties: { - category: 'CognitiveSearch' - authType: 'ApiKey' - isSharedToAll: true - target: 'https://${search.name}.search.windows.net/' - credentials: { - key: !empty(aiSearchName) ? search.listAdminKeys().primaryKey : '' - } - } - } -} - -resource search 'Microsoft.Search/searchServices@2021-04-01-preview' existing = - if (!empty(aiSearchName)) { - name: aiSearchName - } - -output name string = hub.name -output id string = hub.id -output principalId string = hub.identity.principalId diff --git a/infra/core/ai/project.bicep b/infra/core/ai/project.bicep deleted file mode 100644 index 34fe7663..00000000 --- a/infra/core/ai/project.bicep +++ /dev/null @@ -1,66 +0,0 @@ -@description('The AI Foundry Hub Resource name') -param name string -@description('The display name of the AI Foundry Hub Resource') -param displayName string = name -@description('The name of the AI Foundry Hub Resource where this project should be created') -param hubName string - -@description('The SKU name to use for the AI Foundry Hub Resource') -param skuName string = 'Basic' -@description('The SKU tier to use for the AI Foundry Hub Resource') -@allowed(['Basic', 'Free', 'Premium', 'Standard']) -param skuTier string = 'Basic' -@description('The public network access setting to use for the AI Foundry Hub Resource') -@allowed(['Enabled','Disabled']) -param publicNetworkAccess string = 'Enabled' - -param location string = resourceGroup().location -param tags object = {} - -resource project 'Microsoft.MachineLearningServices/workspaces@2024-01-01-preview' = { - name: name - location: location - tags: tags - sku: { - name: skuName - tier: skuTier - } - kind: 'Project' - identity: { - type: 'SystemAssigned' - } - properties: { - friendlyName: displayName - hbiWorkspace: false - v1LegacyMode: false - publicNetworkAccess: publicNetworkAccess - hubResourceId: hub.id - } -} - -module mlServiceRoleDataScientist '../security/role.bicep' = { - name: 'ml-service-role-data-scientist' - params: { - principalId: project.identity.principalId - roleDefinitionId: 'f6c7c914-8db3-469d-8ca1-694a8f32e121' - principalType: 'ServicePrincipal' - } -} - -module mlServiceRoleSecretsReader '../security/role.bicep' = { - name: 'ml-service-role-secrets-reader' - params: { - principalId: project.identity.principalId - roleDefinitionId: 'ea01e6af-a1c1-4350-9563-ad00f8c72ec5' - principalType: 'ServicePrincipal' - } -} - -resource hub 'Microsoft.MachineLearningServices/workspaces@2024-01-01-preview' existing = { - name: hubName -} - -output id string = project.id -output name string = project.name -output principalId string = project.identity.principalId -output discoveryUrl string = project.properties.discoveryUrl diff --git a/infra/core/host/container-apps.bicep b/infra/core/host/container-apps.bicep index 1c656e28..74db9bd3 100644 --- a/infra/core/host/container-apps.bicep +++ b/infra/core/host/container-apps.bicep @@ -23,7 +23,7 @@ module containerAppsEnvironment 'container-apps-environment.bicep' = { module containerRegistry 'container-registry.bicep' = { name: '${name}-container-registry' - scope: !empty(containerRegistryResourceGroupName) ? resourceGroup(containerRegistryResourceGroupName) : resourceGroup() + scope: resourceGroup(!empty(containerRegistryResourceGroupName) ? containerRegistryResourceGroupName : resourceGroup().name) params: { name: containerRegistryName location: location diff --git a/infra/main.bicep b/infra/main.bicep index 34b8b6e8..6fc222fd 100644 --- a/infra/main.bicep +++ b/infra/main.bicep @@ -408,15 +408,81 @@ module openAI 'core/ai/cognitiveservices.bicep' = if (deployAzureOpenAI) { } } -module ai 'core/ai/ai-environment.bicep' = if (useAiProject) { +module storage 'br/public:avm/res/storage/storage-account:0.9.1' = if (useAiProject) { + name: 'storage' + scope: resourceGroup + params: { + name: '${take(replace(prefix, '-', ''), 17)}storage' + location: location + tags: tags + kind: 'StorageV2' + skuName: 'Standard_LRS' + networkAcls: { + defaultAction: 'Allow' + bypass: 'AzureServices' + } + allowBlobPublicAccess: false + allowSharedKeyAccess: false + roleAssignments: [ + { + principalId: principalId + principalType: 'User' + roleDefinitionIdOrName: 'Storage Blob Data Contributor' + } + ] + blobServices: { + containers: [ + { + name: 'default' + publicAccess: 'None' + } + ] + cors: { + corsRules: [ + { + allowedOrigins: [ + 'https://mlworkspace.azure.ai' + 'https://ml.azure.com' + 'https://*.ml.azure.com' + 'https://ai.azure.com' + 'https://*.ai.azure.com' + 'https://mlworkspacecanary.azure.ai' + 'https://mlworkspace.azureml-test.net' + ] + allowedMethods: [ + 'GET' + 'HEAD' + 'POST' + 'PUT' + 'DELETE' + 'OPTIONS' + 'PATCH' + ] + maxAgeInSeconds: 1800 + exposedHeaders: [ + '*' + ] + allowedHeaders: [ + '*' + ] + } + ] + } + } + } +} + +module ai 'core/ai/ai-foundry.bicep' = if (useAiProject) { name: 'ai' scope: resourceGroup params: { location: 'swedencentral' tags: tags - hubName: 'aihub-${resourceToken}' - projectName: 'aiproj-${resourceToken}' - applicationInsightsId: monitoring.outputs.applicationInsightsId + foundryName: 'aifoundry-${resourceToken}' + projectName: 'aiproject-${resourceToken}' + storageAccountName: storage.outputs.name + principalId: principalId + principalType: empty(runningOnGh) ? 'User' : 'ServicePrincipal' } } @@ -426,11 +492,22 @@ module openAIRoleUser 'core/security/role.bicep' = { name: 'openai-role-user' params: { principalId: principalId - roleDefinitionId: '5e0bd9bd-7b93-4f28-af87-19fc36ad61bd' + roleDefinitionId: '5e0bd9bd-7b93-4f28-af87-19fc36ad61bd' // Cognitive Services OpenAI User + principalType: empty(runningOnGh) ? 'User' : 'ServicePrincipal' + } +} + +module azureAiUserRole 'core/security/role.bicep' = if (useAiProject && resourceGroup.name != openAIResourceGroup.name) { + name: 'azureai-role-user' + scope: resourceGroup + params: { + principalId: principalId + roleDefinitionId: '53ca6127-db72-4b80-b1b0-d745d6d5456d' // Azure AI User principalType: empty(runningOnGh) ? 'User' : 'ServicePrincipal' } } + // Backend roles module openAIRoleBackend 'core/security/role.bicep' = { scope: openAIResourceGroup @@ -442,6 +519,17 @@ module openAIRoleBackend 'core/security/role.bicep' = { } } +// Application Insights Reader role for web app +module appInsightsReaderRole 'core/security/role.bicep' = { + scope: resourceGroup + name: 'appinsights-reader-role' + params: { + principalId: principalId + roleDefinitionId: '43d0d8ad-25c7-4714-9337-8ba259a9fe05' // Application Insights Component Reader + principalType: 'User' + } +} + output AZURE_LOCATION string = location output AZURE_TENANT_ID string = tenant().tenantId output AZURE_RESOURCE_GROUP string = resourceGroup.name @@ -484,6 +572,7 @@ output AZURE_OPENAI_EVAL_DEPLOYMENT_CAPACITY string = deployAzureOpenAI ? evalDe output AZURE_OPENAI_EVAL_DEPLOYMENT_SKU string = deployAzureOpenAI ? evalDeploymentSku : '' output AZURE_OPENAI_EVAL_MODEL string = deployAzureOpenAI ? evalModelName : '' +output AZURE_AI_FOUNDRY string = useAiProject ? ai.outputs.foundryName : '' output AZURE_AI_PROJECT string = useAiProject ? ai.outputs.projectName : '' output POSTGRES_HOST string = postgresServer.outputs.POSTGRES_DOMAIN_NAME diff --git a/pyproject.toml b/pyproject.toml index aa248487..d84731a2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -7,7 +7,6 @@ lint.isort.known-first-party = ["fastapi_app"] [tool.mypy] check_untyped_defs = true -python_version = 3.9 exclude = [".venv/*"] [tool.pytest.ini_options] diff --git a/requirements-dev.txt b/requirements-dev.txt index 632cfe91..e73ac0c7 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -14,4 +14,3 @@ pytest-snapshot locust psycopg2 dotenv-azd -freezegun diff --git a/src/backend/fastapi_app/api_models.py b/src/backend/fastapi_app/api_models.py index 46574c4e..06d14a6b 100644 --- a/src/backend/fastapi_app/api_models.py +++ b/src/backend/fastapi_app/api_models.py @@ -1,9 +1,8 @@ from enum import Enum -from typing import Any, Optional, Union +from typing import Any, Optional -from openai.types.chat import ChatCompletionMessageParam +from openai.types.responses import ResponseInputItemParam from pydantic import BaseModel, Field -from pydantic_ai.messages import ModelRequest, ModelResponse class AIChatRoles(str, Enum): @@ -37,7 +36,7 @@ class ChatRequestContext(BaseModel): class ChatRequest(BaseModel): - messages: list[ChatCompletionMessageParam] + messages: list[ResponseInputItemParam] context: ChatRequestContext sessionState: Optional[Any] = None @@ -96,7 +95,7 @@ class ChatParams(ChatRequestOverrides): enable_text_search: bool enable_vector_search: bool original_user_query: str - past_messages: list[Union[ModelRequest, ModelResponse]] + past_messages: list[ResponseInputItemParam] class Filter(BaseModel): diff --git a/src/backend/fastapi_app/dependencies.py b/src/backend/fastapi_app/dependencies.py index bd7bc4b4..2715819e 100644 --- a/src/backend/fastapi_app/dependencies.py +++ b/src/backend/fastapi_app/dependencies.py @@ -53,7 +53,7 @@ async def common_parameters(): embedding_column = os.getenv("OLLAMA_EMBEDDING_COLUMN") or "embedding_nomic" elif OPENAI_EMBED_HOST == "github": openai_embed_deployment = None - openai_embed_model = os.getenv("GITHUB_EMBED_MODEL") or "text-embedding-3-large" + openai_embed_model = os.getenv("GITHUB_EMBED_MODEL") or "openai/text-embedding-3-large" openai_embed_dimensions = int(os.getenv("GITHUB_EMBED_DIMENSIONS", 1024)) embedding_column = os.getenv("GITHUB_EMBEDDING_COLUMN") or "embedding_3l" else: @@ -70,7 +70,7 @@ async def common_parameters(): openai_embed_model = os.getenv("OLLAMA_EMBED_MODEL") or "nomic-embed-text" elif OPENAI_CHAT_HOST == "github": openai_chat_deployment = None - openai_chat_model = os.getenv("GITHUB_MODEL") or "gpt-4o" + openai_chat_model = os.getenv("GITHUB_MODEL") or "openai/gpt-4o" else: openai_chat_deployment = None openai_chat_model = os.getenv("OPENAICOM_CHAT_MODEL") or "gpt-3.5-turbo" diff --git a/src/backend/fastapi_app/openai_clients.py b/src/backend/fastapi_app/openai_clients.py index af76229d..b704dc9d 100644 --- a/src/backend/fastapi_app/openai_clients.py +++ b/src/backend/fastapi_app/openai_clients.py @@ -54,11 +54,10 @@ async def create_openai_chat_client( ) elif OPENAI_CHAT_HOST == "github": logger.info("Setting up OpenAI client for chat completions using GitHub Models") - github_base_url = os.getenv("GITHUB_BASE_URL", "https://models.inference.ai.azure.com") - github_model = os.getenv("GITHUB_MODEL", "gpt-4o") - logger.info(f"Using GitHub Models with base URL: {github_base_url}, model: {github_model}") + github_model = os.getenv("GITHUB_MODEL", "openai/gpt-4o") + logger.info(f"Using GitHub Models with model: {github_model}") openai_chat_client = openai.AsyncOpenAI( - base_url=github_base_url, + base_url="https://models.github.ai/inference", api_key=os.getenv("GITHUB_TOKEN"), ) else: @@ -114,11 +113,10 @@ async def create_openai_embed_client( ) elif OPENAI_EMBED_HOST == "github": logger.info("Setting up OpenAI client for embeddings using GitHub Models") - github_base_url = os.getenv("GITHUB_BASE_URL", "https://models.inference.ai.azure.com") - github_embed_model = os.getenv("GITHUB_EMBED_MODEL", "text-embedding-3-small") - logger.info(f"Using GitHub Models with base URL: {github_base_url}, embedding model: {github_embed_model}") + github_embed_model = os.getenv("GITHUB_EMBED_MODEL", "openai/text-embedding-3-small") + logger.info(f"Using GitHub Models with embedding model: {github_embed_model}") openai_embed_client = openai.AsyncOpenAI( - base_url=github_base_url, + base_url="https://models.github.ai/inference", api_key=os.getenv("GITHUB_TOKEN"), ) else: diff --git a/src/backend/fastapi_app/prompts/query_fewshots.json b/src/backend/fastapi_app/prompts/query_fewshots.json index d5ab7f2b..0ef450fd 100644 --- a/src/backend/fastapi_app/prompts/query_fewshots.json +++ b/src/backend/fastapi_app/prompts/query_fewshots.json @@ -1,76 +1,36 @@ [ { - "parts": [ - { - "content": "good options for climbing gear that can be used outside?", - "timestamp": "2025-05-07T19:02:46.977501Z", - "part_kind": "user-prompt" - } - ], - "instructions": null, - "kind": "request" + "role": "user", + "content": "good options for climbing gear that can be used outside?" }, { - "parts": [ - { - "tool_name": "search_database", - "args": "{\"search_query\":\"climbing gear outside\"}", - "tool_call_id": "call_4HeBCmo2uioV6CyoePEGyZPc", - "part_kind": "tool-call" - } - ], - "model_name": "gpt-4o-mini-2024-07-18", - "timestamp": "2025-05-07T19:02:47Z", - "kind": "response" + "id": "madeup", + "call_id": "call_abc123", + "name": "search_database", + "arguments": "{\"search_query\":\"climbing gear outside\"}", + "type": "function_call" }, { - "parts": [ - { - "tool_name": "search_database", - "content": "Search results for climbing gear that can be used outside: ...", - "tool_call_id": "call_4HeBCmo2uioV6CyoePEGyZPc", - "timestamp": "2025-05-07T19:02:48.242408Z", - "part_kind": "tool-return" - } - ], - "instructions": null, - "kind": "request" + "id": "madeupoutput", + "call_id": "call_abc123", + "output": "Search results for climbing gear that can be used outside: ...", + "type": "function_call_output" }, { - "parts": [ - { - "content": "are there any shoes less than $50?", - "timestamp": "2025-05-07T19:02:46.977501Z", - "part_kind": "user-prompt" - } - ], - "instructions": null, - "kind": "request" + "role": "user", + "content": "are there any shoes less than $50?" }, { - "parts": [ - { - "tool_name": "search_database", - "args": "{\"search_query\":\"shoes\",\"price_filter\":{\"comparison_operator\":\"<\",\"value\":50}}", - "tool_call_id": "call_4HeBCmo2uioV6CyoePEGyZPc", - "part_kind": "tool-call" - } - ], - "model_name": "gpt-4o-mini-2024-07-18", - "timestamp": "2025-05-07T19:02:47Z", - "kind": "response" + "id": "madeup", + "call_id": "call_abc456", + "name": "search_database", + "arguments": "{\"search_query\":\"shoes\",\"price_filter\":{\"comparison_operator\":\"<\",\"value\":50}}", + "type": "function_call" }, { - "parts": [ - { - "tool_name": "search_database", - "content": "Search results for shoes cheaper than 50: ...", - "tool_call_id": "call_4HeBCmo2uioV6CyoePEGyZPc", - "timestamp": "2025-05-07T19:02:48.242408Z", - "part_kind": "tool-return" - } - ], - "instructions": null, - "kind": "request" + "id": "madeupoutput", + "call_id": "call_abc456", + "output": "Search results for shoes cheaper than 50: ...", + "type": "function_call_output" } ] diff --git a/src/backend/fastapi_app/rag_advanced.py b/src/backend/fastapi_app/rag_advanced.py index 3541d8c7..eb53aa6a 100644 --- a/src/backend/fastapi_app/rag_advanced.py +++ b/src/backend/fastapi_app/rag_advanced.py @@ -1,13 +1,19 @@ +import json from collections.abc import AsyncGenerator from typing import Optional, Union +from agents import ( + Agent, + ItemHelpers, + ModelSettings, + OpenAIChatCompletionsModel, + Runner, + ToolCallOutputItem, + function_tool, + set_tracing_disabled, +) from openai import AsyncAzureOpenAI, AsyncOpenAI -from openai.types.chat import ChatCompletionMessageParam -from pydantic_ai import Agent, RunContext -from pydantic_ai.messages import ModelMessagesTypeAdapter -from pydantic_ai.models.openai import OpenAIModel -from pydantic_ai.providers.openai import OpenAIProvider -from pydantic_ai.settings import ModelSettings +from openai.types.responses import EasyInputMessageParam, ResponseInputItemParam, ResponseTextDeltaEvent from fastapi_app.api_models import ( AIChatRoles, @@ -24,7 +30,9 @@ ThoughtStep, ) from fastapi_app.postgres_searcher import PostgresSearcher -from fastapi_app.rag_base import ChatParams, RAGChatBase +from fastapi_app.rag_base import RAGChatBase + +set_tracing_disabled(disabled=True) class AdvancedRAGChat(RAGChatBase): @@ -34,7 +42,7 @@ class AdvancedRAGChat(RAGChatBase): def __init__( self, *, - messages: list[ChatCompletionMessageParam], + messages: list[ResponseInputItemParam], overrides: ChatRequestOverrides, searcher: PostgresSearcher, openai_chat_client: Union[AsyncOpenAI, AsyncAzureOpenAI], @@ -46,34 +54,29 @@ def __init__( self.model_for_thoughts = ( {"model": chat_model, "deployment": chat_deployment} if chat_deployment else {"model": chat_model} ) - pydantic_chat_model = OpenAIModel( - chat_model if chat_deployment is None else chat_deployment, - provider=OpenAIProvider(openai_client=openai_chat_client), + openai_agents_model = OpenAIChatCompletionsModel( + model=chat_model if chat_deployment is None else chat_deployment, openai_client=openai_chat_client ) - self.search_agent = Agent[ChatParams, SearchResults]( - pydantic_chat_model, - model_settings=ModelSettings( - temperature=0.0, - max_tokens=500, - **({"seed": self.chat_params.seed} if self.chat_params.seed is not None else {}), - ), - system_prompt=self.query_prompt_template, - tools=[self.search_database], - output_type=SearchResults, + self.search_agent = Agent( + name="Searcher", + instructions=self.query_prompt_template, + tools=[function_tool(self.search_database)], + tool_use_behavior="stop_on_first_tool", + model=openai_agents_model, ) self.answer_agent = Agent( - pydantic_chat_model, - system_prompt=self.answer_prompt_template, + name="Answerer", + instructions=self.answer_prompt_template, + model=openai_agents_model, model_settings=ModelSettings( temperature=self.chat_params.temperature, max_tokens=self.chat_params.response_token_limit, - **({"seed": self.chat_params.seed} if self.chat_params.seed is not None else {}), + extra_body={"seed": self.chat_params.seed} if self.chat_params.seed is not None else {}, ), ) async def search_database( self, - ctx: RunContext[ChatParams], search_query: str, price_filter: Optional[PriceFilter] = None, brand_filter: Optional[BrandFilter] = None, @@ -97,9 +100,9 @@ async def search_database( filters.append(brand_filter) results = await self.searcher.search_and_embed( search_query, - top=ctx.deps.top, - enable_vector_search=ctx.deps.enable_vector_search, - enable_text_search=ctx.deps.enable_text_search, + top=self.chat_params.top, + enable_vector_search=self.chat_params.enable_vector_search, + enable_text_search=self.chat_params.enable_text_search, filters=filters, ) return SearchResults( @@ -107,56 +110,63 @@ async def search_database( ) async def prepare_context(self) -> tuple[list[ItemPublic], list[ThoughtStep]]: - few_shots = ModelMessagesTypeAdapter.validate_json(self.query_fewshots) + few_shots: list[ResponseInputItemParam] = json.loads(self.query_fewshots) user_query = f"Find search results for user query: {self.chat_params.original_user_query}" - results = await self.search_agent.run( - user_query, - message_history=few_shots + self.chat_params.past_messages, - deps=self.chat_params, - ) - items = results.output.items + new_user_message = EasyInputMessageParam(role="user", content=user_query) + all_messages = few_shots + self.chat_params.past_messages + [new_user_message] + + run_results = await Runner.run(self.search_agent, input=all_messages) + most_recent_response = run_results.new_items[-1] + if isinstance(most_recent_response, ToolCallOutputItem): + search_results = most_recent_response.output + else: + raise ValueError("Error retrieving search results, model did not call tool properly") + thoughts = [ ThoughtStep( title="Prompt to generate search arguments", - description=results.all_messages(), + description=[{"content": self.query_prompt_template}] + + ItemHelpers.input_to_new_input_list(run_results.input), props=self.model_for_thoughts, ), ThoughtStep( title="Search using generated search arguments", - description=results.output.query, + description=search_results.query, props={ "top": self.chat_params.top, "vector_search": self.chat_params.enable_vector_search, "text_search": self.chat_params.enable_text_search, - "filters": results.output.filters, + "filters": search_results.filters, }, ), ThoughtStep( title="Search results", - description=items, + description=search_results.items, ), ] - return items, thoughts + return search_results.items, thoughts async def answer( self, items: list[ItemPublic], earlier_thoughts: list[ThoughtStep], ) -> RetrievalResponse: - response = await self.answer_agent.run( - user_prompt=self.prepare_rag_request(self.chat_params.original_user_query, items), - message_history=self.chat_params.past_messages, + run_results = await Runner.run( + self.answer_agent, + input=self.chat_params.past_messages + + [{"content": self.prepare_rag_request(self.chat_params.original_user_query, items), "role": "user"}], ) return RetrievalResponse( - message=Message(content=str(response.output), role=AIChatRoles.ASSISTANT), + message=Message(content=str(run_results.final_output), role=AIChatRoles.ASSISTANT), context=RAGContext( data_points={item.id: item for item in items}, thoughts=earlier_thoughts + [ ThoughtStep( title="Prompt to generate answer", - description=response.all_messages(), + description=[{"content": self.answer_prompt_template}] + + ItemHelpers.input_to_new_input_list(run_results.input), props=self.model_for_thoughts, ), ], @@ -168,24 +178,28 @@ async def answer_stream( items: list[ItemPublic], earlier_thoughts: list[ThoughtStep], ) -> AsyncGenerator[RetrievalResponseDelta, None]: - async with self.answer_agent.run_stream( - self.prepare_rag_request(self.chat_params.original_user_query, items), - message_history=self.chat_params.past_messages, - ) as agent_stream_runner: - yield RetrievalResponseDelta( - context=RAGContext( - data_points={item.id: item for item in items}, - thoughts=earlier_thoughts - + [ - ThoughtStep( - title="Prompt to generate answer", - description=agent_stream_runner.all_messages(), - props=self.model_for_thoughts, - ), - ], - ), - ) - - async for message in agent_stream_runner.stream_text(delta=True, debounce_by=None): - yield RetrievalResponseDelta(delta=Message(content=str(message), role=AIChatRoles.ASSISTANT)) - return + run_results = Runner.run_streamed( + self.answer_agent, + input=self.chat_params.past_messages + + [{"content": self.prepare_rag_request(self.chat_params.original_user_query, items), "role": "user"}], # noqa + ) + + yield RetrievalResponseDelta( + context=RAGContext( + data_points={item.id: item for item in items}, + thoughts=earlier_thoughts + + [ + ThoughtStep( + title="Prompt to generate answer", + description=[{"content": self.answer_prompt_template}] + + ItemHelpers.input_to_new_input_list(run_results.input), + props=self.model_for_thoughts, + ), + ], + ), + ) + + async for event in run_results.stream_events(): + if event.type == "raw_response_event" and isinstance(event.data, ResponseTextDeltaEvent): + yield RetrievalResponseDelta(delta=Message(content=str(event.data.delta), role=AIChatRoles.ASSISTANT)) + return diff --git a/src/backend/fastapi_app/rag_base.py b/src/backend/fastapi_app/rag_base.py index 62bdc800..54e633c2 100644 --- a/src/backend/fastapi_app/rag_base.py +++ b/src/backend/fastapi_app/rag_base.py @@ -1,10 +1,8 @@ import pathlib from abc import ABC, abstractmethod from collections.abc import AsyncGenerator -from typing import Union -from openai.types.chat import ChatCompletionMessageParam -from pydantic_ai.messages import ModelRequest, ModelResponse, TextPart, UserPromptPart +from openai.types.responses import ResponseInputItemParam from fastapi_app.api_models import ( ChatParams, @@ -20,32 +18,17 @@ class RAGChatBase(ABC): prompts_dir = pathlib.Path(__file__).parent / "prompts/" answer_prompt_template = open(prompts_dir / "answer.txt").read() - def get_chat_params( - self, messages: list[ChatCompletionMessageParam], overrides: ChatRequestOverrides - ) -> ChatParams: + def get_chat_params(self, messages: list[ResponseInputItemParam], overrides: ChatRequestOverrides) -> ChatParams: response_token_limit = 1024 prompt_template = overrides.prompt_template or self.answer_prompt_template enable_text_search = overrides.retrieval_mode in ["text", "hybrid", None] enable_vector_search = overrides.retrieval_mode in ["vectors", "hybrid", None] - original_user_query = messages[-1]["content"] + original_user_query = messages[-1].get("content") if not isinstance(original_user_query, str): raise ValueError("The most recent message content must be a string.") - # Convert to PydanticAI format: - past_messages: list[Union[ModelRequest, ModelResponse]] = [] - for message in messages[:-1]: - content = message["content"] - if not isinstance(content, str): - raise ValueError("All messages must have string content.") - if message["role"] == "user": - past_messages.append(ModelRequest(parts=[UserPromptPart(content=content)])) - elif message["role"] == "assistant": - past_messages.append(ModelResponse(parts=[TextPart(content=content)])) - else: - raise ValueError(f"Cannot convert message: {message}") - return ChatParams( top=overrides.top, temperature=overrides.temperature, @@ -57,7 +40,7 @@ def get_chat_params( enable_text_search=enable_text_search, enable_vector_search=enable_vector_search, original_user_query=original_user_query, - past_messages=past_messages, + past_messages=messages[:-1], ) @abstractmethod diff --git a/src/backend/fastapi_app/rag_simple.py b/src/backend/fastapi_app/rag_simple.py index 2d41bb9d..69126618 100644 --- a/src/backend/fastapi_app/rag_simple.py +++ b/src/backend/fastapi_app/rag_simple.py @@ -1,12 +1,9 @@ from collections.abc import AsyncGenerator from typing import Optional, Union +from agents import Agent, ItemHelpers, ModelSettings, OpenAIChatCompletionsModel, Runner, set_tracing_disabled from openai import AsyncAzureOpenAI, AsyncOpenAI -from openai.types.chat import ChatCompletionMessageParam -from pydantic_ai import Agent -from pydantic_ai.models.openai import OpenAIModel -from pydantic_ai.providers.openai import OpenAIProvider -from pydantic_ai.settings import ModelSettings +from openai.types.responses import ResponseInputItemParam, ResponseTextDeltaEvent from fastapi_app.api_models import ( AIChatRoles, @@ -21,12 +18,14 @@ from fastapi_app.postgres_searcher import PostgresSearcher from fastapi_app.rag_base import RAGChatBase +set_tracing_disabled(disabled=True) + class SimpleRAGChat(RAGChatBase): def __init__( self, *, - messages: list[ChatCompletionMessageParam], + messages: list[ResponseInputItemParam], overrides: ChatRequestOverrides, searcher: PostgresSearcher, openai_chat_client: Union[AsyncOpenAI, AsyncAzureOpenAI], @@ -38,17 +37,17 @@ def __init__( self.model_for_thoughts = ( {"model": chat_model, "deployment": chat_deployment} if chat_deployment else {"model": chat_model} ) - pydantic_chat_model = OpenAIModel( - chat_model if chat_deployment is None else chat_deployment, - provider=OpenAIProvider(openai_client=openai_chat_client), + openai_agents_model = OpenAIChatCompletionsModel( + model=chat_model if chat_deployment is None else chat_deployment, openai_client=openai_chat_client ) self.answer_agent = Agent( - pydantic_chat_model, - system_prompt=self.answer_prompt_template, + name="Answerer", + instructions=self.answer_prompt_template, + model=openai_agents_model, model_settings=ModelSettings( temperature=self.chat_params.temperature, max_tokens=self.chat_params.response_token_limit, - **({"seed": self.chat_params.seed} if self.chat_params.seed is not None else {}), + extra_body={"seed": self.chat_params.seed} if self.chat_params.seed is not None else {}, ), ) @@ -85,19 +84,22 @@ async def answer( items: list[ItemPublic], earlier_thoughts: list[ThoughtStep], ) -> RetrievalResponse: - response = await self.answer_agent.run( - user_prompt=self.prepare_rag_request(self.chat_params.original_user_query, items), - message_history=self.chat_params.past_messages, + run_results = await Runner.run( + self.answer_agent, + input=self.chat_params.past_messages + + [{"content": self.prepare_rag_request(self.chat_params.original_user_query, items), "role": "user"}], ) + return RetrievalResponse( - message=Message(content=str(response.output), role=AIChatRoles.ASSISTANT), + message=Message(content=str(run_results.final_output), role=AIChatRoles.ASSISTANT), context=RAGContext( data_points={item.id: item for item in items}, thoughts=earlier_thoughts + [ ThoughtStep( title="Prompt to generate answer", - description=response.all_messages(), + description=[{"content": self.answer_prompt_template}] + + ItemHelpers.input_to_new_input_list(run_results.input), props=self.model_for_thoughts, ), ], @@ -109,24 +111,28 @@ async def answer_stream( items: list[ItemPublic], earlier_thoughts: list[ThoughtStep], ) -> AsyncGenerator[RetrievalResponseDelta, None]: - async with self.answer_agent.run_stream( - self.prepare_rag_request(self.chat_params.original_user_query, items), - message_history=self.chat_params.past_messages, - ) as agent_stream_runner: - yield RetrievalResponseDelta( - context=RAGContext( - data_points={item.id: item for item in items}, - thoughts=earlier_thoughts - + [ - ThoughtStep( - title="Prompt to generate answer", - description=agent_stream_runner.all_messages(), - props=self.model_for_thoughts, - ), - ], - ), - ) + run_results = Runner.run_streamed( + self.answer_agent, + input=self.chat_params.past_messages + + [{"content": self.prepare_rag_request(self.chat_params.original_user_query, items), "role": "user"}], + ) + + yield RetrievalResponseDelta( + context=RAGContext( + data_points={item.id: item for item in items}, + thoughts=earlier_thoughts + + [ + ThoughtStep( + title="Prompt to generate answer", + description=[{"content": self.answer_agent.instructions}] + + ItemHelpers.input_to_new_input_list(run_results.input), + props=self.model_for_thoughts, + ), + ], + ), + ) - async for message in agent_stream_runner.stream_text(delta=True, debounce_by=None): - yield RetrievalResponseDelta(delta=Message(content=str(message), role=AIChatRoles.ASSISTANT)) - return + async for event in run_results.stream_events(): + if event.type == "raw_response_event" and isinstance(event.data, ResponseTextDeltaEvent): + yield RetrievalResponseDelta(delta=Message(content=str(event.data.delta), role=AIChatRoles.ASSISTANT)) + return diff --git a/src/backend/pyproject.toml b/src/backend/pyproject.toml index 7f5ac750..7ede97c9 100644 --- a/src/backend/pyproject.toml +++ b/src/backend/pyproject.toml @@ -6,20 +6,18 @@ dependencies = [ "fastapi>=0.111.0,<1.0.0", "uvicorn>=0.30.1,<1.0.0", "python-dotenv>=1.0.1,<2.0.0", - "environs>=11.0.0,<12.0.0", + "environs>=11.0.0,<15.0.0", "azure-identity>=1.16.1,<2.0.0", "aiohttp>=3.9.5,<4.0.0", "asyncpg>=0.29.0,<1.0.0", "SQLAlchemy[asyncio]>=2.0.30,<3.0.0", "pgvector>=0.3.0,<0.4.0", "openai>=1.34.0,<2.0.0", - "tiktoken>=0.7.0,<0.8.0", - "openai-messages-token-helper>=0.1.8,<0.2.0", "azure-monitor-opentelemetry>=1.6.0,<2.0.0", "opentelemetry-instrumentation-sqlalchemy", "opentelemetry-instrumentation-aiohttp-client", "opentelemetry-instrumentation-openai", - "pydantic-ai-slim[openai]" + "openai-agents" ] [build-system] diff --git a/src/backend/requirements.txt b/src/backend/requirements.txt index bc349b03..b83031b6 100644 --- a/src/backend/requirements.txt +++ b/src/backend/requirements.txt @@ -1,19 +1,21 @@ # This file was autogenerated by uv via the following command: -# uv pip compile pyproject.toml -o requirements.txt --python-version 3.9 -aiohappyeyeballs==2.4.4 +# uv pip compile pyproject.toml -o requirements_new.txt --python-version 3.10 +aiohappyeyeballs==2.6.1 # via aiohttp -aiohttp==3.11.18 +aiohttp==3.12.14 # via fastapi-app (pyproject.toml) -aiosignal==1.3.1 +aiosignal==1.4.0 # via aiohttp annotated-types==0.7.0 # via pydantic -anyio==4.6.2.post1 +anyio==4.9.0 # via # httpx + # mcp # openai + # sse-starlette # starlette -asgiref==3.8.1 +asgiref==3.9.1 # via opentelemetry-instrumentation-asgi async-timeout==5.0.1 # via @@ -21,24 +23,31 @@ async-timeout==5.0.1 # asyncpg asyncpg==0.30.0 # via fastapi-app (pyproject.toml) -attrs==24.2.0 - # via aiohttp -azure-core==1.32.0 +attrs==25.3.0 + # via + # aiohttp + # jsonschema + # referencing +azure-core==1.35.0 # via # azure-core-tracing-opentelemetry # azure-identity # azure-monitor-opentelemetry # azure-monitor-opentelemetry-exporter # msrest -azure-core-tracing-opentelemetry==1.0.0b11 +azure-core-tracing-opentelemetry==1.0.0b12 # via azure-monitor-opentelemetry -azure-identity==1.19.0 - # via fastapi-app (pyproject.toml) -azure-monitor-opentelemetry==1.6.8 +azure-identity==1.23.1 + # via + # fastapi-app (pyproject.toml) + # azure-monitor-opentelemetry-exporter +azure-monitor-opentelemetry==1.6.12 # via fastapi-app (pyproject.toml) -azure-monitor-opentelemetry-exporter==1.0.0b32 +azure-monitor-opentelemetry-exporter==1.0.0b40 # via azure-monitor-opentelemetry -certifi==2024.8.30 +backports-datetime-fromisoformat==2.0.3 + # via marshmallow +certifi==2025.7.14 # via # httpcore # httpx @@ -46,94 +55,94 @@ certifi==2024.8.30 # requests cffi==1.17.1 # via cryptography -charset-normalizer==3.4.0 +charset-normalizer==3.4.2 # via requests -click==8.1.7 +click==8.2.1 # via uvicorn colorama==0.4.6 # via griffe -cryptography==44.0.3 +cryptography==45.0.5 # via # azure-identity # msal # pyjwt -deprecated==1.2.15 +deprecated==1.2.18 # via # opentelemetry-api # opentelemetry-semantic-conventions distro==1.9.0 # via openai -environs==14.1.1 +environs==14.2.0 # via fastapi-app (pyproject.toml) -eval-type-backport==0.2.2 - # via pydantic-ai-slim -exceptiongroup==1.2.2 - # via - # anyio - # pydantic-ai-slim -fastapi==0.115.8 +exceptiongroup==1.3.0 + # via anyio +fastapi==0.116.1 # via fastapi-app (pyproject.toml) fixedint==0.1.6 # via azure-monitor-opentelemetry-exporter -frozenlist==1.5.0 +frozenlist==1.7.0 # via # aiohttp # aiosignal -greenlet==3.1.1 +greenlet==3.2.3 # via sqlalchemy griffe==1.7.3 - # via pydantic-ai-slim -h11==0.14.0 + # via openai-agents +h11==0.16.0 # via # httpcore # uvicorn -httpcore==1.0.7 +httpcore==1.0.9 # via httpx -httpx==0.28.0 +httpx==0.28.1 # via + # mcp # openai - # pydantic-ai-slim - # pydantic-graph +httpx-sse==0.4.1 + # via mcp idna==3.10 # via # anyio # httpx # requests # yarl -importlib-metadata==8.4.0 +importlib-metadata==8.6.1 # via opentelemetry-api isodate==0.7.2 # via msrest -jiter==0.8.0 +jiter==0.10.0 # via openai -logfire-api==3.14.1 - # via pydantic-graph -marshmallow==3.23.1 +jsonschema==4.24.0 + # via mcp +jsonschema-specifications==2025.4.1 + # via jsonschema +marshmallow==4.0.0 # via environs -msal==1.31.1 +mcp==1.11.0 + # via openai-agents +msal==1.32.3 # via # azure-identity # msal-extensions -msal-extensions==1.2.0 +msal-extensions==1.3.1 # via azure-identity msrest==0.7.1 # via azure-monitor-opentelemetry-exporter -multidict==6.1.0 +multidict==6.6.3 # via # aiohttp # yarl -numpy==2.0.2 +numpy==2.2.6 # via pgvector -oauthlib==3.2.2 +oauthlib==3.3.1 # via requests-oauthlib -openai==1.77.0 +openai==1.96.1 # via # fastapi-app (pyproject.toml) - # openai-messages-token-helper - # pydantic-ai-slim -openai-messages-token-helper==0.1.11 + # openai-agents +openai-agents==0.2.0 # via fastapi-app (pyproject.toml) -opentelemetry-api==1.30.0 +opentelemetry-api==1.31.1 # via # azure-core-tracing-opentelemetry # azure-monitor-opentelemetry-exporter @@ -153,8 +162,7 @@ opentelemetry-api==1.30.0 # opentelemetry-instrumentation-wsgi # opentelemetry-sdk # opentelemetry-semantic-conventions - # pydantic-ai-slim -opentelemetry-instrumentation==0.51b0 +opentelemetry-instrumentation==0.52b1 # via # opentelemetry-instrumentation-aiohttp-client # opentelemetry-instrumentation-asgi @@ -169,42 +177,42 @@ opentelemetry-instrumentation==0.51b0 # opentelemetry-instrumentation-urllib # opentelemetry-instrumentation-urllib3 # opentelemetry-instrumentation-wsgi -opentelemetry-instrumentation-aiohttp-client==0.51b0 +opentelemetry-instrumentation-aiohttp-client==0.52b1 # via fastapi-app (pyproject.toml) -opentelemetry-instrumentation-asgi==0.51b0 +opentelemetry-instrumentation-asgi==0.52b1 # via opentelemetry-instrumentation-fastapi -opentelemetry-instrumentation-dbapi==0.51b0 +opentelemetry-instrumentation-dbapi==0.52b1 # via opentelemetry-instrumentation-psycopg2 -opentelemetry-instrumentation-django==0.51b0 +opentelemetry-instrumentation-django==0.52b1 # via azure-monitor-opentelemetry -opentelemetry-instrumentation-fastapi==0.51b0 +opentelemetry-instrumentation-fastapi==0.52b1 # via azure-monitor-opentelemetry -opentelemetry-instrumentation-flask==0.51b0 +opentelemetry-instrumentation-flask==0.52b1 # via azure-monitor-opentelemetry -opentelemetry-instrumentation-openai==0.38.7 +opentelemetry-instrumentation-openai==0.41.0 # via fastapi-app (pyproject.toml) -opentelemetry-instrumentation-psycopg2==0.51b0 +opentelemetry-instrumentation-psycopg2==0.52b1 # via azure-monitor-opentelemetry -opentelemetry-instrumentation-requests==0.51b0 +opentelemetry-instrumentation-requests==0.52b1 # via azure-monitor-opentelemetry -opentelemetry-instrumentation-sqlalchemy==0.51b0 +opentelemetry-instrumentation-sqlalchemy==0.52b1 # via fastapi-app (pyproject.toml) -opentelemetry-instrumentation-urllib==0.51b0 +opentelemetry-instrumentation-urllib==0.52b1 # via azure-monitor-opentelemetry -opentelemetry-instrumentation-urllib3==0.51b0 +opentelemetry-instrumentation-urllib3==0.52b1 # via azure-monitor-opentelemetry -opentelemetry-instrumentation-wsgi==0.51b0 +opentelemetry-instrumentation-wsgi==0.52b1 # via # opentelemetry-instrumentation-django # opentelemetry-instrumentation-flask opentelemetry-resource-detector-azure==0.1.5 # via azure-monitor-opentelemetry -opentelemetry-sdk==1.30.0 +opentelemetry-sdk==1.31.1 # via # azure-monitor-opentelemetry # azure-monitor-opentelemetry-exporter # opentelemetry-resource-detector-azure -opentelemetry-semantic-conventions==0.51b0 +opentelemetry-semantic-conventions==0.52b1 # via # opentelemetry-instrumentation # opentelemetry-instrumentation-aiohttp-client @@ -220,9 +228,9 @@ opentelemetry-semantic-conventions==0.51b0 # opentelemetry-instrumentation-urllib3 # opentelemetry-instrumentation-wsgi # opentelemetry-sdk -opentelemetry-semantic-conventions-ai==0.4.2 +opentelemetry-semantic-conventions-ai==0.4.10 # via opentelemetry-instrumentation-openai -opentelemetry-util-http==0.51b0 +opentelemetry-util-http==0.52b1 # via # opentelemetry-instrumentation-aiohttp-client # opentelemetry-instrumentation-asgi @@ -233,97 +241,116 @@ opentelemetry-util-http==0.51b0 # opentelemetry-instrumentation-urllib # opentelemetry-instrumentation-urllib3 # opentelemetry-instrumentation-wsgi -packaging==24.2 +packaging==25.0 # via - # marshmallow # opentelemetry-instrumentation # opentelemetry-instrumentation-flask # opentelemetry-instrumentation-sqlalchemy pgvector==0.3.6 # via fastapi-app (pyproject.toml) -pillow==11.0.0 - # via openai-messages-token-helper -portalocker==2.10.1 - # via msal-extensions -propcache==0.2.1 +propcache==0.3.2 # via # aiohttp # yarl -psutil==5.9.8 +psutil==7.0.0 # via azure-monitor-opentelemetry-exporter pycparser==2.22 # via cffi -pydantic==2.10.2 +pydantic==2.11.7 # via # fastapi + # mcp # openai - # pydantic-ai-slim - # pydantic-graph -pydantic-ai-slim==0.1.10 - # via fastapi-app (pyproject.toml) -pydantic-core==2.27.1 + # openai-agents + # pydantic-settings +pydantic-core==2.33.2 # via pydantic -pydantic-graph==0.1.10 - # via pydantic-ai-slim +pydantic-settings==2.10.1 + # via mcp pyjwt==2.10.1 # via msal -python-dotenv==1.0.1 +python-dotenv==1.1.1 # via # fastapi-app (pyproject.toml) # environs + # pydantic-settings +python-multipart==0.0.20 + # via mcp +referencing==0.36.2 + # via + # jsonschema + # jsonschema-specifications regex==2024.11.6 # via tiktoken -requests==2.32.3 +requests==2.32.4 # via # azure-core # msal # msrest + # openai-agents # requests-oauthlib # tiktoken requests-oauthlib==2.0.0 # via msrest -six==1.16.0 +rpds-py==0.26.0 + # via + # jsonschema + # referencing +six==1.17.0 # via azure-core sniffio==1.3.1 # via # anyio # openai -sqlalchemy==2.0.36 +sqlalchemy==2.0.41 # via fastapi-app (pyproject.toml) -starlette==0.41.3 - # via fastapi -tiktoken==0.7.0 +sse-starlette==2.4.1 + # via mcp +starlette==0.47.2 # via - # fastapi-app (pyproject.toml) - # openai-messages-token-helper - # opentelemetry-instrumentation-openai + # fastapi + # mcp +tiktoken==0.9.0 + # via opentelemetry-instrumentation-openai tqdm==4.67.1 # via openai -typing-extensions==4.12.2 +types-requests==2.32.4.20250611 + # via openai-agents +typing-extensions==4.14.1 # via + # aiosignal # anyio # asgiref # azure-core # azure-identity + # environs + # exceptiongroup # fastapi + # marshmallow # multidict # openai + # openai-agents # opentelemetry-sdk # pydantic # pydantic-core + # referencing # sqlalchemy # starlette # typing-inspection # uvicorn -typing-inspection==0.4.0 +typing-inspection==0.4.1 # via - # pydantic-ai-slim - # pydantic-graph -urllib3==2.4.0 - # via requests -uvicorn==0.32.1 - # via fastapi-app (pyproject.toml) -wrapt==1.17.0 + # pydantic + # pydantic-settings +urllib3==2.5.0 + # via + # requests + # types-requests +uvicorn==0.35.0 + # via + # fastapi-app (pyproject.toml) + # mcp +wrapt==1.17.2 # via # deprecated # opentelemetry-instrumentation @@ -331,7 +358,7 @@ wrapt==1.17.0 # opentelemetry-instrumentation-dbapi # opentelemetry-instrumentation-sqlalchemy # opentelemetry-instrumentation-urllib3 -yarl==1.18.3 +yarl==1.20.1 # via aiohttp -zipp==3.21.0 +zipp==3.23.0 # via importlib-metadata diff --git a/src/frontend/package-lock.json b/src/frontend/package-lock.json index 92f7e615..252ddabd 100644 --- a/src/frontend/package-lock.json +++ b/src/frontend/package-lock.json @@ -308,11 +308,10 @@ } }, "node_modules/@babel/runtime": { - "version": "7.22.15", + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.27.1.tgz", + "integrity": "sha512-1x3D2xEk2fRo3PAhwQwu5UubzgiVWSXTBfWpVd2Mx2AzRqJuDJCsgaDVZ7HB5iGzDW1Hl1sWN2mFyKjmR9uAog==", "license": "MIT", - "dependencies": { - "regenerator-runtime": "^0.14.0" - }, "engines": { "node": ">=6.9.0" } @@ -4072,10 +4071,6 @@ "node": ">=6" } }, - "node_modules/regenerator-runtime": { - "version": "0.14.0", - "license": "MIT" - }, "node_modules/resolve": { "version": "1.22.4", "license": "MIT", @@ -4606,10 +4601,9 @@ } }, "@babel/runtime": { - "version": "7.22.15", - "requires": { - "regenerator-runtime": "^0.14.0" - } + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.27.1.tgz", + "integrity": "sha512-1x3D2xEk2fRo3PAhwQwu5UubzgiVWSXTBfWpVd2Mx2AzRqJuDJCsgaDVZ7HB5iGzDW1Hl1sWN2mFyKjmR9uAog==" }, "@babel/template": { "version": "7.26.9", @@ -6924,9 +6918,6 @@ } } }, - "regenerator-runtime": { - "version": "0.14.0" - }, "resolve": { "version": "1.22.4", "requires": { diff --git a/src/frontend/src/components/Answer/Answer.tsx b/src/frontend/src/components/Answer/Answer.tsx index a542064c..01b8bd3f 100644 --- a/src/frontend/src/components/Answer/Answer.tsx +++ b/src/frontend/src/components/Answer/Answer.tsx @@ -1,4 +1,4 @@ -import { useMemo } from "react"; +import { useMemo, useState } from "react"; import { Stack, IconButton } from "@fluentui/react"; import DOMPurify from "dompurify"; @@ -29,6 +29,7 @@ export const Answer = ({ onFollowupQuestionClicked, showFollowupQuestions }: Props) => { + const [isReferencesCollapsed, setIsReferencesCollapsed] = useState(true); const followupQuestions = answer.context.followup_questions; const messageContent = answer.message.content; const parsedAnswer = useMemo(() => parseAnswerToHtml(messageContent, isStreaming, onCitationClicked), [answer]); @@ -60,22 +61,32 @@ export const Answer = ({ {!!parsedAnswer.citations.length && ( - References: + + setIsReferencesCollapsed(!isReferencesCollapsed)} + /> + References: + + + {!isReferencesCollapsed && (
    - {parsedAnswer.citations.map((rowId, ind) => { - const citation = answer.context.data_points[rowId]; - if (!citation) return null; - return ( -
  1. -

    {citation.name}

    -

    Brand: {citation.brand}

    -

    Price: {citation.price}

    -

    {citation.description}

    -
  2. - ); - })} + {parsedAnswer.citations.map((rowId, ind) => { + const citation = answer.context.data_points[rowId]; + if (!citation) return null; + return ( +
  3. +

    {citation.name}

    +

    Brand: {citation.brand}

    +

    Price: {citation.price}

    +

    {citation.description}

    +
  4. + ); + })}
- + )}
)} diff --git a/tests/conftest.py b/tests/conftest.py index f3800dd3..5fe67053 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -8,7 +8,6 @@ import pytest import pytest_asyncio from fastapi.testclient import TestClient -from freezegun import freeze_time from openai.types import CreateEmbeddingResponse, Embedding from openai.types.chat import ChatCompletion, ChatCompletionChunk from openai.types.chat.chat_completion import ( @@ -336,13 +335,6 @@ async def mock_acreate(*args, **kwargs): yield -@pytest.fixture(autouse=True) -def frozen_time(): - """Freeze time for all tests to ensure consistent timestamps""" - with freeze_time("2024-01-01 12:00:00"): - yield - - @pytest.fixture(scope="function") def mock_azure_credential(mock_session_env): """Mock the Azure credential for testing.""" diff --git a/tests/snapshots/test_api_routes/test_advanced_chat_flow/advanced_chat_flow_response.json b/tests/snapshots/test_api_routes/test_advanced_chat_flow/advanced_chat_flow_response.json index 240a638a..612be773 100644 --- a/tests/snapshots/test_api_routes/test_advanced_chat_flow/advanced_chat_flow_response.json +++ b/tests/snapshots/test_api_routes/test_advanced_chat_flow/advanced_chat_flow_response.json @@ -19,154 +19,45 @@ "title": "Prompt to generate search arguments", "description": [ { - "parts": [ - { - "content": "good options for climbing gear that can be used outside?", - "timestamp": "2025-05-07T19:02:46.977501Z", - "part_kind": "user-prompt" - } - ], - "instructions": null, - "kind": "request" + "content": "Your job is to find search results based off the user's question and past messages.\nYou have access to only these tools:\n1. **search_database**: This tool allows you to search a table for items based on a query.\n You can pass in a search query and optional filters.\nOnce you get the search results, you're done.\n" }, { - "parts": [ - { - "tool_name": "search_database", - "args": "{\"search_query\":\"climbing gear outside\"}", - "tool_call_id": "call_4HeBCmo2uioV6CyoePEGyZPc", - "part_kind": "tool-call" - } - ], - "model_name": "gpt-4o-mini-2024-07-18", - "timestamp": "2025-05-07T19:02:47Z", - "kind": "response" + "role": "user", + "content": "good options for climbing gear that can be used outside?" }, { - "parts": [ - { - "tool_name": "search_database", - "content": "Search results for climbing gear that can be used outside: ...", - "tool_call_id": "call_4HeBCmo2uioV6CyoePEGyZPc", - "timestamp": "2025-05-07T19:02:48.242408Z", - "part_kind": "tool-return" - } - ], - "instructions": null, - "kind": "request" + "id": "madeup", + "call_id": "call_abc123", + "name": "search_database", + "arguments": "{\"search_query\":\"climbing gear outside\"}", + "type": "function_call" }, { - "parts": [ - { - "content": "are there any shoes less than $50?", - "timestamp": "2025-05-07T19:02:46.977501Z", - "part_kind": "user-prompt" - } - ], - "instructions": null, - "kind": "request" + "id": "madeupoutput", + "call_id": "call_abc123", + "output": "Search results for climbing gear that can be used outside: ...", + "type": "function_call_output" }, { - "parts": [ - { - "tool_name": "search_database", - "args": "{\"search_query\":\"shoes\",\"price_filter\":{\"comparison_operator\":\"<\",\"value\":50}}", - "tool_call_id": "call_4HeBCmo2uioV6CyoePEGyZPc", - "part_kind": "tool-call" - } - ], - "model_name": "gpt-4o-mini-2024-07-18", - "timestamp": "2025-05-07T19:02:47Z", - "kind": "response" + "role": "user", + "content": "are there any shoes less than $50?" }, { - "parts": [ - { - "tool_name": "search_database", - "content": "Search results for shoes cheaper than 50: ...", - "tool_call_id": "call_4HeBCmo2uioV6CyoePEGyZPc", - "timestamp": "2025-05-07T19:02:48.242408Z", - "part_kind": "tool-return" - } - ], - "instructions": null, - "kind": "request" + "id": "madeup", + "call_id": "call_abc456", + "name": "search_database", + "arguments": "{\"search_query\":\"shoes\",\"price_filter\":{\"comparison_operator\":\"<\",\"value\":50}}", + "type": "function_call" }, { - "parts": [ - { - "content": "Find search results for user query: What is the capital of France?", - "timestamp": "2024-01-01T12:00:00Z", - "part_kind": "user-prompt" - } - ], - "instructions": null, - "kind": "request" + "id": "madeupoutput", + "call_id": "call_abc456", + "output": "Search results for shoes cheaper than 50: ...", + "type": "function_call_output" }, { - "parts": [ - { - "tool_name": "search_database", - "args": "{\"search_query\":\"climbing gear outside\"}", - "tool_call_id": "call_abc123", - "part_kind": "tool-call" - } - ], - "model_name": "test-model", - "timestamp": "1970-01-01T00:00:00Z", - "kind": "response" - }, - { - "parts": [ - { - "tool_name": "search_database", - "content": { - "query": "climbing gear outside", - "items": [ - { - "id": 1, - "type": "Footwear", - "brand": "Daybird", - "name": "Wanderer Black Hiking Boots", - "description": "Daybird's Wanderer Hiking Boots in sleek black are perfect for all your outdoor adventures. These boots are made with a waterproof leather upper and a durable rubber sole for superior traction. With their cushioned insole and padded collar, these boots will keep you comfortable all day long.", - "price": 109.99 - } - ], - "filters": [] - }, - "tool_call_id": "call_abc123", - "timestamp": "2024-01-01T12:00:00Z", - "part_kind": "tool-return" - } - ], - "instructions": null, - "kind": "request" - }, - { - "parts": [ - { - "tool_name": "final_result", - "args": "{\"query\": \"capital of France\", \"items\": [{\"id\": 1, \"type\": \"Footwear\", \"brand\": \"Daybird\", \"name\": \"Wanderer Black Hiking Boots\", \"description\": \"Daybird's Wanderer Hiking Boots in sleek black are perfect for all your outdoor adventures. These boots are made with a waterproof leather upper and a durable rubber sole for superior traction. With their cushioned insole and padded collar, these boots will keep you comfortable all day long.\", \"price\": 109.99}], \"filters\": []}", - "tool_call_id": "call_abc123final", - "part_kind": "tool-call" - } - ], - "model_name": "test-model", - "timestamp": "1970-01-01T00:00:00Z", - "kind": "response" - }, - { - "parts": [ - { - "tool_name": "final_result", - "content": "Final result processed.", - "tool_call_id": "call_abc123final", - "timestamp": "2024-01-01T12:00:00Z", - "part_kind": "tool-return" - } - ], - "instructions": null, - "kind": "request" + "role": "user", + "content": "Find search results for user query: What is the capital of France?" } ], "props": { @@ -176,7 +67,7 @@ }, { "title": "Search using generated search arguments", - "description": "capital of France", + "description": "climbing gear outside", "props": { "top": 1, "vector_search": true, @@ -202,32 +93,11 @@ "title": "Prompt to generate answer", "description": [ { - "parts": [ - { - "content": "Assistant helps customers with questions about products.\nRespond as if you are a salesperson helping a customer in a store. Do NOT respond with tables.\nAnswer ONLY with the product details listed in the products.\nIf there isn't enough information below, say you don't know.\nDo not generate answers that don't use the sources below.\nEach product has an ID in brackets followed by colon and the product details.\nAlways include the product ID for each product you use in the response.\nUse square brackets to reference the source, for example [52].\nDon't combine citations, list each product separately, for example [27][51].", - "timestamp": "2024-01-01T12:00:00Z", - "dynamic_ref": null, - "part_kind": "system-prompt" - }, - { - "content": "What is the capital of France?Sources:\n[1]:Name:Wanderer Black Hiking Boots Description:Daybird's Wanderer Hiking Boots in sleek black are perfect for all your outdoor adventures. These boots are made with a waterproof leather upper and a durable rubber sole for superior traction. With their cushioned insole and padded collar, these boots will keep you comfortable all day long. Price:109.99 Brand:Daybird Type:Footwear", - "timestamp": "2024-01-01T12:00:00Z", - "part_kind": "user-prompt" - } - ], - "instructions": null, - "kind": "request" + "content": "Assistant helps customers with questions about products.\nRespond as if you are a salesperson helping a customer in a store. Do NOT respond with tables.\nAnswer ONLY with the product details listed in the products.\nIf there isn't enough information below, say you don't know.\nDo not generate answers that don't use the sources below.\nEach product has an ID in brackets followed by colon and the product details.\nAlways include the product ID for each product you use in the response.\nUse square brackets to reference the source, for example [52].\nDon't combine citations, list each product separately, for example [27][51]." }, { - "parts": [ - { - "content": "The capital of France is Paris. [Benefit_Options-2.pdf].", - "part_kind": "text" - } - ], - "model_name": "test-model", - "timestamp": "1970-01-01T00:00:00Z", - "kind": "response" + "content": "What is the capital of France?Sources:\n[1]:Name:Wanderer Black Hiking Boots Description:Daybird's Wanderer Hiking Boots in sleek black are perfect for all your outdoor adventures. These boots are made with a waterproof leather upper and a durable rubber sole for superior traction. With their cushioned insole and padded collar, these boots will keep you comfortable all day long. Price:109.99 Brand:Daybird Type:Footwear", + "role": "user" } ], "props": { diff --git a/tests/snapshots/test_api_routes/test_advanced_chat_streaming_flow/advanced_chat_streaming_flow_response.jsonlines b/tests/snapshots/test_api_routes/test_advanced_chat_streaming_flow/advanced_chat_streaming_flow_response.jsonlines index e241106d..d29b85c4 100644 --- a/tests/snapshots/test_api_routes/test_advanced_chat_streaming_flow/advanced_chat_streaming_flow_response.jsonlines +++ b/tests/snapshots/test_api_routes/test_advanced_chat_streaming_flow/advanced_chat_streaming_flow_response.jsonlines @@ -1,2 +1,2 @@ -{"delta":null,"context":{"data_points":{"1":{"id":1,"type":"Footwear","brand":"Daybird","name":"Wanderer Black Hiking Boots","description":"Daybird's Wanderer Hiking Boots in sleek black are perfect for all your outdoor adventures. These boots are made with a waterproof leather upper and a durable rubber sole for superior traction. With their cushioned insole and padded collar, these boots will keep you comfortable all day long.","price":109.99}},"thoughts":[{"title":"Prompt to generate search arguments","description":[{"parts":[{"content":"good options for climbing gear that can be used outside?","timestamp":"2025-05-07T19:02:46.977501Z","part_kind":"user-prompt"}],"instructions":null,"kind":"request"},{"parts":[{"tool_name":"search_database","args":"{\"search_query\":\"climbing gear outside\"}","tool_call_id":"call_4HeBCmo2uioV6CyoePEGyZPc","part_kind":"tool-call"}],"model_name":"gpt-4o-mini-2024-07-18","timestamp":"2025-05-07T19:02:47Z","kind":"response"},{"parts":[{"tool_name":"search_database","content":"Search results for climbing gear that can be used outside: ...","tool_call_id":"call_4HeBCmo2uioV6CyoePEGyZPc","timestamp":"2025-05-07T19:02:48.242408Z","part_kind":"tool-return"}],"instructions":null,"kind":"request"},{"parts":[{"content":"are there any shoes less than $50?","timestamp":"2025-05-07T19:02:46.977501Z","part_kind":"user-prompt"}],"instructions":null,"kind":"request"},{"parts":[{"tool_name":"search_database","args":"{\"search_query\":\"shoes\",\"price_filter\":{\"comparison_operator\":\"<\",\"value\":50}}","tool_call_id":"call_4HeBCmo2uioV6CyoePEGyZPc","part_kind":"tool-call"}],"model_name":"gpt-4o-mini-2024-07-18","timestamp":"2025-05-07T19:02:47Z","kind":"response"},{"parts":[{"tool_name":"search_database","content":"Search results for shoes cheaper than 50: ...","tool_call_id":"call_4HeBCmo2uioV6CyoePEGyZPc","timestamp":"2025-05-07T19:02:48.242408Z","part_kind":"tool-return"}],"instructions":null,"kind":"request"},{"parts":[{"content":"Find search results for user query: What is the capital of France?","timestamp":"2024-01-01T12:00:00Z","part_kind":"user-prompt"}],"instructions":null,"kind":"request"},{"parts":[{"tool_name":"search_database","args":"{\"search_query\":\"climbing gear outside\"}","tool_call_id":"call_abc123","part_kind":"tool-call"}],"model_name":"test-model","timestamp":"1970-01-01T00:00:00Z","kind":"response"},{"parts":[{"tool_name":"search_database","content":{"query":"climbing gear outside","items":[{"id":1,"type":"Footwear","brand":"Daybird","name":"Wanderer Black Hiking Boots","description":"Daybird's Wanderer Hiking Boots in sleek black are perfect for all your outdoor adventures. These boots are made with a waterproof leather upper and a durable rubber sole for superior traction. With their cushioned insole and padded collar, these boots will keep you comfortable all day long.","price":109.99}],"filters":[]},"tool_call_id":"call_abc123","timestamp":"2024-01-01T12:00:00Z","part_kind":"tool-return"}],"instructions":null,"kind":"request"},{"parts":[{"tool_name":"final_result","args":"{\"query\": \"capital of France\", \"items\": [{\"id\": 1, \"type\": \"Footwear\", \"brand\": \"Daybird\", \"name\": \"Wanderer Black Hiking Boots\", \"description\": \"Daybird's Wanderer Hiking Boots in sleek black are perfect for all your outdoor adventures. These boots are made with a waterproof leather upper and a durable rubber sole for superior traction. With their cushioned insole and padded collar, these boots will keep you comfortable all day long.\", \"price\": 109.99}], \"filters\": []}","tool_call_id":"call_abc123final","part_kind":"tool-call"}],"model_name":"test-model","timestamp":"1970-01-01T00:00:00Z","kind":"response"},{"parts":[{"tool_name":"final_result","content":"Final result processed.","tool_call_id":"call_abc123final","timestamp":"2024-01-01T12:00:00Z","part_kind":"tool-return"}],"instructions":null,"kind":"request"}],"props":{"model":"gpt-4o-mini","deployment":"gpt-4o-mini"}},{"title":"Search using generated search arguments","description":"capital of France","props":{"top":1,"vector_search":true,"text_search":true,"filters":[]}},{"title":"Search results","description":[{"id":1,"type":"Footwear","brand":"Daybird","name":"Wanderer Black Hiking Boots","description":"Daybird's Wanderer Hiking Boots in sleek black are perfect for all your outdoor adventures. These boots are made with a waterproof leather upper and a durable rubber sole for superior traction. With their cushioned insole and padded collar, these boots will keep you comfortable all day long.","price":109.99}],"props":{}},{"title":"Prompt to generate answer","description":[{"parts":[{"content":"Assistant helps customers with questions about products.\nRespond as if you are a salesperson helping a customer in a store. Do NOT respond with tables.\nAnswer ONLY with the product details listed in the products.\nIf there isn't enough information below, say you don't know.\nDo not generate answers that don't use the sources below.\nEach product has an ID in brackets followed by colon and the product details.\nAlways include the product ID for each product you use in the response.\nUse square brackets to reference the source, for example [52].\nDon't combine citations, list each product separately, for example [27][51].","timestamp":"2024-01-01T12:00:00Z","dynamic_ref":null,"part_kind":"system-prompt"},{"content":"What is the capital of France?Sources:\n[1]:Name:Wanderer Black Hiking Boots Description:Daybird's Wanderer Hiking Boots in sleek black are perfect for all your outdoor adventures. These boots are made with a waterproof leather upper and a durable rubber sole for superior traction. With their cushioned insole and padded collar, these boots will keep you comfortable all day long. Price:109.99 Brand:Daybird Type:Footwear","timestamp":"2024-01-01T12:00:00Z","part_kind":"user-prompt"}],"instructions":null,"kind":"request"}],"props":{"model":"gpt-4o-mini","deployment":"gpt-4o-mini"}}],"followup_questions":null},"sessionState":null} +{"delta":null,"context":{"data_points":{"1":{"id":1,"type":"Footwear","brand":"Daybird","name":"Wanderer Black Hiking Boots","description":"Daybird's Wanderer Hiking Boots in sleek black are perfect for all your outdoor adventures. These boots are made with a waterproof leather upper and a durable rubber sole for superior traction. With their cushioned insole and padded collar, these boots will keep you comfortable all day long.","price":109.99}},"thoughts":[{"title":"Prompt to generate search arguments","description":[{"content":"Your job is to find search results based off the user's question and past messages.\nYou have access to only these tools:\n1. **search_database**: This tool allows you to search a table for items based on a query.\n You can pass in a search query and optional filters.\nOnce you get the search results, you're done.\n"},{"role":"user","content":"good options for climbing gear that can be used outside?"},{"id":"madeup","call_id":"call_abc123","name":"search_database","arguments":"{\"search_query\":\"climbing gear outside\"}","type":"function_call"},{"id":"madeupoutput","call_id":"call_abc123","output":"Search results for climbing gear that can be used outside: ...","type":"function_call_output"},{"role":"user","content":"are there any shoes less than $50?"},{"id":"madeup","call_id":"call_abc456","name":"search_database","arguments":"{\"search_query\":\"shoes\",\"price_filter\":{\"comparison_operator\":\"<\",\"value\":50}}","type":"function_call"},{"id":"madeupoutput","call_id":"call_abc456","output":"Search results for shoes cheaper than 50: ...","type":"function_call_output"},{"role":"user","content":"Find search results for user query: What is the capital of France?"}],"props":{"model":"gpt-4o-mini","deployment":"gpt-4o-mini"}},{"title":"Search using generated search arguments","description":"climbing gear outside","props":{"top":1,"vector_search":true,"text_search":true,"filters":[]}},{"title":"Search results","description":[{"id":1,"type":"Footwear","brand":"Daybird","name":"Wanderer Black Hiking Boots","description":"Daybird's Wanderer Hiking Boots in sleek black are perfect for all your outdoor adventures. These boots are made with a waterproof leather upper and a durable rubber sole for superior traction. With their cushioned insole and padded collar, these boots will keep you comfortable all day long.","price":109.99}],"props":{}},{"title":"Prompt to generate answer","description":[{"content":"Assistant helps customers with questions about products.\nRespond as if you are a salesperson helping a customer in a store. Do NOT respond with tables.\nAnswer ONLY with the product details listed in the products.\nIf there isn't enough information below, say you don't know.\nDo not generate answers that don't use the sources below.\nEach product has an ID in brackets followed by colon and the product details.\nAlways include the product ID for each product you use in the response.\nUse square brackets to reference the source, for example [52].\nDon't combine citations, list each product separately, for example [27][51]."},{"content":"What is the capital of France?Sources:\n[1]:Name:Wanderer Black Hiking Boots Description:Daybird's Wanderer Hiking Boots in sleek black are perfect for all your outdoor adventures. These boots are made with a waterproof leather upper and a durable rubber sole for superior traction. With their cushioned insole and padded collar, these boots will keep you comfortable all day long. Price:109.99 Brand:Daybird Type:Footwear","role":"user"}],"props":{"model":"gpt-4o-mini","deployment":"gpt-4o-mini"}}],"followup_questions":null},"sessionState":null} {"delta":{"content":"The capital of France is Paris. [Benefit_Options-2.pdf].","role":"assistant"},"context":null,"sessionState":null} diff --git a/tests/snapshots/test_api_routes/test_simple_chat_flow/simple_chat_flow_response.json b/tests/snapshots/test_api_routes/test_simple_chat_flow/simple_chat_flow_response.json index 337a67d3..e311917b 100644 --- a/tests/snapshots/test_api_routes/test_simple_chat_flow/simple_chat_flow_response.json +++ b/tests/snapshots/test_api_routes/test_simple_chat_flow/simple_chat_flow_response.json @@ -42,32 +42,11 @@ "title": "Prompt to generate answer", "description": [ { - "parts": [ - { - "content": "Assistant helps customers with questions about products.\nRespond as if you are a salesperson helping a customer in a store. Do NOT respond with tables.\nAnswer ONLY with the product details listed in the products.\nIf there isn't enough information below, say you don't know.\nDo not generate answers that don't use the sources below.\nEach product has an ID in brackets followed by colon and the product details.\nAlways include the product ID for each product you use in the response.\nUse square brackets to reference the source, for example [52].\nDon't combine citations, list each product separately, for example [27][51].", - "timestamp": "2024-01-01T12:00:00Z", - "dynamic_ref": null, - "part_kind": "system-prompt" - }, - { - "content": "What is the capital of France?Sources:\n[1]:Name:Wanderer Black Hiking Boots Description:Daybird's Wanderer Hiking Boots in sleek black are perfect for all your outdoor adventures. These boots are made with a waterproof leather upper and a durable rubber sole for superior traction. With their cushioned insole and padded collar, these boots will keep you comfortable all day long. Price:109.99 Brand:Daybird Type:Footwear", - "timestamp": "2024-01-01T12:00:00Z", - "part_kind": "user-prompt" - } - ], - "instructions": null, - "kind": "request" + "content": "Assistant helps customers with questions about products.\nRespond as if you are a salesperson helping a customer in a store. Do NOT respond with tables.\nAnswer ONLY with the product details listed in the products.\nIf there isn't enough information below, say you don't know.\nDo not generate answers that don't use the sources below.\nEach product has an ID in brackets followed by colon and the product details.\nAlways include the product ID for each product you use in the response.\nUse square brackets to reference the source, for example [52].\nDon't combine citations, list each product separately, for example [27][51]." }, { - "parts": [ - { - "content": "The capital of France is Paris. [Benefit_Options-2.pdf].", - "part_kind": "text" - } - ], - "model_name": "test-model", - "timestamp": "1970-01-01T00:00:00Z", - "kind": "response" + "content": "What is the capital of France?Sources:\n[1]:Name:Wanderer Black Hiking Boots Description:Daybird's Wanderer Hiking Boots in sleek black are perfect for all your outdoor adventures. These boots are made with a waterproof leather upper and a durable rubber sole for superior traction. With their cushioned insole and padded collar, these boots will keep you comfortable all day long. Price:109.99 Brand:Daybird Type:Footwear", + "role": "user" } ], "props": { diff --git a/tests/snapshots/test_api_routes/test_simple_chat_flow_message_history/simple_chat_flow_message_history_response.json b/tests/snapshots/test_api_routes/test_simple_chat_flow_message_history/simple_chat_flow_message_history_response.json index 6bc9d4ec..d0456cd7 100644 --- a/tests/snapshots/test_api_routes/test_simple_chat_flow_message_history/simple_chat_flow_message_history_response.json +++ b/tests/snapshots/test_api_routes/test_simple_chat_flow_message_history/simple_chat_flow_message_history_response.json @@ -42,48 +42,19 @@ "title": "Prompt to generate answer", "description": [ { - "parts": [ - { - "content": "What is the capital of France?", - "timestamp": "2024-01-01T12:00:00Z", - "part_kind": "user-prompt" - } - ], - "instructions": null, - "kind": "request" + "content": "Assistant helps customers with questions about products.\nRespond as if you are a salesperson helping a customer in a store. Do NOT respond with tables.\nAnswer ONLY with the product details listed in the products.\nIf there isn't enough information below, say you don't know.\nDo not generate answers that don't use the sources below.\nEach product has an ID in brackets followed by colon and the product details.\nAlways include the product ID for each product you use in the response.\nUse square brackets to reference the source, for example [52].\nDon't combine citations, list each product separately, for example [27][51]." }, { - "parts": [ - { - "content": "The capital of France is Paris.", - "part_kind": "text" - } - ], - "model_name": null, - "timestamp": "2024-01-01T12:00:00Z", - "kind": "response" + "content": "What is the capital of France?", + "role": "user" }, { - "parts": [ - { - "content": "What is the capital of France?Sources:\n[1]:Name:Wanderer Black Hiking Boots Description:Daybird's Wanderer Hiking Boots in sleek black are perfect for all your outdoor adventures. These boots are made with a waterproof leather upper and a durable rubber sole for superior traction. With their cushioned insole and padded collar, these boots will keep you comfortable all day long. Price:109.99 Brand:Daybird Type:Footwear", - "timestamp": "2024-01-01T12:00:00Z", - "part_kind": "user-prompt" - } - ], - "instructions": null, - "kind": "request" + "content": "The capital of France is Paris.", + "role": "assistant" }, { - "parts": [ - { - "content": "The capital of France is Paris. [Benefit_Options-2.pdf].", - "part_kind": "text" - } - ], - "model_name": "test-model", - "timestamp": "1970-01-01T00:00:00Z", - "kind": "response" + "content": "What is the capital of France?Sources:\n[1]:Name:Wanderer Black Hiking Boots Description:Daybird's Wanderer Hiking Boots in sleek black are perfect for all your outdoor adventures. These boots are made with a waterproof leather upper and a durable rubber sole for superior traction. With their cushioned insole and padded collar, these boots will keep you comfortable all day long. Price:109.99 Brand:Daybird Type:Footwear", + "role": "user" } ], "props": { diff --git a/tests/snapshots/test_api_routes/test_simple_chat_streaming_flow/simple_chat_streaming_flow_response.jsonlines b/tests/snapshots/test_api_routes/test_simple_chat_streaming_flow/simple_chat_streaming_flow_response.jsonlines index 28bfd00f..65d3ae5b 100644 --- a/tests/snapshots/test_api_routes/test_simple_chat_streaming_flow/simple_chat_streaming_flow_response.jsonlines +++ b/tests/snapshots/test_api_routes/test_simple_chat_streaming_flow/simple_chat_streaming_flow_response.jsonlines @@ -1,2 +1,2 @@ -{"delta":null,"context":{"data_points":{"1":{"id":1,"type":"Footwear","brand":"Daybird","name":"Wanderer Black Hiking Boots","description":"Daybird's Wanderer Hiking Boots in sleek black are perfect for all your outdoor adventures. These boots are made with a waterproof leather upper and a durable rubber sole for superior traction. With their cushioned insole and padded collar, these boots will keep you comfortable all day long.","price":109.99}},"thoughts":[{"title":"Search query for database","description":"What is the capital of France?","props":{"top":1,"vector_search":true,"text_search":true}},{"title":"Search results","description":[{"id":1,"type":"Footwear","brand":"Daybird","name":"Wanderer Black Hiking Boots","description":"Daybird's Wanderer Hiking Boots in sleek black are perfect for all your outdoor adventures. These boots are made with a waterproof leather upper and a durable rubber sole for superior traction. With their cushioned insole and padded collar, these boots will keep you comfortable all day long.","price":109.99}],"props":{}},{"title":"Prompt to generate answer","description":[{"parts":[{"content":"Assistant helps customers with questions about products.\nRespond as if you are a salesperson helping a customer in a store. Do NOT respond with tables.\nAnswer ONLY with the product details listed in the products.\nIf there isn't enough information below, say you don't know.\nDo not generate answers that don't use the sources below.\nEach product has an ID in brackets followed by colon and the product details.\nAlways include the product ID for each product you use in the response.\nUse square brackets to reference the source, for example [52].\nDon't combine citations, list each product separately, for example [27][51].","timestamp":"2024-01-01T12:00:00Z","dynamic_ref":null,"part_kind":"system-prompt"},{"content":"What is the capital of France?Sources:\n[1]:Name:Wanderer Black Hiking Boots Description:Daybird's Wanderer Hiking Boots in sleek black are perfect for all your outdoor adventures. These boots are made with a waterproof leather upper and a durable rubber sole for superior traction. With their cushioned insole and padded collar, these boots will keep you comfortable all day long. Price:109.99 Brand:Daybird Type:Footwear","timestamp":"2024-01-01T12:00:00Z","part_kind":"user-prompt"}],"instructions":null,"kind":"request"}],"props":{"model":"gpt-4o-mini","deployment":"gpt-4o-mini"}}],"followup_questions":null},"sessionState":null} +{"delta":null,"context":{"data_points":{"1":{"id":1,"type":"Footwear","brand":"Daybird","name":"Wanderer Black Hiking Boots","description":"Daybird's Wanderer Hiking Boots in sleek black are perfect for all your outdoor adventures. These boots are made with a waterproof leather upper and a durable rubber sole for superior traction. With their cushioned insole and padded collar, these boots will keep you comfortable all day long.","price":109.99}},"thoughts":[{"title":"Search query for database","description":"What is the capital of France?","props":{"top":1,"vector_search":true,"text_search":true}},{"title":"Search results","description":[{"id":1,"type":"Footwear","brand":"Daybird","name":"Wanderer Black Hiking Boots","description":"Daybird's Wanderer Hiking Boots in sleek black are perfect for all your outdoor adventures. These boots are made with a waterproof leather upper and a durable rubber sole for superior traction. With their cushioned insole and padded collar, these boots will keep you comfortable all day long.","price":109.99}],"props":{}},{"title":"Prompt to generate answer","description":[{"content":"Assistant helps customers with questions about products.\nRespond as if you are a salesperson helping a customer in a store. Do NOT respond with tables.\nAnswer ONLY with the product details listed in the products.\nIf there isn't enough information below, say you don't know.\nDo not generate answers that don't use the sources below.\nEach product has an ID in brackets followed by colon and the product details.\nAlways include the product ID for each product you use in the response.\nUse square brackets to reference the source, for example [52].\nDon't combine citations, list each product separately, for example [27][51]."},{"content":"What is the capital of France?Sources:\n[1]:Name:Wanderer Black Hiking Boots Description:Daybird's Wanderer Hiking Boots in sleek black are perfect for all your outdoor adventures. These boots are made with a waterproof leather upper and a durable rubber sole for superior traction. With their cushioned insole and padded collar, these boots will keep you comfortable all day long. Price:109.99 Brand:Daybird Type:Footwear","role":"user"}],"props":{"model":"gpt-4o-mini","deployment":"gpt-4o-mini"}}],"followup_questions":null},"sessionState":null} {"delta":{"content":"The capital of France is Paris. [Benefit_Options-2.pdf].","role":"assistant"},"context":null,"sessionState":null} diff --git a/tests/test_openai_clients.py b/tests/test_openai_clients.py index ecac8759..47caba26 100644 --- a/tests/test_openai_clients.py +++ b/tests/test_openai_clients.py @@ -1,5 +1,6 @@ import pytest +from fastapi_app.dependencies import common_parameters from fastapi_app.openai_clients import create_openai_chat_client, create_openai_embed_client from tests.data import test_data @@ -22,3 +23,44 @@ async def test_create_openai_chat_client(mock_azure_credential, mock_openai_chat model="gpt-4o-mini", messages=[{"content": "test", "role": "user"}] ) assert response.choices[0].message.content == "The capital of France is Paris. [Benefit_Options-2.pdf]." + + +@pytest.mark.asyncio +async def test_github_models_configuration(monkeypatch): + """Test that GitHub Models uses the correct URLs and model names.""" + # Set up environment for GitHub Models + monkeypatch.setenv("OPENAI_CHAT_HOST", "github") + monkeypatch.setenv("OPENAI_EMBED_HOST", "github") + monkeypatch.setenv("GITHUB_TOKEN", "fake-token") + # Don't set GITHUB_MODEL to test defaults + + # Test chat client configuration + chat_client = await create_openai_chat_client(None) + assert str(chat_client.base_url).rstrip("/") == "https://models.github.ai/inference" + assert chat_client.api_key == "fake-token" + + # Test embed client configuration + embed_client = await create_openai_embed_client(None) + assert str(embed_client.base_url).rstrip("/") == "https://models.github.ai/inference" + assert embed_client.api_key == "fake-token" + + # Test that dependencies use correct defaults + context = await common_parameters() + assert context.openai_chat_model == "openai/gpt-4o" + assert context.openai_embed_model == "openai/text-embedding-3-large" + + +@pytest.mark.asyncio +async def test_github_models_with_custom_values(monkeypatch): + """Test that GitHub Models respects custom environment values.""" + # Set up environment for GitHub Models with custom values + monkeypatch.setenv("OPENAI_CHAT_HOST", "github") + monkeypatch.setenv("OPENAI_EMBED_HOST", "github") + monkeypatch.setenv("GITHUB_TOKEN", "fake-token") + monkeypatch.setenv("GITHUB_MODEL", "openai/gpt-4") + monkeypatch.setenv("GITHUB_EMBED_MODEL", "openai/text-embedding-ada-002") + + # Test that dependencies use custom values + context = await common_parameters() + assert context.openai_chat_model == "openai/gpt-4" + assert context.openai_embed_model == "openai/text-embedding-ada-002" pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy