-
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
16 changed files
with
198 additions
and
88 deletions.
There are no files selected for viewing
This file contains 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,16 @@ | ||
if __name__ == '__main__': | ||
from googleapiclient.discovery import build | ||
import pprint | ||
|
||
my_api_key = os.environ.get("GOOGLE_API_KEY") | ||
my_cse_id = os.environ.get("GOOGLE_CSE_ID") | ||
|
||
def google_search(search_term, api_key, cse_id, **kwargs): | ||
service = build("customsearch", "v1", developerKey=api_key) | ||
res = service.cse().list(q=search_term, cx=cse_id, **kwargs).execute() | ||
return res['items'] | ||
|
||
results = google_search( | ||
'stackoverflow site:en.wikipedia.org', my_api_key, my_cse_id, num=10) | ||
for result in results: | ||
pprint.pprint(result) |
This file contains 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 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 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,48 @@ | ||
#!/usr/bin/env python3 | ||
# -*- coding: utf-8 -*- | ||
|
||
""" | ||
@project: HsPyLib-AskAI | ||
@package: askai.utils | ||
@file: cache_service.py | ||
@created: Tue, 16 Jan 2024 | ||
@author: <B>H</B>ugo <B>S</B>aporetti <B>J</B>unior" | ||
@site: https://github.com/yorevs/hspylib | ||
@license: MIT - Please refer to <https://opensource.org/licenses/MIT> | ||
Copyright·(c)·2024,·HSPyLib | ||
""" | ||
import logging as log | ||
import os | ||
from typing import List, Optional | ||
|
||
from hspylib.core.metaclass.singleton import Singleton | ||
from langchain_community.utilities import GoogleSearchAPIWrapper | ||
from langchain_core.tools import Tool | ||
|
||
|
||
class InternetService(metaclass=Singleton): | ||
"""Provide a internet search service used to complete queries that require realtime data.ß""" | ||
|
||
INSTANCE: 'InternetService' = None | ||
|
||
ASKAI_INTERNET_DATA_KEY = "askai-internet-data" | ||
|
||
def __init__(self): | ||
self._search = GoogleSearchAPIWrapper() | ||
self._tool = Tool( | ||
name="google_search", description="Search Google for recent results.", func=self._search.run, | ||
) | ||
|
||
def _top_results(self, query: str, max_results: int = 5) -> List[str]: | ||
"""TODO""" | ||
return self._search.results(query, max_results) | ||
|
||
def search(self, query: str) -> Optional[str]: | ||
"""TODO""" | ||
search_results = self._tool.run(query) | ||
log.debug(f"Internet search returned: %s", search_results) | ||
return os.linesep.join(search_results) if isinstance(search_results, list) else search_results | ||
|
||
|
||
assert (internet := InternetService().INSTANCE) is not None |
This file contains 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 was deleted.
Oops, something went wrong.
This file contains 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,15 @@ | ||
import json | ||
from dataclasses import dataclass | ||
from typing import List | ||
|
||
|
||
@dataclass | ||
class SearchResult: | ||
"""Keep track of the internet search responses.""" | ||
|
||
query: str = None | ||
urls: str | List[str] = None | ||
results: str = None | ||
|
||
def __str__(self): | ||
return f"Internet search results: {json.dumps(self.__dict__, default=lambda obj: obj.__dict__)}" |
This file contains 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 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 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 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,63 @@ | ||
#!/usr/bin/env python3 | ||
# -*- coding: utf-8 -*- | ||
|
||
""" | ||
@project: HsPyLib-AskAI | ||
@package: askai.core.processor | ||
@file: generic_processor.py | ||
@created: Fri, 23 Feb 2024 | ||
@author: <B>H</B>ugo <B>S</B>aporetti <B>J</B>unior" | ||
@site: https://github.com/yorevs/hspylib | ||
@license: MIT - Please refer to <https://opensource.org/licenses/MIT> | ||
Copyright·(c)·2024,·HSPyLib | ||
""" | ||
import logging as log | ||
from typing import Tuple, Optional, List | ||
|
||
from langchain_core.prompts import PromptTemplate | ||
|
||
from askai.core.askai_messages import msg | ||
from askai.core.askai_prompt import prompt | ||
from askai.core.component.cache_service import cache | ||
from askai.core.component.internet_service import internet | ||
from askai.core.model.query_response import QueryResponse | ||
from askai.core.model.search_result import SearchResult | ||
from askai.core.processor.ai_processor import AIProcessor | ||
from askai.core.support.object_mapper import object_mapper | ||
from askai.core.support.shared_instances import shared | ||
|
||
|
||
class InternetProcessor(AIProcessor): | ||
"""Process generic prompts.""" | ||
|
||
def __init__(self): | ||
super().__init__('internet-prompt', 'internet-persona') | ||
|
||
def process(self, query_response: QueryResponse) -> Tuple[bool, Optional[str]]: | ||
status = False | ||
output = None | ||
template = PromptTemplate(input_variables=['user'], template=self.template()) | ||
final_prompt: str = msg.translate(template.format(user=prompt.user)) | ||
shared.context.set("SETUP", final_prompt, 'system') | ||
shared.context.set("QUESTION", query_response.question) | ||
context: List[dict] = shared.context.get_many("SETUP", "QUESTION") | ||
log.info("Setup::[INTERNET] '%s' context=%s", query_response.question, context) | ||
try: | ||
if not (response := cache.read_reply(query_response.question)): | ||
if (response := shared.engine.ask(context, temperature=0.0, top_p=0.0)) and response.is_success: | ||
search_result: SearchResult = object_mapper.of_json(response.message, SearchResult) | ||
if results := internet.search(search_result.query): | ||
search_result.results = results | ||
output = str(search_result) | ||
shared.context.set("INTERNET", output, 'assistant') | ||
cache.save_reply(query_response.question, output) | ||
status = True | ||
else: | ||
output = msg.llm_error(response.message) | ||
else: | ||
log.debug('Reply found for "%s" in cache.', query_response.question) | ||
output = response | ||
status = True | ||
finally: | ||
return status, output |
Oops, something went wrong.