-
Notifications
You must be signed in to change notification settings - Fork 57
implements referenced documents on /query and updates /streaming_query to match #403
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
thoraxe
wants to merge
18
commits into
lightspeed-core:main
Choose a base branch
from
thoraxe:query-referenced-docs
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
f022501
implements referenced documents on /query
thoraxe 8c0a1d0
code rabbit fixes and additional tests
thoraxe d6e1475
formatting
thoraxe 866bb5c
more coderabbit changes
thoraxe 3026397
coderabbit changes
thoraxe d5e2622
more coderabbit
thoraxe a7f815e
more coderabbit
thoraxe af646c6
π°
thoraxe 06cba91
fixes in-place modification issue
thoraxe 1f8fbb9
codrabbit test change requests
thoraxe 1256193
fixes some issues with tests
thoraxe 1fa7b87
avoid brittle equality
thoraxe dcf4f23
Merge branch 'main' into query-referenced-docs
thoraxe 12becc5
coderabbit
thoraxe 0291e11
coderabbit
thoraxe a463e6f
coderabbit
thoraxe 36a5604
Merge branch 'main' into query-referenced-docs
thoraxe 622ae9d
fix lint
thoraxe File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,11 +1,13 @@ | ||
| """Handler for REST API call to provide answer to query.""" | ||
|
|
||
| import ast | ||
| from datetime import datetime, UTC | ||
| import json | ||
| import logging | ||
| import os | ||
| from pathlib import Path | ||
| from typing import Annotated, Any | ||
| import re | ||
| from typing import Annotated, Any, cast | ||
|
|
||
| from llama_stack_client import APIConnectionError | ||
| from llama_stack_client import AsyncLlamaStackClient # type: ignore | ||
|
|
@@ -41,10 +43,79 @@ | |
| router = APIRouter(tags=["query"]) | ||
| auth_dependency = get_auth_dependency() | ||
|
|
||
| METADATA_PATTERN = re.compile(r"\nMetadata: (\{.+})\n") | ||
|
|
||
|
|
||
| def _process_knowledge_search_content( | ||
| tool_response: Any, metadata_map: dict[str, dict[str, Any]] | ||
| ) -> None: | ||
|
||
| """Process knowledge search tool response content for metadata.""" | ||
| for text_content_item in tool_response.content: | ||
| if not hasattr(text_content_item, "text"): | ||
| continue | ||
|
|
||
| for match in METADATA_PATTERN.findall(text_content_item.text): | ||
| try: | ||
| meta = ast.literal_eval(match) | ||
| if "document_id" in meta: | ||
| metadata_map[meta["document_id"]] = meta | ||
| except Exception: # pylint: disable=broad-except | ||
| logger.debug( | ||
| "An exception was thrown in processing %s", | ||
| match, | ||
| ) | ||
|
|
||
coderabbitai[bot] marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| def extract_referenced_documents_from_steps(steps: list) -> list[dict[str, str]]: | ||
| """Extract referenced documents from tool execution steps. | ||
|
|
||
| Args: | ||
| steps: List of response steps from the agent | ||
|
|
||
| Returns: | ||
| List of referenced documents with doc_url and doc_title | ||
| """ | ||
| metadata_map: dict[str, dict[str, Any]] = {} | ||
|
|
||
| for step in steps: | ||
| if step.step_type != "tool_execution" or not hasattr(step, "tool_responses"): | ||
| continue | ||
|
|
||
| for tool_response in step.tool_responses: | ||
| if ( | ||
| tool_response.tool_name != "knowledge_search" | ||
| or not tool_response.content | ||
| ): | ||
| continue | ||
|
|
||
| _process_knowledge_search_content(tool_response, metadata_map) | ||
|
|
||
| # Extract referenced documents from metadata | ||
| return [ | ||
| { | ||
| "doc_url": v["docs_url"], | ||
| "doc_title": v["title"], | ||
| } | ||
| for v in filter( | ||
| lambda v: ("docs_url" in v) and ("title" in v), | ||
| metadata_map.values(), | ||
| ) | ||
| ] | ||
|
|
||
|
|
||
| query_response: dict[int | str, dict[str, Any]] = { | ||
| 200: { | ||
| "conversation_id": "123e4567-e89b-12d3-a456-426614174000", | ||
| "response": "LLM answer", | ||
| "referenced_documents": [ | ||
| { | ||
| "doc_url": ( | ||
| "https://docs.openshift.com/container-platform/" | ||
| "4.15/operators/olm/index.html" | ||
| ), | ||
| "doc_title": "Operator Lifecycle Manager (OLM)", | ||
| } | ||
| ], | ||
| }, | ||
| 400: { | ||
| "description": "Missing or invalid credentials provided by client", | ||
|
|
@@ -189,7 +260,7 @@ async def query_endpoint_handler( | |
| user_conversation=user_conversation, query_request=query_request | ||
| ), | ||
| ) | ||
| response, conversation_id = await retrieve_response( | ||
| response, conversation_id, referenced_documents = await retrieve_response( | ||
| client, | ||
| llama_stack_model_id, | ||
| query_request, | ||
|
|
@@ -223,7 +294,11 @@ async def query_endpoint_handler( | |
| provider_id=provider_id, | ||
| ) | ||
|
|
||
| return QueryResponse(conversation_id=conversation_id, response=response) | ||
| return QueryResponse( | ||
| conversation_id=conversation_id, | ||
| response=response, | ||
| referenced_documents=referenced_documents, | ||
| ) | ||
|
|
||
| # connection to Llama Stack server | ||
| except APIConnectionError as e: | ||
|
|
@@ -322,7 +397,7 @@ async def retrieve_response( # pylint: disable=too-many-locals | |
| query_request: QueryRequest, | ||
| token: str, | ||
| mcp_headers: dict[str, dict[str, str]] | None = None, | ||
| ) -> tuple[str, str]: | ||
| ) -> tuple[str, str, list[dict[str, str]]]: | ||
| """Retrieve response from LLMs and agents.""" | ||
| available_input_shields = [ | ||
| shield.identifier | ||
|
|
@@ -402,15 +477,24 @@ async def retrieve_response( # pylint: disable=too-many-locals | |
| toolgroups=toolgroups, | ||
| ) | ||
|
|
||
| # Check for validation errors in the response | ||
| # Check for validation errors and extract referenced documents | ||
| steps = getattr(response, "steps", []) | ||
| for step in steps: | ||
| if step.step_type == "shield_call" and step.violation: | ||
| # Metric for LLM validation errors | ||
| metrics.llm_calls_validation_errors_total.inc() | ||
| break | ||
|
|
||
| return str(response.output_message.content), conversation_id # type: ignore[union-attr] | ||
| # Extract referenced documents from tool execution steps | ||
| referenced_documents = extract_referenced_documents_from_steps(steps) | ||
|
|
||
| # When stream=False, response should have output_message attribute | ||
| response_obj = cast(Any, response) | ||
| return ( | ||
| str(response_obj.output_message.content), | ||
| conversation_id, | ||
| referenced_documents, | ||
| ) | ||
|
|
||
|
|
||
| def validate_attachments_metadata(attachments: list[Attachment]) -> None: | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.