-
Notifications
You must be signed in to change notification settings - Fork 10
feat: web search #119
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
Merged
Merged
feat: web search #119
Changes from all commits
Commits
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
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
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 |
|---|---|---|
| @@ -0,0 +1,96 @@ | ||
| import asyncio | ||
| import logging | ||
| from typing import List | ||
|
|
||
| from duckduckgo_search import DDGS | ||
| from fastapi import HTTPException, status | ||
|
|
||
| from nilai_common.api_model import Source | ||
| from nilai_common import Message | ||
| from nilai_common.api_model import EnhancedMessages, WebSearchContext | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| def perform_web_search_sync(query: str) -> WebSearchContext: | ||
| """Synchronously query DuckDuckGo and build a contextual prompt. | ||
|
|
||
| The function sends *query* to DuckDuckGo, extracts the first three text results, | ||
| formats them in a single prompt, and returns that prompt together with the | ||
| metadata (URL and snippet) of every result. | ||
| """ | ||
| if not query or not query.strip(): | ||
| raise HTTPException( | ||
| status_code=status.HTTP_400_BAD_REQUEST, | ||
| detail="Web search requested with an empty query", | ||
| ) | ||
|
|
||
| try: | ||
| with DDGS() as ddgs: | ||
| raw_results = list(ddgs.text(query, max_results=3, region="us-en")) | ||
|
|
||
| if not raw_results: | ||
| raise HTTPException( | ||
| status_code=status.HTTP_503_SERVICE_UNAVAILABLE, | ||
| detail="Web search failed, service currently unavailable", | ||
| ) | ||
|
|
||
| snippets: List[str] = [] | ||
| sources: List[Source] = [] | ||
|
|
||
| for result in raw_results: | ||
| if result.get("title") and result.get("body"): | ||
| title = result["title"] | ||
| body = result["body"][:500] | ||
| snippets.append(f"{title}: {body}") | ||
| sources.append(Source(source=result["href"], content=body)) | ||
|
|
||
| prompt = ( | ||
| "You have access to the following current information from web search:\n" | ||
| + "\n".join(snippets) | ||
| ) | ||
|
|
||
| return WebSearchContext(prompt=prompt, sources=sources) | ||
|
|
||
| except HTTPException: | ||
| raise | ||
| except Exception as exc: | ||
| logger.error("Error performing web search: %s", exc) | ||
| raise HTTPException( | ||
| status_code=status.HTTP_503_SERVICE_UNAVAILABLE, | ||
| detail="Web search failed, service currently unavailable", | ||
| ) from exc | ||
|
|
||
|
|
||
| async def get_web_search_context(query: str) -> WebSearchContext: | ||
| """Non-blocking wrapper around *perform_web_search_sync*.""" | ||
| loop = asyncio.get_running_loop() | ||
| return await loop.run_in_executor(None, perform_web_search_sync, query) | ||
|
|
||
|
|
||
| async def enhance_messages_with_web_search( | ||
| messages: List[Message], query: str | ||
| ) -> EnhancedMessages: | ||
| ctx = await get_web_search_context(query) | ||
| enhanced = [Message(role="system", content=ctx.prompt)] + messages | ||
| return EnhancedMessages(messages=enhanced, sources=ctx.sources) | ||
|
|
||
|
|
||
| async def handle_web_search(req_messages: List[Message]) -> EnhancedMessages: | ||
| """Handle web search for the given messages. | ||
|
|
||
| Only the last user message is used as the query. | ||
| """ | ||
|
|
||
| user_query = "" | ||
| for message in reversed(req_messages): | ||
| if message.role == "user": | ||
| user_query = message.content | ||
| break | ||
blefo marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| if not user_query: | ||
| return EnhancedMessages(messages=req_messages, sources=[]) | ||
| try: | ||
| return await enhance_messages_with_web_search(req_messages, user_query) | ||
| except Exception: | ||
| return EnhancedMessages(messages=req_messages, sources=[]) | ||
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
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
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
jcabrero marked this conversation as resolved.
Show resolved
Hide resolved
|
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.
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.