CosmosAIGraph

repository·main·Indexed 41 days ago

https://github.com/azurecosmosdb/cosmosaigraph

An 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.

Tokens
20.9K
Snippets
46
Records
102
Agent score
100%

What's inside CosmosAIGraph

  1. Overview of CosmosAIGraph

    main
    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.
  2. Overview of CosmosAIGraph (caig) Architecture

    main

    CosmosAIGraph (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_app and graph_app directories of the repository and are packaged as Docker containers named caig_web and caig_graph respectively.

  3. Understand the Python codebase structure in impl\app

    main

    The Python implementation is located in the impl\app directory. 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 using pytest.
    • docker: Dockerfiles and docker-compose.yml files.
  4. What is cleared during a session reset

    main

    A session reset via the brand link clears data in three layers:

    Client-side (Browser)

    • Local Storage: All localStorage data 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_id and 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}.json
      • tmp/ai_conv_{conversation_id}.json
  5. What is the OmniRAG pattern?

    main

    The 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.
  6. Use Apache Jena Fuseki as an external graph backend

    main

    By 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_BACKEND environment variable to fuseki.

    How it works

    1. Model Assembly: At startup, AppGraphBuilder assembles the RDF model (ontology + triples from Cosmos DB/RDF/JSON).
    2. Upload: If CAIG_GRAPH_BACKEND=fuseki is set, the graph_app connects to the Fuseki dataset at CAIG_FUSEKI_DATASET_URL and uploads the model via the SPARQL Graph Store Protocol.
    3. Querying: Subsequent requests to /sparql_query, /sparql_update, and /add_documents are served by Fuseki via SPARQL 1.1.
    4. Performance Optimization: To prevent an N+1 HTTP request storm during /sparql_bom_query traversals, the graph_app fetches a single local snapshot of the Fuseki dataset and runs the traversal in-process.
    export CAIG_GRAPH_BACKEND=fuseki
  7. Model data for in-memory graph construction

    main

    CosmosAIGraph 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 edges attribute 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"
      ]
    }
  8. Configure CosmosAIGraph using environment variables

    main

    The application uses ConfigService to 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 .env file for local development, the project utilizes the python-dotenv library. Note: Do not commit .env files to source control as they may contain secrets.

  9. Apply Custom Rules to NL2SPARQL and OmniRAG Chat

    main

    Custom 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 sessionStorage under sparql_custom_rules are 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.
  10. CosmosAIGraph Technology Stack

    main

    The 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.
  11. Understand the CosmosAIGraph application components

    main

    CosmosAIGraph 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.