CosmosAIGraph
repository·main·Indexed 41 days ago
https://github.com/azurecosmosdb/cosmosaigraphAn implementation of the OmniRAG pattern that integrates Azure Cosmos DB's vector and hybrid search capabilities with Apache Jena's graph database. It provides a multi-source, intent-aware retrieval system for AI applications using a technology stack including Python, FastAPI, Azure OpenAI, semantic-kernel, and SPARQL 1.1.
What's inside CosmosAIGraph
- CosmosAIGraph is an AI-powered implementation of the OmniRAG pattern. It combines Azure Cosmos DB (utilizing DiskANN for Vector/Hybrid Search) with an Apache Jena in-memory graph database to provide advanced retrieval capabilities for Generative AI applications.
Overview of CosmosAIGraph (caig) Architecture
mainCosmosAIGraph (caig) is a solution composed of two primary microservices:
- web: The user-facing microservice providing an HTML-based UI and a RESTful API.
- graph: The graph microservice utilizing an in-memory Apache Jena graph.
These services are located in the
web_appandgraph_appdirectories of the repository and are packaged as Docker containers namedcaig_webandcaig_graphrespectively.Understand the Python codebase structure in impl\app
mainThe Python implementation is located in the
impl\appdirectory. Key subdirectories include:src/models: Pydantic models for request/response payloads (webservice_models.py) and internal data structures (internal_models.py).src/services: Business logic implementation (e.g.,ConfigService,AiService,DBService).src/util: Utility modules for filesystem access, prompt optimization, and SPARQL/OWL formatting.ontologies: OWL schema files (*.owl).rdf: RDF graph data files (*.nt).sparql: SPARQL query statements and Jinja2 templates.templates&views: Jinja2 templates for web and non-web use.tests: Unit tests usingpytest.docker: Dockerfiles anddocker-compose.ymlfiles.
What is cleared during a session reset
mainA session reset via the brand link clears data in three layers:
Client-side (Browser)
- Local Storage: All
localStoragedata is wiped to remove client-side session state. - Visual State: The UI provides feedback by showing "Clearing Session..." during the process.
Server-side (Backend)
- FastAPI Session: The server session is cleared, removing
conversation_idand other session variables. - Database: The active conversation document is deleted from the Cosmos DB NoSQL container.
- Temporary Files: Files in the
tmp/directory associated with the conversation are removed:tmp/conv_{conversation_id}.jsontmp/ai_conv_{conversation_id}.json
- Local Storage: All
What is the OmniRAG pattern?
mainThe OmniRAG pattern is an advanced Retrieval Augmented Generation pattern designed to maximize result relevancy by detecting user intent and intelligently routing requests to multiple data sources.
Core tenets include:
- Omni-source with data virtualization: Uses all available data sources in their original formats, minimizing movement and transformation.
- Knowledge graph: Uses entities and relationships to allow AI to reason over structured data alongside original data.
- User intent detection: Uses AI to automatically route queries to the appropriate data source.
- Runtime NL2Query conversion: Converts natural language user queries into the specific query language of the target source (e.g., SPARQL, SQL) using utterance analysis or AI.
- Session analytics: Enables fine-tuning of the 'golden dataset' (questions + intent) and can be used for semantic cache generation.
Use Apache Jena Fuseki as an external graph backend
mainBy default, CosmosAIGraph uses an in-process, in-memory Jena model. You can switch to an external Apache Jena Fuseki triple store by setting the
CAIG_GRAPH_BACKENDenvironment variable tofuseki.How it works
- Model Assembly: At startup,
AppGraphBuilderassembles the RDF model (ontology + triples from Cosmos DB/RDF/JSON). - Upload: If
CAIG_GRAPH_BACKEND=fusekiis set, thegraph_appconnects to the Fuseki dataset atCAIG_FUSEKI_DATASET_URLand uploads the model via the SPARQL Graph Store Protocol. - Querying: Subsequent requests to
/sparql_query,/sparql_update, and/add_documentsare served by Fuseki via SPARQL 1.1. - Performance Optimization: To prevent an N+1 HTTP request storm during
/sparql_bom_querytraversals, thegraph_appfetches a single local snapshot of the Fuseki dataset and runs the traversal in-process.
export CAIG_GRAPH_BACKEND=fuseki- Model Assembly: At startup,
Model data for in-memory graph construction
mainCosmosAIGraph does not require a pre-defined schema in Cosmos DB. The graph is constructed in-memory within the Apache Jena process by ingesting JSON documents from Cosmos DB during initialization.
To facilitate graph construction, you should include attributes in your JSON documents that represent relationships (edges). You can use a generic
edgesattribute containing a list of outgoing relationships, or use specific field names that the ingestion logic can map to RDF triples.In the reference implementation for Python libraries, the following fields are used to build the graph:
developers: A list of developer contact identifiers.dependency_ids: A list of identifiers representing dependencies (e.g.,pypi_<libname>).
{ "developers": [ "contact@palletsprojects.com" ], "dependency_ids": [ "pypi_asgiref", "pypi_blinker", "pypi_click", "pypi_importlib_metadata", "pypi_itsdangerous", "pypi_jinja2", "pypi_python_dotenv", "pypi_werkzeug" ] }Configure CosmosAIGraph using environment variables
mainThe application uses
ConfigServiceto manage configuration via environment variables. This approach is optimized for containerized deployments like Azure Container Apps (ACA) or Azure Kubernetes Service (AKS).All application environment variables begin with the prefix
CAIG_.To use a
.envfile for local development, the project utilizes thepython-dotenvlibrary. Note: Do not commit.envfiles to source control as they may contain secrets.Define endpoint schemas using Pydantic models
mainTo enable automatic OpenAPI/Swagger documentation in CosmosAIGraph, define your endpoint request and response bodies using Pydantic models. This ensures that the generated documentation accurately reflects the data structures expected and returned by your microservices.Apply Custom Rules to NL2SPARQL and OmniRAG Chat
mainCustom rules are dynamically injected into AI prompts to guide SPARQL generation. However, they only apply under specific conditions:
NL2SPARQL Console
When you submit a natural language query in the NL2SPARQL console, any rules stored in
sessionStorageundersparql_custom_rulesare automatically loaded into a hidden field and sent to the backend. The resulting SPARQL will respect these domain-specific instructions.OmniRAG Chat
Custom rules are applied in the OmniRAG Chat interface only when the "graph" RAG strategy is selected.
- If you use the "graph" strategy, the rules are injected into the prompt.
- If you use "DB" or "Vector" strategies, the rules are not applied.
CosmosAIGraph Technology Stack
mainThe solution is built using the following technologies:
- Python3: The primary programming language.
- FastAPI: The framework used for web and HTTP services.
- Azure Cosmos DB for NoSQL: The persistent datastore for source data (domain data with embeddings), session history (prompts/completions and feedback), and vector database capabilities.
- Azure OpenAI: Provides the AI models.
- semantic-kernel: Used for AI and LLM orchestration.
- Apache Jena: Provides the high-performance in-memory graph.
- SPARQL 1.1: The query language used for the graph.
- Web Ontology Language (OWL): The language used for graph schema and ontology definitions.
Understand the CosmosAIGraph application components
mainCosmosAIGraph is composed of several key components that work together to provide AI-driven graph capabilities:
- Web app: The UI frontend that provides the user interface and AI functionality.
- Graph app: A microservice containing the in-memory graph.
- Azure Container Apps: Serves as the runtime orchestrator for the Web app and Graph app microservices.
- Azure Cosmos DB for NoSQL: Stores domain data, conversational AI documents, and embeddings.
- Azure OpenAI: Provides the completion and embedding models used by the system.