Elamur Research

Investigating Large Language Models for Text-to-SPARQL Generation

Paper · 2025 · Jacopo D'Abramo, Andrea Zugarini and Paolo Torroni

Summary

A question can name the right things and still send a database looking in the wrong direction. To find who married Robert Kennedy’s daughter, a query must first follow the relationship from Kennedy to his child, then find that person’s spouse. A query that reverses the first relationship can use the right names and still ask for a different person. D’Abramo and colleagues study how large language models translate ordinary questions into SPARQL, a query language for knowledge graphs. In their main experiments, the translator receives the question and the correct graph entries and relationships. Its job is to assemble those ingredients into a query the graph can execute.

The authors use few-shot learning, putting worked examples in the prompt without updating the translator’s weights. Their Dynamic Few-Shot Learning method, or DFSL, retrieves examples for each question from the relevant benchmark’s training split. It looks for similarity in the wording and in the supplied entities and relations. The authors also test what happens when they keep several likely queries from beam search, the decoding procedure that explores competing continuations. They run the candidates on the graph and choose an answer using a simple rule. Across the benchmarks, choosing the first nonempty result in beam order worked better than choosing the largest result set.

The experiments cover DBpedia and Wikidata. Scores measure how closely the answers returned by the generated query match the answers returned by the reference query. With CodeLlama 70B, retrieved examples and multiple beam candidates produced test answer F1 scores of 84.45 on QALD-9 plus, 62.20 on QALD-10, and 77.89 on QALD-9 DB. These scores exceeded the published task-specialized baselines listed for those benchmarks. On LC-QuAD 2.0, the same configuration reached 89.10, while the strongest specialized baseline reached 95.00. Retrieval was especially effective on LC-QuAD 2.0 and offered much less advantage over fixed examples on QALD-10, whose test questions differ from its training questions.

The strongest scores depend on the correct entity and relation information being available. Removing it weakened the system on both graphs the authors tested, even though retrieved examples still helped compared with a prompt containing only the task description and question. The study establishes how far prompting and query execution can take the translation stage of graph question answering. Finding the right graph entries in the first place remains a separate task.

Deep dive: Investigating Large Language Models for Text-to-SPARQL Generation

D’Abramo and colleagues test how retrieved examples and multiple candidate queries improve text-to-SPARQL generation without task-specific fine-tuning. · about 32 minutes to read

The problem and its context

From a question to a graph operation

A question answering system can draw its answer from a graph of recorded facts. The graph represents a fact by connecting entities with a named relation. A query describes which connections to look for and what to return when the graph contains them. An ordinary question leaves much of that work implicit. A person reading a question about the capitals of African countries can infer that the countries are an intermediate part of the search and that the requested output is their capitals. The query has to express both roles explicitly.

This distinction gives text-to-SPARQL its place in a larger question-answering system. Entity linking connects a mention in the question to the intended entry in the graph. Relation linking identifies the graph’s properties for the relationships the question invokes. A query generator then has to decide how to use those entries and properties. It has to choose where to leave variables, which patterns should share a variable, and what value the query should return. It also has to decide whether the question asks for matching entries, a count, or a yes-or-no result.

The main task in the paper starts after the linking decisions. A benchmark supplies the entities and relations associated with the question, and the authors call this reference information gold. The setup lets them examine query construction with the intended vocabulary already available. For example, a supplied parent–child property can tell the generator which graph relation it should use. The property’s presence in the prompt leaves open which endpoint should be the named person and which should be an unknown child. The generator also has to decide whether to return the child or use the child to find another person.

The authors highlight the triple flip, an error in which the generated pattern reverses its subject and object. Its consequence depends on the graph’s representation of the property. With the endpoints swapped, the graph may return an empty set or may find an completely different match. The query can still look plausible, particularly when it contains the expected entity identifier and property. This makes triple direction a good example of why the authors study both the construction of a query and the result of executing it.

Earlier ways of assembling a query

The paper traces earlier graph querying work through rules, templates, and search. Rules and templates could express regular ways of turning a request into a graph query, but the authors describe scalability problems for manual and partly manual systems as graphs such as DBpedia and Wikidata expanded. A translator that depends on hand-built forms has to cover the growing variety of graph content and the ways questions refer to it. The paper presents later work as pursuing two broad routes through this problem.

One route retrieves relevant material from the graph. The approaches the authors discuss include splitting a question into subproblems, gathering facts around linked entities, and finding evidence by predicting relations or exploring paths through the graph. Knowledge-Augmented Language Model Prompting for Zero-Shot Knowledge Graph Question Answering is their example of a method that uses linked entities to retrieve facts. This kind of retrieval supplies evidence about the question currently being answered. In DFSL, the items retrieved are worked examples of previous questions and their queries. The current question’s answer comes from executing a new query against the graph.

The other route produces a formal interpretation, a task in semantic parsing. Some methods construct a preliminary logical form and refine it before execution. The paper describes KB-BINDER as using a language model to propose a logical form and a lexicon-based similarity search to refine it. It also discusses an approach that represents logical forms as sequences of Python function calls, with the aim of reducing format errors. Such work helps explain the significance of the starting conditions. A system given only a question has to recover information that is supplied directly to the generator in the main DFSL experiments. The authors restrict their main comparisons to text-to-SPARQL benchmarks with reference entities and relations.

