Skip to content

About

.NET 10 application with an interactive Blazor Server frontend and an isolated Azure Functions backend for storing texts and embeddings in PostgreSQL with the vector extension, and searching for the five closest texts using cosine distance. Embeddings are generated by the text-embedding-3-large deployment in Azure OpenAI (Microsoft Foundry).

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

DB Semantic Search

.NET 10 application with an interactive Blazor Server frontend and an isolated Azure Functions backend for storing texts and embeddings in PostgreSQL with the vector extension, and searching for the five closest texts using cosine distance. Embeddings are generated by the text-embedding-3-large deployment in Azure OpenAI (Microsoft Foundry). User authentication is not required.

Structure

Path Responsibility
src/DBSemanticSearch.Core Domain model, database/model interfaces, validation, and application service
src/DBSemanticSearch.Contracts REST DTOs and JSON batch schema
src/DBSemanticSearch.Client REST client used by Blazor
src/DBSemanticSearch.Foundry Azure OpenAI (Microsoft Foundry) configuration and adapter
src/DBSemanticSearch.Postgres PostgreSQL/pgvector repository
src/DBSemanticSearch.Api Azure Functions HTTP endpoints
src/DBSemanticSearch.Web Blazor pages for entering text, uploading JSON, and searching
infra Azure Bicep resources and AZD parameters
tests Unit tests for services, batches, and the client

Architecture

