---
sidebar_position: 6
question: How do I run SPARQL on the knowledge graph from a module?
kind: task
via_web: na
via_cli: na
via_python: available
via_api: available
via_config: na
ref_python: triple_store.query
prereq: You need a module that lists `"triple_store"` in its dependencies. [Create a module](/capabilities/build/modules/creating-a-module) first.
next:
  - /capabilities/build/agents/give-it-tools
  - /capabilities/build/knowledge-graph/explore-the-graph
---

# Query with SPARQL

A module runs SPARQL on the triple store with `triple_store.query`, or `query_stream` for large results. A query you want agents to reuse goes in a workflow class of the module: its parameters are the query's arguments, and `as_tools()` turns it into a tool.

## Web UI

Not applicable. Nexus has no SPARQL editor: the Composer shows the SPARQL it ran, read-only ([Explore the graph](/capabilities/build/knowledge-graph/explore-the-graph?via=web)). On the Docker stack, YASGUI at `http://localhost:3000` edits SPARQL on Fuseki.

## CLI

Not applicable. There is no `abi` command that runs SPARQL. Send the query to the store's endpoint (REST API tab), or run it from Python.

## Python

The module lists `"triple_store"` in its dependencies: see [Add data](/capabilities/build/knowledge-graph/add-data?via=python). RDF results need the `naas-abi-sdk[rdf]` extra.

### Run a query

```python
store = self.engine.services.triple_store
rows = await store.query("""
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    SELECT ?s ?label
    WHERE { GRAPH <http://ontology.naas.ai/graph/my_module> { ?s rdfs:label ?label } }
    LIMIT 10
""")
for row in rows:
    print(row.s, row.label)
```

`query` returns an `rdflib` result: rows for a `SELECT`, a graph for a `CONSTRUCT` or `DESCRIBE`, a boolean for an `ASK`.

### Stream a large result

```python
sparql = """
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    SELECT ?s ?label
    WHERE { GRAPH <http://ontology.naas.ai/graph/my_module> { ?s rdfs:label ?label } }
"""
async with store.query_stream(sparql) as result:
    async for row in result.rows:
        print(row["s"], row["label"])
```

`query_stream` reads the result as it arrives, with no size cap. `result.rows` (a `SELECT`, each row a dict of variable name to `rdflib` term) and `result.triples` (a `CONSTRUCT` or `DESCRIBE`) are read once, inside the block.

### Reuse a query as an agent tool

Write the query in a workflow class, with its arguments as the parameters model:

```python title="src/my_module/workflows/FindRecordWorkflow.py"
from __future__ import annotations

from dataclasses import dataclass

from naas_abi_sdk.workflow import Workflow, WorkflowConfiguration, WorkflowParameters
from pydantic import Field


@dataclass
class FindRecordWorkflowConfiguration(WorkflowConfiguration):
    """Configuration for FindRecordWorkflow."""


class FindRecordWorkflowParameters(WorkflowParameters):
    record_id: str = Field(
        description="Identifier of the record in the source system.",
        pattern=r"^[A-Za-z0-9_-]{1,64}$",
    )


class FindRecordWorkflow(Workflow[FindRecordWorkflowParameters]):
    """Look up a single record by its identifier."""

    def __init__(self, configuration: FindRecordWorkflowConfiguration, module=None):
        super().__init__(configuration)
        self.module = module

    @classmethod
    def New(cls, module) -> "FindRecordWorkflow":
        return cls(FindRecordWorkflowConfiguration(), module)

    async def run(self, parameters: FindRecordWorkflowParameters) -> list[dict]:
        rows = await self.module.engine.services.triple_store.query(f"""
            PREFIX my_module: <http://ontology.naas.ai/my_module/>
            SELECT DISTINCT ?record WHERE {{
              GRAPH <http://ontology.naas.ai/graph/my_module> {{
                ?record my_module:record_id "{parameters.record_id}" .
              }}
            }}
        """)
        return [{"record": str(row.record)} for row in rows]
```

The class docstring is the tool's description and the parameters' `Field(description=...)` its arguments: the agent picks the tool from them, so write the description as the question a user would ask. The `pattern` is checked before `run`, so a value cannot change the query. The module builds the class and names it `find_record_workflow`; an agent of the module takes it as a tool with `await self.build_processes()`, then `self.get_workflow_instance("find_record_workflow").as_tools()`. See [Create a workflow](/capabilities/build/agents/creating-a-workflow) and [Give it tools](/capabilities/build/agents/give-it-tools).

## REST API

The Nexus API and the engine API have no route that takes raw SPARQL. The triple store's own endpoint does, on the machine that runs it.

### Send the query

With `abi dev up`, the store is the `oxigraph` server; `abi dev ports` prints its port (7878 plus the checkout's offset). It has no auth:

```bash
curl -X POST "http://127.0.0.1:7878/query" \
  -H "Content-Type: application/sparql-query" \
  -H "Accept: application/sparql-results+json" \
  --data 'SELECT ?g (COUNT(*) AS ?n) WHERE { GRAPH ?g { ?s ?p ?o } } GROUP BY ?g'
```

### Or on the Docker stack

Fuseki answers SPARQL on `http://localhost:3030/ds/query` (dataset `ds`). Its admin user is `admin`, with the `FUSEKI_ADMIN_PASSWORD` from `.env`.

## Config

Not applicable. Queries are code in the module, not `config.yaml` entries. `config.yaml` only picks the store: see [Triple Store](/user-guide/get-started/configuration#triple-store).

## Best practices

- **Descriptions.** Say which question the query answers and what it leaves out. The agent chooses on that text.
- **Validation.** Give every argument the tightest `pattern` its values allow before it goes into the query.
- **Query shape.** Declare every `PREFIX`, scope the pattern with `GRAPH <...>`, use `DISTINCT` when joins can repeat rows, order the results, and add a `LIMIT` for large sets.