The paper also describes earlier systems that generate SPARQL directly. One uses a pointer network and relation-aware attention to capture the entities, properties, and keywords relevant to building a query. Another, SGPT, combines an encoder for linguistic features of the question with a GPT-2 decoder. The authors identify the representation of connections among graph entities and relations as a challenge for that architecture. TSET addresses triple direction through a specialized training stage called Triplet Structure Correction. Its approach makes the structure of triples part of what the translator is trained to handle. D’Abramo and colleagues ask how much of the same practical difficulty can be addressed at inference time, through examples and alternative outputs.

Why the examples might matter

In-context learning puts the task, worked examples, and current input in a prompt. During inference the translator can use the examples as analogies, with its parameters held fixed. The paper contrasts this with fine-tuning, which adapts the parameters to the task. Building an in-context system therefore shifts part of the design problem to the choice of examples. A prompt can supply an illustration of SPARQL syntax, a graph-specific convention, or a whole pattern of connected triples that resembles what the current question requires.

Earlier work gave several reasons to treat demonstration choice as an experimental variable. The authors discuss a nearest-neighbor method that retrieves examples using distances or similarities between encoded inputs. They also describe work using diverse examples to broaden the structural coverage of prompts for compositional tasks. Other studies generated demonstrations for particular inputs or ranked prompts using perplexity. Work on text-to-SQL and on graph question answering had already put related approaches into practice. The authors identify the open-weight generators they test as a point of difference from the proprietary systems used in the retrieval-based prompting work they discuss.

Those precedents leave a practical question about how to recognize a useful analogy for SPARQL. Similar wording can bring up a question that asks for a different operation. A shared property can reveal an analogy between questions about different people or places. The authors’ design uses both kinds of evidence to select examples. It also leaves a separate opportunity to recover from an incorrect initial query by looking at what the other candidates actually return.

The method, step by step

What the translator receives and returns

The system starts with a natural-language question, its entities, and its relations. Think of the entities and relations as the vocabulary available to express the query. The graph engine will eventually need identifiers that refer to the right entries and properties. The prompt makes that vocabulary available alongside the ordinary wording. The translation still has to determine how to connect the identifiers, what other conditions the question imposes, and where in the resulting pattern to read out an answer.

A store of solved examples supplies the analogies. Each record has the same kinds of input as the current question, plus a reference SPARQL query. The system finds records that resemble the current case, gives their worked queries to the translator, and then presents the current case for completion. In the single-query version, the top decoded query supplies the answer. In the multi-query version, query execution supplies further evidence about which candidate to use.

From a question with graph links to an answer

The steps in order.

From a question with graph links to an answerStep 1: Receive the question, entities, and relations1. Receive the question, entities, and relationsStep 2: Encode inputs for example retrieval2. Encode inputs for example retrievalStep 3: Retrieve the closest worked examples3. Retrieve the closest worked examplesStep 4: Assemble instructions, examples, and target input4. Assemble instructions, examples, and target inputStep 5: Decode candidate SPARQL queries5. Decode candidate SPARQL queriesStep 6: Execute the queries on the graph6. Execute the queries on the graphStep 7: Select an answer from the results7. Select an answer from the results

The paper represents a knowledge graph as follows.

G := (E, R, F)

Here G is the graph, E is its collection of entities, R is its collection of relations, and F is its collection of facts. The symbol := defines the graph in terms of the tuple on its right. The authors give the facts the following structure.

F ⊆ E × R × E

The symbol ⊆ means that F is a subset of the possible triples. Each × forms part of the Cartesian product, so a candidate triple has an entity from E in its first position, a relation from R in its middle position, and an entity from E in its last position. The first entity is the subject and the last is the object. Only triples recorded among the facts belong to F. The positions explain why swapping the two entities changes the connection that the query asks the graph to match.

The paper calls the question collection Q and writes q for a question in it. It denotes the entities and relations for that question by E_q and R_q. A generated SPARQL query is s_q, and running it against G yields an answer, denoted by a, which can be empty. The paper expresses single-query generation as a conditional choice.

s_q = arg max_s P_θ(s | C, E_q, R_q, q)

On the left, s_q is the query selected for question q. On the right, s ranges over candidate query sequences, and arg max_s asks for the sequence that maximizes the expression that follows. P_θ is the probability assigned by the pretrained generator with parameters θ. The vertical bar | reads as “given.” The conditions are C, the prompt context containing material such as instructions and demonstrations, E_q and R_q, the supplied entities and relations, and q, the wording itself. The equation describes the target of decoding in terms of sequence probability. The search procedure explores a limited collection of sequences in practice.

Finding a relevant worked example

A solved example in the store contains a question, its entities, its relations, and the corresponding query. Using the paper’s notation, x is a stored question, E_x and R_x are its entities and relations, and s_x is its SPARQL query. The store S is built from the training split of the benchmark under study. The query s_x is saved for use in the demonstration. Retrieval itself measures similarity using the question, entities, and relations.

To obtain the retrieval input, the system joins the question and its supplied graph information into a single piece of text. The paper uses this concatenation for the new question and for each stored example. It is helpful to give the concatenated input a different label from the original question, since the paper uses the question symbol in both senses.

