Find answers from the community

Updated 3 months ago

How to parse the response object of LlamaIndex so as to obtain the document ids, the sourc

How to parse the response object of LlamaIndex so as to obtain the document ids, the source text and the similarity scores of those sources with the query?
k
u
3 comments
Please stand by @datum as I search the knowledge base. We are experiencing especially high traffic right now and might take longer than usual. :wave:
----------------------
To parse the response object of LlamaIndex and obtain the document ids, the source text, and the similarity scores of those sources with the query, you can use the response.source_nodes attribute of the response object. This attribute contains a list of nodes that contributed to the response. Each node in this list is an instance of the NodeWithScore class, which includes the document id, the source text, and the similarity score among other attributes.

Here is an example of how you can parse the response:

Plain Text
response = query_engine.query("<query_str>")

# get sources
source_nodes = response.source_nodes

# iterate over the source nodes
for node in source_nodes:
    # get the document id
    doc_id = node.node.doc_id
    # get the source text
    text = node.node.text
    # get the similarity score
    similarity = node.score

    print(f"Document ID: {doc_id}, Text: {text}, Similarity: {similarity}")


In this example, query_engine is an instance of a query engine, and <query_str> is the query string.

Please note that the NodeWithScore class is part of the llama_index.data_structs.node module, and the query method is part of the QueryEngine class in the llama_index.query_engine module.

For more information, you can refer to the LlamaIndex documentation ().
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------
The response object has a method get_formatted_sources that shows you what you're looking for. For the similarity score you can manually iterate over response.source_nodes and access each score as node.score
Add a reply
Sign up and join the conversation on Discord