Logo de Sparql Llm

Sparql Llm

Organisation
sib-swiss

🩜✹ Chat system, MCP server, and reusable components to improve LLMs capabilities when generating SPARQL queries

Éditeursib-swiss
DépÎtsparql-llm
LangueJupyter Notebook
Forks
23
Étoiles
124
Outils disponibles
0
Type de transportstdio
LicenceMIT
Liens
  • Connectez des outils Ă  vos workflows IA

    Sparql Llm propose des fonctionnalités MCP utilisables par les clients et agents IA compatibles.

  • 0 outils disponibles

    Parcourez les actions invocables ci-dessous, avec leurs noms et descriptions lorsque le serveur les fournit.

  • Configuration prĂȘte Ă  copier

    Utilisez les exemples de configuration pour configurer ce serveur dans votre client MCP préféré.

  • Indicateurs de popularitĂ© open source

    124 étoiles et 23 forks sur le dépÎt associé.

✹ SPARQL query generation with LLMs 🩜

PyPI - Version PyPI - Python Version Tests

This project provides tools to enhance the capabilities of Large Language Models (LLMs) in generating SPARQL queries for specific endpoints:

The system integrates Retrieval-Augmented Generation (RAG) and SPARQL query validation through endpoint schemas, to ensure more accurate and relevant query generation on large scale knowledge graphs.

The components are designed to work either independently or as part of a full chat-based system that can be deployed for a set of SPARQL endpoints. It requires endpoints to include metadata such as SPARQL query examples and endpoint descriptions using the Vocabulary of Interlinked Datasets (VoID), which can be automatically generated using the void-generator.

🌈 Features

  • Metadata Extraction: Functions to extract and load relevant metadata from SPARQL endpoints. These loaders are compatible with LangChain but are flexible enough to be used independently, providing metadata as JSON for custom vector store integration.
  • SPARQL Query Validation: A function to automatically parse and validate federated SPARQL queries against the VoID description of the target endpoints.
  • MCP server with tools to help LLM write SPARQL queries for a set of endpoints
  • Deployable Chat System: A reusable and containerized system for deploying an LLM-based chat service with a web UI, API, and vector database. This system helps users write SPARQL queries by leveraging endpoint metadata (WIP).
  • Live Example: Configuration for expasy.org/chat, an LLM-powered chat system supporting SPARQL query generation for endpoints maintained by the SIB.

[!TIP]

You can quickly check if an endpoint contains the expected metadata at sib-swiss.github.io/sparql-editor/check

🔌 MCP server

The server exposes a Model Context Protocol (MCP) endpoint to access biodata resources at the SIB, through their SPARQL endpoints, such as UniProt, Bgee, OMA, SwissLipids, Cellosaurus at chat.expasy.org/mcp

đŸ› ïž Available tools

  • 📝 Retrieve relevant documents (query examples and classes schema) to help writing SPARQL queries to access SIB biodata resources
    • Arguments:
      • question (string): the user's question
      • potential_classes (list[string]): high level concepts and potential classes that could be found in the SPARQL endpoints
      • steps (list[string]): split the question in standalone smaller parts if relevant
  • đŸ·ïž Retrieve relevant classes schema to help writing SPARQL queries to access SIB biodata resources
    • Arguments:
      • classes (list[string]): high level concepts and potential classes that could be found in the SPARQL endpoints
  • 📡 Execute a SPARQL query against a SPARQL endpoint
    • Arguments:
      • query (string): a valid SPARQL query string
      • endpoint (string): the SPARQL endpoint URL to execute the query against

âšĄïž Connect client to MCP server

Follow the instructions of your client, and use the URL of the public server: https://chat.expasy.org/mcp

For example, for GitHub Copilot in VSCode, to add a new MCP server through the VSCode UI:

  • Open side panel chat (ctrl+shift+i or cmd+shift+i), and make sure the mode is set to Agent in the bottom right
  • Open command palette (ctrl+shift+p or cmd+shift+p), and search for MCP: Open User Configuration, this will open a mcp.json file

📡 Use streamable HTTP server

Connect to a running streamable HTTP MCP server, such as the publicly available chat.expasy.org/mcp.

In your VSCode mcp.json you should have the following:

sh
{
	"servers": {
		"expasy-mcp-http": {
			"url": "https://chat.expasy.org/mcp/",
			"type": "http"
		}
	}
}

⌚ Use stdio transport

sh
uvx sparql-llm

Optionally you can provide the path to a custom settings JSON file to configure the server (e.g. the list of endpoints that will be indexed and available through the server), see the Settings class for detailed available settings.