q_joined := [q, E_q, R_q]

Here q_joined is the text sent to the encoder. The brackets denote the sequence of parts being concatenated, with q the natural-language question, E_q its entities, and R_q its relations. For a stored example, the same positions are filled with x, E_x, and R_x. The input thus includes both how a question is phrased and the graph vocabulary that a query for it is expected to use.

The encoder maps this text to a vector, an ordered set of coordinates. The authors use the sentence encoder all-mpnet-base-v2. They write e_q for the vector for the current input and e_x for the vector for a stored example. Both belong to a real-valued space of dimension d, where d is the number of coordinates in the encoder’s output. The paper contrasts its dense representation with the BM25 retrieval used in the related work that inspired its design. In this setup, every example is ranked by comparing the encoded current question and encoded example.

score(q, x) = sim(e_q, e_x), ∀x ∈ S

score(q, x) is the relevance score assigned to example x for question q. The function sim measures similarity between e_q and e_x. The authors use cosine similarity, which compares the directions of the two vectors. The symbol ∀ means that the rule applies to every x, and ∈ indicates that the example belongs to the store S. Once the examples are ranked, the system takes the first k entries, where k is the number of worked examples to insert into the prompt.

The point of including the graph vocabulary at this stage is easier to see in a question that asks for a spouse through a child. A worked example about another family can show that the unknown child should be the object of the child relation and the subject of the spouse relation. An example with comparable wording about a named person may contain neither of those structural clues. The similarity score can give examples with pertinent relations a better chance of appearing in the prompt. It ranks the text associated with examples and leaves the translator to decide how the worked query applies to the current question.

Turning the examples into a prompt

The prompt begins with instructions about the task, the information available, and the expected output format. Then come the retrieved examples. Each shows the example question, its reference entities and relations, and the corresponding SPARQL. The template marks off the examples and puts distinct opening and closing markers around their query text. Finally, the prompt presents the target question and its supplied graph information. The system extracts the generated query from inside the same query markers.

The appendix’s fixed-example prompt shows the range of operations the authors want demonstrations to convey. One worked example asks for companies in Munich and includes a class relationship as well as a location constraint. Another asks about films featuring Leonardo DiCaprio and shows a count of distinct matches. A question about Christian Bale and Batman Begins calls for an ASK query, which tests whether a pattern holds. A further example looks for libraries that meet a date condition. These examples illustrate different decisions a demonstration can support, from how to use a graph property to what form the returned result should take.

The fixed-example baseline presents the same hand-selected examples for every question. DFSL fills the same part of the prompt with examples retrieved anew for the current question. The standard format otherwise carries over. The authors adjust the name of the graph in the instruction for DBpedia, and the experiments that remove gold inputs also remove the corresponding fields and references from the prompt. This keeps the prompt consistent with the information available in each condition.

The training split is therefore used as a source of reference queries and as a retrieval index. The study does not fit new generator weights to these examples. The authors examined retrieval depths of 1, 3, 5, and 7 with Llama-3 70B before setting k to 5 for the subsequent experiments. This choice applies to the number of demonstrations, a different setting from the number of beam candidates considered during decoding. The authors make the study’s DFSL implementation publicly available.

Keeping competing queries from decoding

Beam search keeps several promising partial outputs as decoding progresses. A single-output system can use beam search internally and still return only its highest-ranked completed sequence. In DFSL-MQ, the authors retain the final hypotheses so that query execution can inform the choice among them. Their motivation is that two plausible sequences might differ exactly where the generator is uncertain, such as in which position an unknown person should occupy in a triple.

For a question about an enclave within Montreal, a query has to put Montreal and the unknown enclave at the appropriate ends of the relation. If the top candidate swaps those roles, further candidates can still contain the useful ordering. Keeping those alternatives gives the system a chance to recover only if they differ in a relevant way. Different candidate texts can also express the same mistaken interpretation. The improvement from execution therefore depends on what decoding places in the candidate list.

The setup uses a beam width of 3 for the ordinary in-context configurations and 10 for DFSL-MQ. Let b be the number of retained beam hypotheses in the multi-query description. The paper denotes the query at position j by s_q,j and the answer set from executing it by A_j. Each query is executed against the same graph. The resulting set can be empty. The authors test two rules for using the sets to choose the final answer.

A = arg max_{A_i ∈ {A₁, …, A_b}} |A_i|

A is the chosen answer set under the Largest Set rule, abbreviated LS. A_i is the result set at beam position i, and A₁ through A_b are the available sets from the b hypotheses. The braces enclose that collection, ∈ means that the selected candidate belongs to it, and the ellipsis represents its intervening members. The bars in |A_i| give the number of answers in A_i. The arg max returns the set with the greatest cardinality, with ties resolved by retaining the earliest such set. The rule favors a candidate that finds graph matches, on the expectation that many wrong patterns yield empty results.

The First Set rule, abbreviated FS, considers the candidates in beam order and takes the first answer set that contains a result. That lets a lower-ranked hypothesis supply the answer when earlier hypotheses return empty sets. Once a candidate returns a nonempty set, a later candidate’s larger result gives it no preference. The difference matters when a permissive query retrieves many graph entries by omitting a constraint. LS can favor it for that very reason. FS relies on the model’s ordering to retain some preference for the more plausible translations while using execution to bypass empty returns.

