Setup and Installation
To use this feature, install thelangchain-hana package:
HanaSparqlQAAgent is an agent-based approach for answering questions over RDF data stored in SAP HANA Cloud. Unlike the chain-based approach, the agent can:
- Dynamically retrieve the ontology using a dedicated tool
- Generate and execute SPARQL queries iteratively
- Self-correct if a query fails or returns unexpected results
- Reason step-by-step about complex questions
Initialization
You need:- An LLM to power the agent’s reasoning
- A
HanaRdfGraph(with connection,graph_uri, and ontology)
HanaRdfGraph instance.
Import the HanaSparqlQAAgent
Agent Overview
The agent uses tools iteratively to:- First retrieve the ontology to understand the data structure
- Generate appropriate SPARQL queries based on the schema
- Execute queries and interpret results
- Formulate natural language answers
Defaults
- Tools:
retrieve_ontology- Retrieves the RDF ontology/schema from the graph in Turtle formatexecute_sparql- Executes SPARQL queries against the HANA RDF graph
- System Prompt: A default system prompt is provided with instructions for SPARQL generation and tool usage.
- Middleware:
ModelRetryMiddleware(max_retries=3)andToolRetryMiddleWare(max_retries=2)is added by default to prevent infinite loops
Customizing Your Agent
You can customize the agent’s behavior by providing additional parameters tocreate_agent:
Example: Question answering over a “Movies” knowledge graph
Prerequisite: You must have an SAP HANA Cloud instance with the triple store feature enabled. For detailed instructions, refer to: Enable Triple StoreLoad the
kgdocu_movies example data. See Knowledge Graph Example.
The example below:
- Instantiates the
HanaRdfGraphpointing at the movies data graph - Creates a
HanaSparqlQAAgentpowered by an LLM - Asks natural-language questions and lets the agent reason through the answers
What’s happening under the hood?
-
Ontology Retrieval
The agent first uses the
retrieve_ontologytool to fetch the RDF schema in Turtle format. This gives it understanding of the available classes, properties, and relationships. -
SPARQL Generation
Based on the ontology and the user’s question, the agent reasons about which entities and properties to query, then generates a valid
SELECTquery. -
Query Execution
The agent calls the
execute_sparqltool to run the generated query against the HANA RDF graph. If the query fails or returns unexpected results, the agent can self-correct and try again. - Answer Formulation The agent interprets the query results and formulates a concise, human-readable answer based strictly on the retrieved data.
Connect these docs to Claude, VSCode, and more via MCP for real-time answers.