flowchart LR
  browser[User's browser]

  subgraph Azure[Azure]
    web[Blazor Server<br/>Windows App Service]

    subgraph backend[Backend]
      api[Azure Functions<br/>.NET isolated]
      core[Core<br/>TextService]
      foundryAdapter[Foundry embedding adapter]
      postgresAdapter[PostgreSQL repository]
    end

    foundry[Microsoft Foundry<br/>text-embedding-3-large]
    database[Azure Database for PostgreSQL<br/>pgvector]
    insights[Application Insights]
  end

  browser <-->|HTTPS and interactive circuit| web
  web -->|Server-side HTTPS<br/>Function key| api
  api --> core
  core -->|Generate embeddings| foundryAdapter
  foundryAdapter -->|Embedding request| foundry
  core -->|Store texts and search vectors| postgresAdapter
  postgresAdapter --> database
  api -.->|Telemetry| insights
  web -.->|Telemetry| insights
Loading

The browser communicates only with the Blazor Server frontend. The frontend calls the Functions API from the server, keeping the Function key out of browser assets and requests. The API uses Foundry to generate embeddings and PostgreSQL with pgvector to store and search texts.

File format and API

The JSON file must be an object with a texts array containing 1–100 items. Texts cannot be empty or consist only of whitespace and cannot exceed 10,000 characters; the maximum file/request size is 1 MiB.

{
  "texts": ["The first text to index", "Another text to index"]
}

The batch processes each item in the supplied order. An invalid item or a model/database error does not stop subsequent items; inserted reports the number saved and each items entry contains index (zero-based), document, or error. A valid document is persisted immediately: retrying a batch after an error may create duplicates.

Method Path Body Response
POST /api/texts {"text":"..."} 201 with document {id,text,createdAt}
POST /api/texts/batch {"texts":["...", "..."]} 200 with {inserted,items:[{index,document,error}]}
POST /api/search {"text":"..."} 200 with {results:[{document,distance}]} (maximum 5)
DELETE /api/texts None 204 with no body; deletes all stored texts and embeddings

Format/validation problems return 400 with { "error": "..." }; requests over 1 MiB return 413. A lower cosine distance indicates greater similarity. For small collections the query performs an exact search without an approximate index.

On the Texts page, Delete all texts opens a confirmation dialog before deleting every stored document and embedding. The operation is irreversible, preserves the database schema, and does not call the embedding model. Cancelling the dialog sends no deletion request. As the application has no user authentication, anyone who can access the frontend can perform this operation.

Local execution

You need .NET SDK 10, Azure Functions Core Tools v4, PostgreSQL with pgvector, Azurite for local storage, Azure CLI, and a text-embedding-3-large deployment in Microsoft Foundry. The local PostgreSQL user must be able to run CREATE EXTENSION vector and create tables; create the semantic_search database first. Sign in to Azure with az login and assign your user the Cognitive Services OpenAI User role on the model resource. Do not put secrets in tracked files.

  1. Copy src/DBSemanticSearch.Api/local.settings.example.json to src/DBSemanticSearch.Api/local.settings.json and configure the PostgreSQL connection string, the HTTPS OpenAI endpoint, and the deployment name. EMBEDDING_DIMENSIONS must match the actual embedding size (3072 for the default deployment) and remains fixed for the existing table. Instead of a connection string, the API accepts DB_HOST, DB_NAME, DB_USER, DB_AUTH_MODE, and, only in Password mode, DB_PASSWORD. DefaultAzureCredential can use the identity from az login locally; all separate connections require TLS with host verification.
  2. Start PostgreSQL and Azurite; start the API from its directory with func start. API calls originate from the Blazor server, so browser CORS configuration is not needed.
  3. From another shell, run dotnet run --project src\DBSemanticSearch.Web --launch-profile http, then open http://localhost:5207. The src/DBSemanticSearch.Web/appsettings.Development.json file, at the project root and not in wwwroot, configures ApiBaseUrl as http://localhost:7071/. Azure Functions Core Tools does not enforce HTTP authorization levels locally, so a local function key is not needed. For other local APIs, set ApiBaseUrl in the server configuration; do not put FunctionKey in tracked files.
  4. Run the tests with dotnet test src/DBSemanticSearch.sln. The API creates the extension and table on the first request, verifying that the column dimension matches the configured model.

Azure deployment

See Prerequisites for the tools, Azure permissions, region and model availability, AZD environment configuration, and psql setup required before running azd up.

infra/main.bicep orchestrates separate Bicep modules for the frontend, backend, database, Foundry, and monitoring. The Blazor Server frontend runs as an ASP.NET Core application on Windows App Service, with WebSockets enabled for interactive circuits; the browser communicates with the website, not directly with Functions. Bicep configures ApiBaseUrl and FunctionKey in App Service settings: the server reads them at runtime and sends the key in requests to Functions, without copying it into public assets. Both settings are required in Azure; locally, the key may be omitted. Azure HTTP Function endpoints require a function key. For multiple App Service instances, plan for session affinity and Blazor circuit management.

Before deployment, run dotnet test src/DBSemanticSearch.sln and az bicep build --file infra/main.bicep; with an AZD environment selected, you can run azd package without modifying Azure resources. In the web package, verify that wwwroot contains no appsettings*.json, function key, or WebAssembly bundle: ASP.NET Core configuration at the package root is not served as a static asset. After all services are deployed, the AZD postdeploy hook reads the Function host key and stores it in the App Service FunctionKey setting; the key is not emitted by Bicep or logged. After deployment, verify the /, /texts, and /search pages, WebSocket circuit reconnection, JSON upload, and a search; browser network requests must not show direct calls to the Function App or the key.

The Foundry module creates a Microsoft Foundry (AIServices) resource with a system-assigned managed identity, a dedicated DB Semantic Search project, and a GlobalStandard deployment (default capacity 10K TPM) of text-embedding-3-large, available in the project. Identity on the account is required to create projects. Deployments are child resources of the Foundry account in the ARM hierarchy, while the project is a separate child resource of the same account. The Function App has a system-assigned managed identity with the Cognitive Services OpenAI User role on the Foundry resource and receives EMBEDDING_ENDPOINT, EMBEDDING_DEPLOYMENT, EMBEDDING_DIMENSIONS=3072, and EMBEDDING_AUTH_MODE=ManagedIdentity. The AZURE_FOUNDRY_PROJECT_ID and AZURE_FOUNDRY_PROJECT_NAME outputs identify the created project.

Application Insights is a single workspace-based instance (appi-api-*) shared through AZURE_APPINSIGHTS_CONNECTION_STRING; the Function App uses it to send telemetry. The frontend can use the same connection string if browser instrumentation is added. Foundry and PostgreSQL do not automatically send telemetry to Application Insights: their platform logs require Diagnostic Settings targeting the Log Analytics workspace.

After completing the prerequisites and selecting the configured AZD environment, deploy with azd up.

The server uses Microsoft Entra ID exclusively: no PostgreSQL password is created. The postprovision hook waits for the server to be ready, configures the Entra administrator with a separate, repeatable Bicep deployment, and registers the Function identity as a PostgreSQL principal (pgaadauth_create_principal_with_oid, plus USAGE, CREATE on schema public of semantic_search). During registration it adds a temporary firewall rule for this machine's public IP and removes it at the end.

The first deployment may take several minutes while identities and role assignments propagate. The public PostgreSQL server configuration allows connections from Azure services (0.0.0.0): for exposed or regulated environments, replace it with a private networking architecture. The function key stays on the server, but it does not authenticate users or make the Functions API private. If the previous WebAssembly version published the key, rotate it after migration while coordinating any other consumers; the host key configured here authorizes all HTTP Functions in the app. Dedicated measures, such as Microsoft Entra/App Service Authentication or Azure API Management, are required to control user access or limit API exposure.

No PostgreSQL or Foundry credentials are configured in the app: the API uses DB_AUTH_MODE=ManagedIdentity, EMBEDDING_AUTH_MODE=ManagedIdentity, and its own system-assigned managed identity. Local secrets remain outside the repository.

Authentication to Foundry

EMBEDDING_AUTH_MODE selects the credential used by the embedding service:

Value Behavior
DefaultAzureCredential (default) Azure credential chain: managed identity in Azure, az login/Visual Studio locally
ManagedIdentity Managed identity only; system-assigned, or user-assigned when EMBEDDING_MANAGED_IDENTITY_CLIENT_ID is set
ApiKey Resource key, read from EMBEDDING_API_KEY (required in this mode)

With ManagedIdentity and DefaultAzureCredential, the identity must have the Cognitive Services OpenAI User role on the resource. Never put the API key in tracked files: in Azure, store it in Key Vault and reference it from the Function settings.

About

.NET 10 application with an interactive Blazor Server frontend and an isolated Azure Functions backend for storing texts and embeddings in PostgreSQL with the vector extension, and searching for the five closest texts using cosine distance. Embeddings are generated by the text-embedding-3-large deployment in Azure OpenAI (Microsoft Foundry).

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Used by

Contributors

Languages