The paper also tests an alternative way to obtain several candidates. In multi-query prompting, the instructions ask the translator to produce multiple queries and explicitly suggest trying versions with subject and object inverted. The candidates are then passed to the same answer selection rules. This comparison asks whether alternative outputs are more useful when the prompt requests them explicitly or when they come from the competing hypotheses the decoder already explored.

Experiments and results

The benchmarks and what the scores mean

The study uses English questions from benchmarks grounded in DBpedia and Wikidata. QALD-9 DB is the paper’s name for the DBpedia benchmark from the Question Answering over Linked Data challenge series. It contains 408 training questions and 150 test questions. QALD-9 plus extends the original collection to additional languages and transfers its queries to Wikidata where the graph supports them. Some queries could not be transferred because corresponding information was unavailable. The resulting benchmark has 371 training questions and 136 test questions. The experiments use its English questions.

QALD-10 also uses Wikidata and was designed to have more complex reference queries. Its 412 training questions come from QALD-9 plus Wikidata. Its 394 test questions were created separately to represent real information needs. The paper emphasizes that the test questions differ markedly from the training questions. This matters because DFSL retrieves from the training split. The split defines both the material available to the method and the kinds of analogy that can reasonably be expected at test time.

LC-QuAD 2.0, used with Wikidata here, contains 30,226 questions, with 24,180 in training and 6,046 in test. Its questions encompass single facts, multiple facts, Boolean tests, and counts. For retrieval, it offers more worked examples and a variety of query structures. A performance comparison between LC-QuAD 2.0 and QALD-10 therefore spans differences in both the amount of training material and how closely that material resembles the test questions. The paper examines the behavior under these existing splits instead of manipulating their composition.

The evaluation compares the result obtained from a generated query with the result obtained from the reference SPARQL for the same question. The authors compute F1 at the question level, then average the scores over examples. F1 balances precision, the share of returned answers that belong in the reference result, with recall, the share of reference answers that were returned. When both queries return empty sets, the paper assigns that question an F1 of 1. This scoring rule gives full credit for agreeing on an empty answer. A query that returns a broad collection containing the right answer can still lose credit for the other entries it includes.

The target of the evaluation is thus what the graph returns. Differences in variable names can leave an answer unchanged, as can other differences between query expressions. Conversely, a query with familiar vocabulary and plausible syntax can score poorly if it returns the wrong variable or sends a graph relation in the wrong direction. Measuring execution makes these distinctions visible at the answer level. The paper uses individual query examples to show how particular construction errors contribute to the aggregate scores.

Generators and comparison conditions

The authors compare Mixtral 8x7B, Llama-3 70B, and CodeLlama 70B. Mixtral is a sparse mixture of experts, with 46.7B parameters in total and fewer than 13B active per inference step. The paper identifies it as the smallest generator in the study. Llama-3 70B was trained on 15T tokens. CodeLlama 70B was initialized from Llama2 70B and adapted with 1T tokens of code-heavy data. That prior specialization makes it a plausible candidate for query generation. The experiments apply no task-specific fine-tuning to it.

The basic comparison changes what the prompt supplies. The plain-question baseline receives the instructions and the question. The zero-shot condition adds the reference entities and relations while leaving out demonstrations. Fixed few-shot prompting adds a hand-picked collection designed to represent different query types. Dynamic few-shot prompting uses the same kind of worked examples but selects them for the target question. These settings let the authors distinguish the gain associated with supplying graph vocabulary from the gain associated with showing how that vocabulary can be turned into queries.

The multi-query comparison starts from dynamic retrieval. It compares the single-output DFSL condition with beam candidates and with the explicit instruction to generate several queries. Each multi-query source is tried with LS and FS. Finally, the paper places the in-context scores alongside published results for task-specialized systems such as SGPT and TSET. A cluster equipped with four NVIDIA A100 GPUs handled the in-context experiments. The comparison reports answer quality, with the tuning and inference configurations described separately from the scores.

How much the demonstrations help

Llama-3 70B had the strongest zero-shot score of the tested generators on every benchmark. Its test answer F1 values in that condition were 63.01 on QALD-9 plus, 58.31 on QALD-10, 54.21 on LC-QuAD 2.0, and 70.49 on QALD-9 DB. Those prompts already supplied entities and relations. The result shows which generator made the strongest use of this prompt under the study’s conditions. It cannot tell from the scores alone how much derives from general sequence generation, familiarity with SPARQL, or prior exposure to benchmark content.

The ranking changes when examples are selected dynamically. CodeLlama 70B gives the strongest DFSL results and is therefore used for the subsequent comparisons. LC-QuAD 2.0 shows the change particularly clearly. Llama-3 70B scores 68.52 with the fixed few-shot prompt, above CodeLlama 70B at 64.46 and Mixtral 8x7B at 61.04. With dynamic selection, CodeLlama 70B reaches 85.45, Llama-3 70B reaches 81.93, and Mixtral 8x7B reaches 81.81. The change in ordering is a reason to evaluate the generator with the intended prompt strategy. A strong result with bare instructions and graph links does not identify the strongest pairing with retrieved examples.

