Replies: 1 comment 1 reply
-
To show the metadata of the document found at the end of the response when generating a stream with
Here's an example of how you can do this: Step 1: Extract MetadataEnsure you have a function to extract metadata from the search results: export function _getMetadata<T extends ContentsOptions = { text: true }>(
result: SearchResult<T>
): Record<string, unknown> {
const newMetadata: Record<string, unknown> = { ...result };
delete newMetadata.text;
return newMetadata;
}
async _getRelevantDocuments(query: string): Promise<Document[]> {
const res: SearchResponse<T> = await this.client.searchAndContents<T>(
query,
this.searchArgs
);
const documents: Document[] = [];
for (const result of res.results) {
let pageContent;
if ("text" in result) {
pageContent = result.text;
} else if ("highlights" in result) {
pageContent = result.highlights.join("\n\n");
} else {
pageContent = "No results found.";
}
documents.push(
new Document({
pageContent,
metadata: _getMetadata<T>(result),
})
);
}
return documents;
} Step 2: Include Metadata in StreamModify your stream handling to include the metadata in the output: const retriever = await loadedVectorStore.asRetriever();
const retrievalChain = await createRetrievalChain({
combineDocsChain,
retriever,
returnSourceDocuments: true, // Ensure source documents are returned
});
const response = await retrievalChain.stream({ input: "Where is London?" });
for await (const chunk of response) {
if (chunk?.answer) {
console.log(chunk.answer);
}
if (chunk?.sourceDocuments) {
chunk.sourceDocuments.forEach((doc) => {
console.log(doc.metadata); // Log the metadata of each document
});
}
} This approach ensures that the metadata is included in the |
Beta Was this translation helpful? Give feedback.
-
Checked other resources
Commit to Help
Example Code
Description
If is generate a stream with retrievalChain as in example.
How can I show the metadata of the document found at the end of the response?
System Info
langchain v0.2
llama cpp
Beta Was this translation helpful? Give feedback.
All reactions