Example settings file for your MCP server deployment:

json
{
    "app_org": "Your organization",
    "app_topics": "genes, proteins, lipids, chemical reactions, and metabolomics data",
    "endpoints" : [
        {
            "label": "UniProt",
            "endpoint_url": "https://sparql.uniprot.org/sparql/",
            "description": "UniProt is a comprehensive resource for protein sequence and annotation data."
        },
        {
            "label": "Bgee",
            "description": "Bgee is a database for retrieval and comparison of gene expression patterns across multiple animal species.",
            "endpoint_url": "https://www.bgee.org/sparql/",
            "homepage_url": "https://www.bgee.org/"
        }
    ]
}

Example mcp.json file to add and configure the MCP server in a client (e.g. VSCode):

json
{
  "servers": {
    "expasy-mcp": {
      "type": "stdio",
      "command": "uvx",
      "env": {
				"SETTINGS_FILEPATH": "/Users/you/sparql-mcp.json"
			},
      "args": [
        "sparql-llm"
      ]
    }
  }
}

[!IMPORTANT]

Click on Start just on top of "openroute-mcp" to start the connection to the MCP server.

You can click the wrench and screwdriver button đŸ› ïž (Configure Tools...) to enable/disable specific tools

[!NOTE]

More details available in the VSCode MCP official docs.

đŸ“Šïž Reusable components

Installation

Requires Python >=3.10

bash
pip install sparql-llm

Or with uv:

sh
uv add sparql-llm

SPARQL query examples loader

Load SPARQL query examples defined using the SHACL ontology from a SPARQL endpoint. See github.com/sib-swiss/sparql-examples for more details on how to define the examples.

python
from sparql_llm import SparqlExamplesLoader

loader = SparqlExamplesLoader("https://sparql.uniprot.org/sparql/")
docs = loader.load()
print(len(docs))
print(docs[0].metadata)

You can provide the examples as a file if it is not integrated in the endpoint, e.g.:

python
loader = SparqlExamplesLoader("https://sparql.uniprot.org/sparql/", examples_file="uniprot_examples.ttl")

Refer to the LangChain documentation to figure out how to best integrate documents loaders to your system.

[!NOTE]

You can check the completeness of your examples against the endpoint schema using this notebook.

SPARQL endpoint schema loader

Generate a human-readable schema using the ShEx format to describe all classes of a SPARQL endpoint based on the VoID description present in the endpoint. Ideally the endpoint should also contain the ontology describing the classes, so the rdfs:label and rdfs:comment of the classes can be used to generate embeddings and improve semantic matching.

[!TIP]

Checkout the void-generator project to automatically generate VoID description for your endpoint.

python
from sparql_llm import SparqlVoidShapesLoader

loader = SparqlVoidShapesLoader("https://sparql.uniprot.org/sparql/")
docs = loader.load()
print(len(docs))
print(docs[0].metadata)

You can provide the VoID description as a file if it is not integrated in the endpoint, e.g.:

python
loader = SparqlVoidShapesLoader("https://sparql.uniprot.org/sparql/", void_file="uniprot_void.ttl")

The generated shapes are well-suited for use with a LLM or a human, as they provide clear information about which predicates are available for a class, and the corresponding classes or datatypes those predicates point to. Each object property references a list of classes rather than another shape, making each shape self-contained and interpretable on its own, e.g. for a Disease Annotation in UniProt:

turtle
up:Disease_Annotation {
a [ up:Disease_Annotation ] ;
up:sequence [ up:Chain_Annotation up:Modified_Sequence ] ;
rdfs:comment xsd:string ;
up:disease IRI
}

Generate complete ShEx shapes from VoID description

You can also generate the complete ShEx shapes for a SPARQL endpoint with:

python
from sparql_llm import get_shex_from_void

shex_str = get_shex_from_void("https://sparql.uniprot.org/sparql/")
print(shex_str)

Validate a SPARQL query based on VoID description

This takes a SPARQL query and validates the predicates/types used are compliant with the VoID description present in the SPARQL endpoint the query is executed on.

This function supports:

  • federated queries (VoID description will be automatically retrieved for each SERVICE call in the query),
  • path patterns (e.g. orth:organism/obo:RO_0002162/up:scientificName)

This function requires that at least one type is defined for each endpoint, but it will be able to infer types of subjects that are connected to the subject for which the type is defined.

It will return a list of issues described in natural language, with hints on how to fix them (by listing the available classes/predicates), which can be passed to an LLM as context to help it figuring out how to fix the query.