CodeLlama 70B prompting strategies on LC-QuAD 2.0 test answer F1

Retrieved examples give the highest score among the single-query prompting settings.

CodeLlama 70B prompting strategies on LC-QuAD 2.0 test answer F1Zero-shot with gold graph links: 38.40Zero-shot with gold graph links38.40Fixed few-shot: 64.46Fixed few-shot64.46Dynamic few-shot (this paper): 85.45Dynamic few-shot (this paper)85.45
The numbers
System or settingF1
Zero-shot with gold graph links38.40
Fixed few-shot64.46
Dynamic few-shot (this paper)85.45

On Wikidata’s QALD-9 plus, CodeLlama 70B moves from 45.94 in the zero-shot setting to 64.49 with fixed examples and 76.59 with retrieved examples. The other generators follow the same progression on that split. Mixtral 8x7B has scores of 49.90, 54.80, and 71.75 in those respective settings. Llama-3 70B has 63.01, 67.69, and 73.60. The result on this benchmark is therefore shared across the generators, although their initial scores and their response to the prompt differ.

On QALD-9 DB, CodeLlama 70B scores 66.43 in the zero-shot condition, 72.67 with fixed examples, and 75.14 with dynamic selection. The fixed prompt is less helpful for the other generators on this benchmark. With Llama-3 70B the zero-shot score is 70.49 and fixed few-shot gives 68.84, followed by 72.66 with DFSL. Mixtral 8x7B records 65.73, 63.86, and 72.74 in the same order. The fixed examples are chosen to show a range of forms. Showing that range to every question can have a different effect from giving each question a small, relevant subset of the benchmark’s examples.

QALD-10 is the clearest exception to the pattern of substantial gains from dynamic selection. CodeLlama 70B gives 57.38 with fixed demonstrations and 57.69 with retrieved ones. Mixtral 8x7B gives 50.26 with the fixed prompt and 49.90 with retrieval. Llama-3 70B improves from 51.28 to 56.59 when switching from fixed to retrieved examples, while its zero-shot score is 58.31. The authors connect the weaker retrieval advantage to the difference between QALD-10’s training and test questions. A ranking procedure can select the best examples it has access to while still finding little that is structurally useful for a particular question. The paper does not report a statistical test for the differences in this comparison.

What changes when several queries are executed

For CodeLlama 70B, the First Set rule applied to final beam hypotheses gives the highest score among the paper’s in-context configurations on each benchmark. It reaches 84.45 on QALD-9 plus, where single-query DFSL scores 76.59. It reaches 62.20 on QALD-10, where single-query DFSL scores 57.69. On LC-QuAD 2.0 the corresponding scores are 89.10 and 85.45. On QALD-9 DB they are 77.89 and 75.14. These comparisons measure the combined change from the single-query setting to the wider search with execution-based selection.

The explicit multi-query prompt gives a different pattern. On QALD-10, its Largest Set result is 58.85 and its First Set result is 58.34, both above single-query DFSL at 57.69. On QALD-9 plus, the two explicit-prompt scores are 73.67 and 74.40. On LC-QuAD 2.0 they are 85.06 and 85.38. On QALD-9 DB they are 73.25 and 73.92. In those cases, both rules give lower scores with explicitly requested queries than the corresponding single-query DFSL run. Merely having several queries to execute is insufficient. The way the alternatives are obtained affects whether the selection rule has a good candidate available.

When the alternatives come from beam search, FS performs better than LS on each benchmark. On QALD-9 plus the beam LS result is 83.21, while on QALD-10 it is 60.48. On LC-QuAD 2.0 it is 85.54. The DBpedia result shows why the selector deserves attention in its own right. Beam LS on QALD-9 DB scores 72.06, below single-query DFSL at 75.14. Beam FS, operating on the candidate source with the other rule, gives 77.89. Extra hypotheses give the system more opportunities to recover, while a heuristic that favors larger answer sets can put those same opportunities to poor use.

Query generation and answer selection on QALD-9 DB test answer F1

First Set with beam candidates is the strongest setting, while Largest Set with beam candidates falls below single-query DFSL.

Query generation and answer selection on QALD-9 DB test answer F1Single-query DFSL: 75.14Single-query DFSL75.14Explicit multi-query prompt with Largest Set: 73.25Explicit multi-query prompt with LargestSet73.25Explicit multi-query prompt with First Set: 73.92Explicit multi-query prompt with FirstSet73.92Beam candidates with Largest Set: 72.06Beam candidates with Largest Set72.06Beam candidates with First Set (this paper): 77.89Beam candidates with First Set (thispaper)77.89
The numbers
System or settingF1
Single-query DFSL75.14
Explicit multi-query prompt with Largest Set73.25
Explicit multi-query prompt with First Set73.92
Beam candidates with Largest Set72.06
Beam candidates with First Set (this paper)77.89

The QALD-10 results also separate the contribution of retrieving demonstrations from the performance of the combined system. Replacing fixed examples with retrieved ones gives little improvement for CodeLlama 70B on that benchmark. Keeping beam candidates and using First Set produces a higher score from the dynamic prompt. The score supports using execution to choose among candidates under this setup. It leaves open how well the same decoding and selection procedure would work with the fixed prompt, since the paper’s multi-query comparison starts from DFSL.

