✨ SPARQL query generation with LLMs 🦜
This project provides tools to enhance the capabilities of Large Language Models (LLMs) in generating queries for specific endpoints:
Alimenter votre agent
Installation de l'éditeur. Ce n'est pas un endpoint PlugMCP.
Host a copy with our keys and logs.
Pas encore de version packagée dans le registre. Suivez le README du dépôt.
URL distante ou commande sur votre machine ? Ce qui distingue les deux installations
Exécuter sur PlugMCP
A new server you create. It is not this listing's official endpoint. Use the publisher install when you want their URL and their credentials.
LancerDe l'éditeur
sparql-llm pip packageThe 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.
🥇 We won the first place at the Text2SPARQL Challenge, co-located with ESWC 2026. Some highlights from our evaluation:
*compared with the second-best system in the challenge
[!TIP]
You can quickly check if an endpoint contains the expected metadata at sib-swiss.github.io/sparql-editor/check
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
question (string): the user's questionpotential_classes (list[string]): high level concepts and potential classes that could be found in the SPARQL endpointssteps (list[string]): split the question in standalone smaller parts if relevantclasses (list[string]): high level concepts and potential classes that could be found in the SPARQL endpointsquery (string): a valid SPARQL query stringendpoint (string): the SPARQL endpoint URL to execute the query againstUniProt tools calling the UniProt REST API directly, defined in uniprot_tools.py:
search_proteins: search UniProtKB entries (accession, name, genes, organism)get_protein: get a UniProtKB entry by accession (name, organism, function, sequence)UniProt tools showing interactive widgets to the user, for clients supporting MCP Apps. The widget gets the full data, the model only gets a text summary. Widgets are in widgets/:
show_protein_features: Nightingale tracks of domains, sites, PTMs, processing, topology, secondary structure and variants, zoomable along the sequence. Given start and end residues (e.g. 102 and 234, or only start for a mutation), the viewer opens zoomed on the region, highlighted on all tracksshow_protein_structure: AlphaFold model colored by pLDDT, or a PDB entry, in Mol* (PDBe Molstar), next to the features list: clicking one highlights its residues. Residues can be highlighted from the start, e.g. a mutationsearch_proteins_table: results of a UniProtKB query (up to 1000 rows) in a sortable table with facets for reviewed status, annotation score and organism. The rows selected by the user are sent back to the modelshow_protein_variants: disease and natural variants from the EBI Proteins API positioned on the sequence next to the domains, filterable by consequence, clinical significance, evidence and disease, with links to ClinVar, dbSNP and PubMedshow_annotation_matrix: heatmap of the reviewed proteins of a gene list by GO terms, keywords or Reactome pathways, for a quick functional overviewshow_protein_network: graph connecting a protein list through 3 kinds of sourced relationships: directed regulations (activation, inhibition, or mixed when both are reported) from OmniPath with their resources, PubMed references and modification sites, physical interactions from IntAct (via UniProtKB), and Reactome pathway membership. It shows the best supported paths from a source to a target protein (highest minimum evidence, then shortest), and the feedback edges going back upstream with the loop they close. Proteins not listed are added when they connect 2 listed ones. Each relationship links to its source records: OmniPath records and sites, PubMed references with the resources citing them, IntAct evidence (PSI-MITAB) and UniProtKB interactions, Reactome pathways, and the queries of all the data used. Drawn with Cytoscape.js, in layers following the signal from the sourceFollow 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:
ctrl+shift+i or cmd+shift+i), and make sure the mode is set to Agent in the bottom rightctrl+shift+p or cmd+shift+p), and search for MCP: Open User Configuration, this will open a mcp.json fileConnect 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:
{
"servers": {
"expasy-mcp-http": {
"url": "https://chat.expasy.org/mcp/",
"type": "http"
}
}
}
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:
{
"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):
{
"servers": {
"expasy-mcp": {
"type": "stdio",
"command": "uvx",
"env": {
"SETTINGS_FILEPATH": "/Users/you/sparql-mcp.json"
},
"args": [
"sparql-llm"
]
}
}
}
[!IMPORTANT]
Click on
Startjust 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.
Requires Python >=3.10
pip install sparql-llm
Or with uv:
uv add sparql-llm
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.
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.:
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.
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.
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.:
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:
up:Disease_Annotation { a [ up:Disease_Annotation ] ; up:sequence [ up:Chain_Annotation up:Modified_Sequence ] ; rdfs:comment xsd:string ; up:disease IRI }
You can also generate the complete ShEx shapes for a SPARQL endpoint with:
from sparql_llm import get_shex_from_void
shex_str = get_shex_from_void("https://sparql.uniprot.org/sparql/")
print(shex_str)
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:
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.
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))
[!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.pyandcompose.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.
Explore and change the system configuration in src/sparql-llm/config.py
Create a .env file at the root of the repository to provide secrets and API keys:
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
Optionally, if you made changes to it, build the chat UI webpage:
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
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:
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:
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):
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
datafolder (e.g. vectordb indexes and endpoints metadata)
Conversations are logged in
data/logs/requests.jsonl, one JSON line per request (group lines onsessionIdto rebuild multi-turn conversations): full messages, steps, generated SPARQL query, tokens, cost and runtime. Those logs can be explored with chat-logs-viewer. Change the path with theREQUESTS_LOGS_FILEPATHenv variable.
[!NOTE]
Query the chat API:
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)
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/entitiesbefore starting the stack
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:
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:
docker compose up -d
VECTORDB_URL=http://localhost:6334 uv run tests/benchmark_biodata.py
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
Checkout the CONTRIBUTING.md page.
If you reuse any part of this work, please cite at least one of our articles below:
@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}
}
@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},
}
🦜✨ Chat system, MCP server, and reusable components to improve LLMs capabilities when generating SPARQL queries
Outils
Pas encore de liste d'outils. Les serveurs distants en obtiennent une après le premier contrôle d'état.
FAQ
Copiez sur cette page la configuration stdio pour Cursor, Claude Desktop, Claude Code ou VS Code. Elle utilise l'installation de l'éditeur, pas un proxy PlugMCP.
Aucune variable d'environnement requise n'est indiquée sur cette fiche.
Sparql Llm s'exécute en local via stdio.
Dernière vérification : 2026-10-26. 🦜✨ Chat system, MCP server, and reusable components to improve LLMs capabilities when generating SPARQL queries