python
from sparql_llm import validate_sparql_with_void

sparql_query = """PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX up: <http://purl.uniprot.org/core/>
PREFIX taxon: <http://purl.uniprot.org/taxonomy/>
PREFIX orth: <http://purl.org/net/orth#>
PREFIX obo: <http://purl.obolibrary.org/obo/>
PREFIX lscr: <http://purl.org/lscr#>
PREFIX genex: <http://purl.org/genex#>
PREFIX sio: <http://semanticscience.org/resource/>
SELECT DISTINCT ?humanProtein ?orthologRatProtein ?orthologRatGene
WHERE {
    ?humanProtein a orth:Protein ;
        lscr:xrefUniprot <http://purl.uniprot.org/uniprot/Q9Y2T1> .
    ?orthologRatProtein a orth:Protein ;
        sio:SIO_010078 ?orthologRatGene ;
        orth:organism/obo:RO_0002162/up:name 'Rattus norvegicus' .
    ?cluster a orth:OrthologsCluster .
    ?cluster orth:hasHomologousMember ?node1 .
    ?cluster orth:hasHomologousMember ?node2 .
    ?node1 orth:hasHomologousMember* ?humanProtein .
    ?node2 orth:hasHomologousMember* ?orthologRatProtein .
    FILTER(?node1 != ?node2)
    SERVICE <https://www.bgee.org/sparql/> {
        ?orthologRatGene a orth:Gene ;
            genex:expressedIn ?anatEntity ;
            orth:organism ?ratOrganism .
        ?anatEntity rdfs:label 'brain' .
        ?ratOrganism obo:RO_0002162 taxon:10116 .
    }
}"""

issues = validate_sparql_with_void(sparql_query, "https://sparql.omabrowser.org/sparql/")
print("\n".join(issues))

🚀 Complete chat system

[!WARNING]

To deploy the complete chat system right now you will need to fork/clone this repository, change the configuration in src/sparql-llm/config.py and compose.yml, then deploy with docker/podman compose. It can easily be adapted to use any LLM served through an OpenAI-compatible API.

Requirements: Docker, nodejs (to build the frontend), and optionally uv if you want to run scripts outside of docker.

  1. Explore and change the system configuration in src/sparql-llm/config.py

  2. Create a .env file at the root of the repository to provide secrets and API keys:

    sh
    CHAT_API_KEY=NOT_SO_SECRET_API_KEY_USED_BY_FRONTEND_TO_AVOID_SPAM_FROM_CRAWLERS
    LOGS_API_KEY=SECRET_PASSWORD_TO_EASILY_ACCESS_LOGS_THROUGH_THE_API
    
    OPENROUTER_API_KEY=sk-YYY
    OPENAI_API_KEY=sk-proj-YYY
    
    LANGFUSE_HOST=https://cloud.langfuse.com
    LANGFUSE_PUBLIC_KEY=
    LANGFUSE_SECRET_KEY=
  3. Optionally, if you made changes to it, build the chat UI webpage:

    sh
    cd chat-with-context
    npm i
    npm run build:demo
    cd ..

    You can change the UI around the chat in chat-with-context/demo/index.html

  4. Start the vector database and web server locally for development, with code from the src folder mounted in the container and automatic API reload on changes to the code:

    bash
    docker compose up

    In production, you will need to make some changes to the compose.prod.yml file to adapt it to your server/proxy setup:

    bash
    docker compose -f compose.prod.yml up

    Then run the indexing script manually from within the container to index the SPARQL endpoints (need to do it once):

    sh
    docker compose -f compose.prod.yml exec api uv run src/sparql_llm/indexing/index_resources.py

    All data from the containers are stored persistently in the data folder (e.g. vectordb indexes and endpoints metadata)

[!NOTE]

Query the chat API:

sh
curl -X POST http://localhost:8000/chat -H "Content-Type: application/json" -d '{"messages": [{"role": "user", "content": "What is the HGNC symbol for the P68871 protein?"}], "model": "mistralai/mistral-small-latest", "stream": true}'

[!WARNING]

Experimental entities indexing: it can take a lot of time to generate embeddings for millions of entities. So we recommend to run the script to generate embeddings on a machine with GPU (does not need to be a powerful one, but at least with a GPU, checkout fastembed GPU docs to install the GPU drivers and dependencies)

sh
docker compose up vectordb -d
VECTORDB_URL=http://localhost:6334 nohup uv run --extra gpu src/sparql_llm/indexing/index_entities.py --gpu &

Then move the entities collection containing the embeddings in data/qdrant/collections/entities before starting the stack