Comparison with task-specialized systems

The strongest in-context scores exceed the published task-specialized scores in the paper’s comparison on QALD-9 plus, QALD-10, and QALD-9 DB. On QALD-9 plus, TSET-base scores 75.85 and TSET-small scores 72.86. CodeLlama 70B with single-query DFSL scores 76.59, and the beam First Set configuration scores 84.45. On QALD-10, the reported TSET-base score is 51.37 and TSET-small scores 47.15. The CodeLlama 70B single-query and multi-query scores are 57.69 and 62.20. In both cases the single-query result already exceeds the strongest specialized result listed.

For QALD-9 DB, the table reports 67.82 for SGPT, alongside 75.14 for single-query DFSL and 77.89 for the beam First Set configuration. The published comparison is sparse on that benchmark, with several cells left unreported. The authors’ strongest DBpedia result can be read against the listed value, and the within-study prompt comparisons give a fuller picture of when the approach helped.

LC-QuAD 2.0 changes the ranking. This benchmark has the broadest set of specialized comparisons in the paper’s table. BART scores 64.00, PGN-BERT-BERT scores 86.00, and SGPT scores 89.04. The beam First Set configuration reaches 89.10. TSET-small and TSET-base score 94.00 and 95.00, respectively. The authors describe LC-QuAD 2.0 as the benchmark most affected by triple flips. The increase from single-query DFSL to the multi-query setting shows recovery at the level of answer F1, while the specialized results show how much performance still depends on the benchmark and the method used to address query structure.

In-context and task-specialized systems on LC-QuAD 2.0 test answer F1

Beam-based selection improves on single-query DFSL, while the TSET variants score higher.

In-context and task-specialized systems on LC-QuAD 2.0 test answer F1BART: 64.00BART64.00PGN-BERT-BERT: 86.00PGN-BERT-BERT86.00SGPT: 89.04SGPT89.04Single-query DFSL: 85.45Single-query DFSL85.45DFSL with beam candidates and First Set (this paper): 89.10DFSL with beam candidates and First Set(this paper)89.10TSET-small: 94.00TSET-small94.00TSET-base: 95.00TSET-base95.00
The numbers
System or settingF1
BART64.00
PGN-BERT-BERT86.00
SGPT89.04
Single-query DFSL85.45
DFSL with beam candidates and First Set (this paper)89.10
TSET-small94.00
TSET-base95.00

The plain-question scores for CodeLlama 70B put the main comparison in perspective. With the task instruction and question alone, it scores 0.08 on QALD-9 plus, 0.02 on QALD-10, 12.00 on LC-QuAD 2.0, and 16.42 on QALD-9 DB. Adding reference entities and relations brings it to the zero-shot scores of 45.94, 33.36, 38.40, and 66.43 on those respective benchmarks. The no-fine-tuning result comes from a system with structured inputs, solved examples, and access to a query engine. The plain-question condition shows the difficulty of relying on the translator’s existing knowledge to supply the graph vocabulary as well as the query.

What the ablations show

What information should the retriever see?

The authors vary the text encoded for example retrieval. In the full system, the encoder sees the question, the entities, and the relations. In the alternative, it sees only the question. This is an intervention on which examples are brought into the prompt. It is different from removing the entity and relation fields from the translator’s input. A reader can therefore attribute the comparison to a change in what information guides example selection, while recognizing that the measured outcome still depends on how well the translator uses the examples it receives.

The paper reports that query quality improves when the supplied graph information is encoded, across the backbones and benchmarks included in its comparison. The comparison is presented as a figure, and the authors discuss the direction of the effect. The finding supports selecting examples in part on the basis of the graph terms they use. A question may be semantically close in ordinary prose but call for a different property or pattern once expressed in the graph. Including graph terms allows the retriever to reflect those distinctions in the ordering of examples. The experiment evaluates that input choice with the encoder and similarity measure held fixed.

There is a practical difference between retrieval and query composition in this ablation. The encoder’s additional input can help it find a solved case that contains the relevant graph property. The demonstration then shows that property in use, potentially in a position the translator can carry over. The relevance score itself does not determine whether to copy that position. Its benefit is measured through the final answer, after the translator and the graph engine have each played their part.

A separate ablation removes reference entities, relations, or both throughout DFSL. For instance, when the entities are removed, the retrieval text for each record contains the question and relations, and the prompt drops the entity fields. The demonstration queries are still supplied as worked outputs. This design approximates a pipeline in which a category of linked input is absent. It alters retrieval and prompting together, so the effect captures the loss at both stages.

On QALD-9 DB, full DFSL gives 75.14 test answer F1. The configuration without supplied relations gives 56.62, and the one without supplied entities gives 60.92. Without either kind of reference information, it gives 49.59. On QALD-9 plus, full DFSL scores 76.59. Removing relations gives 49.47, removing entities gives 31.83, and removing both gives 26.16. The ordering of the individual removals differs across the graphs and benchmark instances. The relation removal has the lower score on QALD-9 DB, while entity removal has the lower score on QALD-9 plus.

This comparison provides a stronger basis for saying that both sorts of input matter than for declaring either universally more important. The test sets differ, as do the graphs and their query vocabularies. Removing an input changes the information available for finding analogies, and it also changes what the translator must infer for the target query. The study does not cross those effects in a way that apportions the losses. The question-only retrieval variant isolates one part of the system, while the full removal experiment measures the overall consequences of the missing information.

In both benchmarks, demonstrations remain useful after removing the entity and relation fields. The reference-free DFSL score on QALD-9 DB is 49.59 compared with the plain-question score of 16.42. On QALD-9 plus it is 26.16 compared with 0.08. In the retrieval setting, the translator can still see example queries containing concrete graph vocabulary and structural patterns. The plain-question prompt supplies neither the worked queries nor the target’s reference links. These results show that worked examples can carry information about the query language and graph conventions even when the target input lacks explicit links. The remaining difference from full DFSL shows how important the target-specific links are.

How many demonstrations help?

The authors vary k, the number of retrieved demonstrations, using Llama-3 70B on the benchmarks. They test 1, 3, 5, and 7. For the smaller benchmark collections, the settings above 1 perform comparably in the authors’ account. On LC-QuAD 2.0, increasing the number appears more helpful. The authors suggest that with a large training store, expanding the shortlist can yield additional examples that resemble the target. They adopt 5 as a common setting for the subsequent experiments.

This comparison examines the quantity of retrieved context under a particular ranking method. It does not establish an optimum across generators or encoders. An additional demonstration can expose a different construction or reinforce a useful one. Its position below the existing retrieved examples also means the ranking judged it less similar. The experiment shows how those effects play out over the examined prompt lengths. QALD-10 illustrates why the underlying training collection matters. A longer shortlist drawn from a dissimilar set of questions can still offer few good analogies.

What the actual queries reveal

The paper’s qualitative comparison of fixed and retrieved examples identifies improvements that go beyond writing well-formed SPARQL. In the question about the spouse of Robert Kennedy’s daughter, the fixed prompt leads to a pattern with the parent–child relation in the wrong direction and the wrong variable selected. The dynamic prompt retrieves an example that goes from a parent to a child and from the child to a spouse. The generated query uses that chain and retains the constraint identifying the daughter. The example shows how a retrieved demonstration can supply the placement of variables as well as the relevant succession of relations.

In a question about countries associated with the Rhine, the generated pattern must bind a country through the river and also constrain that answer to be a country. The version with the fixed prompt reverses the key relation. The retrieved example itself uses a different graph path, but it contains a relevant way of moving through a location relation. The dynamic output places the river and the country variable in the expected roles. For the capitals of African countries, the distinction is between finding the countries and returning their capitals. The fixed-example output selects the country variable. The output given retrieved examples keeps the country as an intermediate binding and selects the capital. Its demonstration likewise uses a country as an intermediate step to a capital.

The multi-query examples illuminate the separate route through beam search. In the Montreal example, the single-query result sends the enclave relation in the opposite direction to the reference. The selected multi-query output restores the ordering of Montreal and the unknown enclave. A question about the anatomical branch associated with the trachea shows the opposite placement change on a different property. The paper also shows a question about the revolution connected to the Russian Empire, where the multi-query result brings the fixed entity and requested variable into the positions used in the reference. These cases demonstrate that useful alternatives can exist in the beam. They do not measure how frequently any particular error type appears in the full test set.

The appendix also shows how answer selection can introduce an error after the decoder has produced a suitable query. In a question about the manufacturer of the NEC PC-9800 series in the electronics sector, the Largest Set rule chooses a query that follows an additional relation and returns a type associated with a match. First Set selects a query that returns the matching manufacturer. For a question about a place within an administrative area, the Largest Set choice relaxes a constraint involving a particular graph entry, allowing the search to return a broader collection. First Set preserves the more specific pattern. In the potassium hydroxide example, Largest Set chooses an ASK query involving a different entity, while First Set retrieves the property value for the intended entity. Together these cases show the ways a candidate can look successful to an execution heuristic and still answer the wrong question.

Limitations

Limits the authors state

The study is confined to English. QALD-9 plus includes more languages, but the experiments use only the English questions. The authors note that the language of evaluation is favorable for the generators they study and leave multilingual evaluation for future work. The results therefore provide evidence about retrieving demonstrations and generating queries for English questions under the tested conditions. They give no direct measurement of how well the same retrieval procedure would find examples across languages or handle graph labels expressed differently in different languages.

The authors also raise possible benchmark contamination from web-scale pretraining. They specifically suggest that prior exposure could help explain Llama-3 70B’s strong zero-shot results and leave the question open. This possibility concerns the data seen before the benchmark experiment, which is separate from the use of training-split examples during retrieval. The DFSL procedure retrieves from the designated training split, but that protocol cannot establish the contents of the generator’s original pretraining data. The performance pattern gives a reason to investigate exposure. It does not demonstrate that exposure occurred or determine its effect on the comparison.

The study uses large generators. Mixtral’s sparse computation gives the experiments a different architecture and lower active parameter count than the other backbones, but the authors leave smaller systems unexamined. The comparison among the selected generators therefore supports claims about those systems and prompt conditions. It does not establish how much generator capacity is needed to recognize a structural analogy in a demonstration or to produce useful alternative queries in a beam.