đŸ„‡ Benchmarks

There are a few benchmarks available for the system:

  • The tests/benchmark.py script will run a list of questions and compare their results to a reference SPARQL queries, with and without query validation, against a list of LLM providers. You will need to change the list of queries if you want to use it for different endpoints. You will need to start the stack in development mode to run it:

    sh
    uv run --env-file .env tests/benchmark.py

    It takes time to run and will log the output and results in data/benchmarks

  • Follow these instructions to run the Text2SPARQL Benchmark.

  • For biodata benchmark:

    sh
    docker compose up -d
    VECTORDB_URL=http://localhost:6334 uv run tests/benchmark_biodata.py

đŸ§‘â€đŸ« Tutorial

There is a step by step tutorial to show how a LLM-based chat system for generating SPARQL queries can be easily built here: https://sib-swiss.github.io/sparql-llm

đŸ§‘â€đŸ’» Contributing

Checkout the CONTRIBUTING.md page.

đŸȘ¶ How to cite this work

If you reuse any part of this work, please cite at least one of our articles below:

bibtex
@article{10.1145/3847195,
author = {Smeros, Panayiotis and Emonet, Vincent and Wang, Ruijie and Sima, Ana-Claudia and Mendes de Farias, Tarcisio},
title = {SPARQL-LLM: Real-Time SPARQL Query Generation from Natural Language Questions},
year = {2026},
publisher = {Association for Computing Machinery},
address = {New York, NY, USA},
issn = {1559-1131},
url = {https://doi.org/10.1145/3847195},
doi = {10.1145/3847195},
journal = {ACM Trans. Web},
month = sep,
keywords = {Large Language Models, SPARQL, TEXT2SPARQL, Bioinformatics, Knowledge Graphs}
}
bibtex
@conference{emonet2025llm,
    title={LLM-based SPARQL Query Generation from Natural Language over Federated Knowledge Graphs},
    author={Emonet, Vincent and Bolleman, Jerven and Duvaud, Severine and Mendes de Farias, Tarcisio and Sima, Ana Claudia},
    year = 2025,
    note={CEUR-WS.org, online \url{https://ceur-ws.org/Vol-3953/355.pdf}},
    booktitle = {ISWC 2024 Special Session on Harmonising Generative AI and Semantic Web Technologies, November 13, 2024, Baltimore, Maryland},
    volume = 3953,
    series = {CEUR Workshop Proceedings},
}

Utilisez le serveur MCP Sparql Llm avec plusieurs modĂšles IA

TypingMind connecte les outils MCP au niveau de l’espace de travail. Une fois Sparql Llm connectĂ©, vous pouvez donc l’utiliser avec diffĂ©rents modĂšles IA dans TypingMind sans avoir Ă  le configurer sĂ©parĂ©ment pour chaque modĂšle. Cette intĂ©gration MCP s’exĂ©cute localement sur votre appareil via le connecteur MCP de TypingMind.

Guide de configuration du connecteur local

Choisissez cette méthode si le serveur MCP doit accéder à des fichiers locaux, à des applications ou à des ressources privées sur votre ordinateur.

1

Ouvrir les paramĂštres MCP

Dans TypingMind, accédez à « ParamÚtres », puis à « ParamÚtres avancés » et à « Model Context Protocol », et choisissez « Configurer connecteur ».

  1. Ouvrez TypingMind dans votre navigateur.
  2. Cliquez sur l’icîne Paramùtres.
  3. Accédez aux paramÚtres avancés.
  4. Ouvrez la section Model Context Protocol.
  5. Cliquez sur « Configurer connecteur » et choisissez « Cet appareil ».
Écran de configuration du connecteur MCP de TypingMind avec l’option « Cet appareil » sĂ©lectionnĂ©e
2

Exécuter la commande du connecteur

Choisissez « Cet appareil », copiez la commande depuis TypingMind et exĂ©cutez-la dans Terminal. Laissez le processus en cours d’exĂ©cution pendant que vous utilisez MCP.

  1. Copiez la commande de configuration affichée par TypingMind.
  2. Ouvrez Terminal sur macOS ou Windows Terminal sur Windows.
  3. Collez et exécutez la commande.
  4. Autorisez l’installation du paquet si Terminal vous demande de confirmer.
  5. Gardez la fenĂȘtre de Terminal ouverte et le processus en cours d’exĂ©cution pendant que vous utilisez les outils MCP.
3

Ajoutez Sparql Llm en tant que serveur

Lorsque l’état du connecteur affiche « PrĂȘt », cliquez sur « Éditer serveurs » et collez la configuration du serveur MCP.

  1. Attendez que l’état du connecteur affiche « PrĂȘt ».
  2. Cliquez sur « Éditer serveurs ».
  3. Collez la configuration du serveur MCP Sparql Llm.
  4. Enregistrez la liste des serveurs.
  5. Actualisez pour vĂ©rifier que le connecteur est toujours prĂȘt.
ParamĂštres MCP de TypingMind affichant un serveur actif et le bouton « Éditer serveurs »
{
  "mcpServers": {
    "sparql-llm": {
      "command": "npx",
      "args": [
        "-y",
        "<mcp-server-package>"
      ]
    }
  }
}
4

Utiliser la connexion avec différents modÚles

Enregistrez la liste des serveurs, ouvrez « Plugins », activez les outils MCP de Sparql Llm, puis sélectionnez un modÚle IA compatible dans TypingMind et utilisez les outils dans une discussion ou attribuez-les à un agent IA.

  1. Ouvrez la page Plugins dans TypingMind.
  2. Activez les outils MCP de Sparql Llm.
  3. Démarrez une discussion et choisissez le modÚle IA que vous souhaitez utiliser.
  4. Utilisez les outils MCP dans le chat ou attribuez-les Ă  un agent IA.
  5. Passez à un autre modÚle IA selon vos besoins sans rétablir la connexion MCP.
Discussion TypingMind utilisant des outils MCP activĂ©s avec un modĂšle d’IA sĂ©lectionnĂ©
Pouvez-vous utiliser Sparql Llm pour m’aider dans cette tñche ?
Sparql Llm
Bien sĂ»r. J’ai tout lu.
Voici ce que j’ai trouvĂ© avec Sparql Llm.

Foire aux questions

À quoi sert le serveur MCP Sparql Llm ?

Sparql Llm est un serveur MCP qui permet aux applications IA compatibles d’accĂ©der Ă  des outils et Ă  des informations contextuelles externes. Dans TypingMind, il vous suffit d’ajouter ce serveur MCP une seule fois pour rendre ses outils disponibles dans votre espace de travail IA.

Puis-je utiliser le serveur MCP Sparql Llm avec plusieurs modĂšles IA dans TypingMind ?

Oui. TypingMind connecte les outils MCP au niveau de l’espace de travail. Vous pouvez donc utiliser Sparql Llm avec diffĂ©rents modĂšles IA comme Claude, ChatGPT, Gemini ou d’autres modĂšles configurĂ©s dans TypingMind, sans avoir Ă  configurer le serveur MCP sĂ©parĂ©ment pour chaque modĂšle.

Pourquoi utiliser le connecteur MCP Sparql Llm avec TypingMind ?

TypingMind est l’une des meilleures interfaces de chat avec les LLM, car elle rĂ©unit plusieurs modĂšles IA, prompts, plugins, agents IA, clĂ©s API et outils MCP dans un seul espace de travail. Une fois Sparql Llm connectĂ©, vous pouvez utiliser ses outils MCP avec vos modĂšles prĂ©fĂ©rĂ©s tout en gardant vos discussions bien organisĂ©es dans TypingMind.

Comment connecter le serveur MCP Sparql Llm Ă  TypingMind ?

Sparql Llm fonctionne via le connecteur MCP local de TypingMind. C’est l’option idĂ©ale lorsque le serveur MCP doit accĂ©der Ă  des fichiers locaux, des applications de bureau, des outils en ligne de commande ou des ressources privĂ©es sur votre ordinateur.

Quels outils le serveur MCP Sparql Llm propose-t-il dans TypingMind ?

Sparql Llm propose des fonctionnalités MCP que vous pouvez activer depuis la page Plugins de TypingMind et utiliser dans les discussions ou attribuer à des agents IA.

Dois-je partager mes clés API avec TypingMind pour utiliser le serveur MCP Sparql Llm ?

Non. TypingMind privilĂ©gie le fonctionnement local et vous permet de garder le contrĂŽle de vos fournisseurs de modĂšles, clĂ©s API, prompts et paramĂštres MCP. Si Sparql Llm nĂ©cessite une authentification, ajoutez les en-tĂȘtes, les paramĂštres OAuth ou la configuration locale requis pour ce serveur MCP lors de la crĂ©ation de la connexion.

Serveurs MCP similaires

Tout voir

Créez votre propre espace IA dÚs maintenant

Abonnez-vous Ă  notre newsletter pour ĂȘtre informĂ© des nouvelles fonctionnalitĂ©s et des prochains cadeaux Ă  gagner 👇