The representation ablation also has a narrow scope. The authors test which text to encode, using the question by itself or the question with its entities and relations. They leave alternative encoders, similarity measures, and arrangements of the input text for future work. The success of including graph vocabulary supports that choice in the reported implementation. It cannot settle whether another encoder would make question-only retrieval more competitive or whether a different arrangement would make the supplied relations easier to use.

Finally, the authors identify additional languages and potentially private knowledge graphs as directions for extending the investigation. The experiments span DBpedia and Wikidata, with each benchmark’s own examples available for retrieval. They do not establish what happens when the graph vocabulary is unfamiliar and there are few solved examples to show its conventions. The existing comparison provides evidence across two graph environments under conditions where each has benchmark data.

Limits that follow from the design

The main scores are conditional on accurate entity and relation linking. In a full question-answering pipeline, the linker can return ambiguous, incomplete, or wrong identifiers. The removal ablation tests entire categories of input being absent. A wrong identifier is a different condition. It could give the retriever a reason to favor misleading examples, then give the translator a plausible but incorrect graph entry to copy. Missing information and incorrect information can therefore affect the system in different ways. The paper measures the former in its ablations and leaves the latter without a direct result.

The multi-query comparison changes the decoding width as well as the use of execution results. The single-query configuration uses a beam width of 3, and DFSL-MQ uses 10. Its higher scores measure the joint effect of a wider search, retaining the terminal hypotheses, and applying a selection rule. The FS-versus-LS comparison within beam generation more directly isolates the rule. The reported setup does not show how much of the gain would remain if the single-query configuration used the wider beam and still returned only its top candidate. It also does not provide the rate at which the correct answer was present somewhere in the retained beam but missed by both heuristics.

The execution rules depend on observable properties of answer sets with limited connection to correctness. An empty return can be the expected outcome of a well-formed question, as the evaluation’s treatment of matching empty sets acknowledges. FS prefers a candidate that returns something. Where the reference result is empty, such a preference can work against agreement with the reference. A nonempty set can also contain plausible answers to a different query. LS is especially vulnerable to losing constraints because that can enlarge the result, but FS can also stop on a wrong nonempty answer before reaching a better candidate. The appendix illustrates particular recoveries and failures, instead of counting their frequency.

Answer F1 measures agreement after execution on the available graph. A generated query can agree with the reference answer for the data currently present while imposing a different condition or relying on a different connection. It might then diverge from the reference if the graph contained additional facts. Conversely, a query can differ in harmless surface details and still retrieve the intended result. The study’s metric is suited to testing the answers a system actually returns. It provides less information about structural equivalence between queries, and the qualitative cases help fill that gap for individual examples.

The comparison with specialized systems combines the authors’ in-context runs with published benchmark scores, several of which are missing for particular datasets. It supports the reported rankings where the comparison exists. The study reports the inference hardware and configurations, but gives no comparative latency or cost result for the systems in the table. Retrieving demonstrations, processing longer prompts, decoding a wider beam, and executing multiple queries all add work at inference time. The experiments establish that the generator can reach the reported answer scores without task-specific weight updates. They do not establish the total cost of reaching those scores compared with training and serving a specialized translator.

The retrieval experiments use the training store supplied by each benchmark. LC-QuAD 2.0 has a larger store and shows strong gains from retrieval, while QALD-10 has a distinct test distribution and relatively modest gains from replacing fixed examples. These are different benchmarks, with different question and query characteristics. The results are consistent with the authors’ explanation that a useful analogy needs to be present in the store. The benchmark comparison alone cannot isolate the effect of store size from the effect of its coverage of test-time structures.

What came after

CypherSmith (2026) cites the study and addresses translation into Cypher, another graph query language. Its title identifies synthetic data as its approach to text-to-query generation. The connection is the problem of turning a natural-language request into an executable graph query and the role that data can play in supporting that translation. D’Abramo and colleagues retrieve solved benchmark examples at inference time. CypherSmith concerns the use of synthetic data for generation in a different query language. The citation and title establish that connection, while leaving open whether CypherSmith adopted dynamic demonstration retrieval, beam-based answer selection, or any other specific part of the SPARQL pipeline.

Cite

Cite as Jacopo D'Abramo, Andrea Zugarini and Paolo Torroni. 2025. Investigating Large Language Models for Text-to-SPARQL Generation. Proceedings of the 4th International Workshop on Knowledge-Augmented Methods for Natural Language Processing.

The paper itself, not this page. BibTeX from the library's record of the work. DOI 10.18653/v1/2025.knowledgenlp-1.5

@inproceedings{dabramo2025investigating,
  title = {{Investigating Large Language Models for Text-to-SPARQL Generation}},
  author = {Jacopo D'Abramo, Andrea Zugarini and Paolo Torroni},
  booktitle = {Proceedings of the 4th International Workshop on Knowledge-Augmented Methods for Natural Language Processing},
  year = {2025},
  doi = {10.18653/v1/2025.knowledgenlp-1.5},
  url = {https://doi.org/10.18653/v1/2025.knowledgenlp-1.5}
}

↑ back to top

This page in Markdown https://md.research.elamur.ai/free/en/papers/abramo-2025-investigating-large-language-models-text/