-
Notifications
You must be signed in to change notification settings - Fork 32
✨ Introduce chatbot client (⚠️) #8516
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
matusdrobuliak66
merged 17 commits into
ITISFoundation:master
from
matusdrobuliak66:introduce-chatbot-client
Oct 15, 2025
Merged
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
945ca4f
introudce chatbot client skeleton
matusdrobuliak66 3972828
introudce chatbot client skeleton
matusdrobuliak66 f5f8b9f
fix
matusdrobuliak66 99968ce
Merge branch 'master' into introduce-chatbot-client
matusdrobuliak66 81dcbe4
improve
matusdrobuliak66 910f649
modify docker compose
matusdrobuliak66 e18dcb9
review @GitHK
matusdrobuliak66 fdad989
review @pcrespov
matusdrobuliak66 0cbd54e
review @pcrespov
matusdrobuliak66 a8bb667
review @pcrespov
matusdrobuliak66 7397e6e
fix
matusdrobuliak66 fa97066
fix
matusdrobuliak66 3bbc3f9
fix
matusdrobuliak66 6f6e332
fix
matusdrobuliak66 51fd6c5
Merge branch 'master' into introduce-chatbot-client
matusdrobuliak66 82740f3
review @pcrespov
matusdrobuliak66 6a2dd0a
Merge branch 'master' into introduce-chatbot-client
matusdrobuliak66 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
Some comments aren't visible on the classic Files Changed page.
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 |
|---|---|---|
|
|
@@ -144,6 +144,7 @@ DYNAMIC_SCHEDULER_UI_STORAGE_SECRET=adminadmin | |
|
|
||
| FUNCTION_SERVICES_AUTHORS='{"UN": {"name": "Unknown", "email": "[email protected]", "affiliation": "unknown"}}' | ||
|
|
||
| WEBSERVER_CHATBOT={} | ||
| WEBSERVER_LICENSES={} | ||
| WEBSERVER_FOGBUGZ={} | ||
| LICENSES_ITIS_VIP_SYNCER_ENABLED=false | ||
|
|
||
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
matusdrobuliak66 marked this conversation as resolved.
Show resolved
Hide resolved
|
Empty file.
138 changes: 138 additions & 0 deletions
138
services/web/server/src/simcore_service_webserver/chatbot/_client.py
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,138 @@ | ||
| import logging | ||
| from typing import Annotated, Any, Final | ||
|
|
||
| import httpx | ||
| from aiohttp import web | ||
| from pydantic import BaseModel, Field | ||
| from servicelib.aiohttp import status | ||
| from servicelib.mimetype_constants import MIMETYPE_APPLICATION_JSON | ||
| from tenacity import ( | ||
| retry, | ||
| retry_if_exception_type, | ||
| retry_if_result, | ||
| stop_after_attempt, | ||
| wait_exponential, | ||
| ) | ||
|
|
||
| from .settings import ChatbotSettings, get_plugin_settings | ||
|
|
||
| _logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class ChatResponse(BaseModel): | ||
| answer: Annotated[str, Field(description="Answer from the chatbot")] | ||
|
|
||
|
|
||
| def _should_retry(response: httpx.Response | None) -> bool: | ||
| if response is None: | ||
| return True | ||
| return ( | ||
| response.status_code >= status.HTTP_500_INTERNAL_SERVER_ERROR | ||
| or response.status_code == status.HTTP_429_TOO_MANY_REQUESTS | ||
| ) | ||
|
|
||
|
|
||
| _CHATBOT_RETRY = retry( | ||
| retry=( | ||
| retry_if_result(_should_retry) | ||
| | retry_if_exception_type( | ||
| ( | ||
| httpx.ConnectError, | ||
| httpx.TimeoutException, | ||
| httpx.NetworkError, | ||
| httpx.ProtocolError, | ||
| ) | ||
| ) | ||
| ), | ||
| stop=stop_after_attempt(3), | ||
| wait=wait_exponential(multiplier=1, min=1, max=10), | ||
| reraise=True, | ||
| ) | ||
|
|
||
|
|
||
| class ChatbotRestClient: | ||
| def __init__(self, chatbot_settings: ChatbotSettings) -> None: | ||
| self._client = httpx.AsyncClient() | ||
| self._chatbot_settings = chatbot_settings | ||
|
|
||
| async def get_settings(self) -> dict[str, Any]: | ||
| """Fetches chatbot settings""" | ||
| url = httpx.URL(self._chatbot_settings.base_url).join("/v1/chat/settings") | ||
|
|
||
| @_CHATBOT_RETRY | ||
| async def _request() -> httpx.Response: | ||
| return await self._client.get(url) | ||
|
|
||
| try: | ||
| response = await _request() | ||
| response.raise_for_status() | ||
| response_data: dict[str, Any] = response.json() | ||
| return response_data | ||
| except Exception: | ||
| _logger.error( # noqa: TRY400 | ||
matusdrobuliak66 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| "Failed to fetch chatbot settings from %s", url | ||
| ) | ||
| raise | ||
|
|
||
| async def ask_question(self, question: str) -> ChatResponse: | ||
matusdrobuliak66 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| """Asks a question to the chatbot""" | ||
| url = httpx.URL(self._chatbot_settings.base_url).join("/v1/chat") | ||
|
|
||
| @_CHATBOT_RETRY | ||
| async def _request() -> httpx.Response: | ||
| return await self._client.post( | ||
| url, | ||
| json={ | ||
| "question": question, | ||
matusdrobuliak66 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| "llm": self._chatbot_settings.CHATBOT_LLM_MODEL, | ||
| "embedding_model": self._chatbot_settings.CHATBOT_EMBEDDING_MODEL, | ||
| }, | ||
| headers={ | ||
| "Content-Type": MIMETYPE_APPLICATION_JSON, | ||
| "Accept": MIMETYPE_APPLICATION_JSON, | ||
| }, | ||
| ) | ||
|
|
||
| try: | ||
| response = await _request() | ||
| response.raise_for_status() | ||
| return ChatResponse.model_validate(response.json()) | ||
| except Exception: | ||
| _logger.error( # noqa: TRY400 | ||
| "Failed to ask question to chatbot at %s", url | ||
matusdrobuliak66 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| ) | ||
| raise | ||
|
|
||
| async def __aenter__(self): | ||
| """Async context manager entry""" | ||
| return self | ||
|
|
||
| async def __aexit__(self, exc_type, exc_val, exc_tb): | ||
| """Async context manager exit - cleanup client""" | ||
| await self._client.aclose() | ||
matusdrobuliak66 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
|
|
||
| _APPKEY: Final = web.AppKey(ChatbotRestClient.__name__, ChatbotRestClient) | ||
matusdrobuliak66 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
|
|
||
| async def setup_chatbot_rest_client(app: web.Application) -> None: | ||
| chatbot_settings = get_plugin_settings(app) | ||
|
|
||
| client = ChatbotRestClient( | ||
| chatbot_settings=chatbot_settings, | ||
| ) | ||
|
|
||
| app[_APPKEY] = client | ||
|
|
||
| # Add cleanup on app shutdown | ||
| async def cleanup_chatbot_client(app: web.Application) -> None: | ||
| client = app.get(_APPKEY) | ||
| if client: | ||
| await client._client.aclose() # pylint: disable=protected-access # noqa: SLF001 | ||
|
|
||
| app.on_cleanup.append(cleanup_chatbot_client) | ||
matusdrobuliak66 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
|
|
||
| def get_chatbot_rest_client(app: web.Application) -> ChatbotRestClient: | ||
| app_key: ChatbotRestClient = app[_APPKEY] | ||
matusdrobuliak66 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| return app_key | ||
7 changes: 7 additions & 0 deletions
7
services/web/server/src/simcore_service_webserver/chatbot/chatbot_service.py
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,7 @@ | ||
| # mypy: disable-error-code=truthy-function | ||
| from ._client import ChatbotRestClient, get_chatbot_rest_client | ||
|
|
||
| __all__ = [ | ||
| "get_chatbot_rest_client", | ||
| "ChatbotRestClient", | ||
| ] |
20 changes: 20 additions & 0 deletions
20
services/web/server/src/simcore_service_webserver/chatbot/plugin.py
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,20 @@ | ||
| import logging | ||
|
|
||
| from aiohttp import web | ||
|
|
||
| from ..application_setup import ModuleCategory, app_setup_func | ||
| from ..products.plugin import setup_products | ||
| from ._client import setup_chatbot_rest_client | ||
|
|
||
| _logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| @app_setup_func( | ||
| __name__, | ||
| ModuleCategory.ADDON, | ||
| settings_name="WEBSERVER_CHATBOT", | ||
| logger=_logger, | ||
| ) | ||
| def setup_chatbot(app: web.Application): | ||
| setup_products(app) | ||
| app.on_startup.append(setup_chatbot_rest_client) |
34 changes: 34 additions & 0 deletions
34
services/web/server/src/simcore_service_webserver/chatbot/settings.py
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,34 @@ | ||
| from functools import cached_property | ||
|
|
||
| from aiohttp import web | ||
| from models_library.basic_types import PortInt | ||
| from pydantic_settings import SettingsConfigDict | ||
| from settings_library.base import BaseCustomSettings | ||
| from settings_library.utils_service import MixinServiceSettings, URLPart | ||
|
|
||
| from ..application_keys import APP_SETTINGS_APPKEY | ||
|
|
||
|
|
||
| class ChatbotSettings(BaseCustomSettings, MixinServiceSettings): | ||
| model_config = SettingsConfigDict(str_strip_whitespace=True, str_min_length=1) | ||
|
|
||
| CHATBOT_HOST: str | ||
matusdrobuliak66 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| CHATBOT_PORT: PortInt | ||
| CHATBOT_LLM_MODEL: str = "gpt-3.5-turbo" | ||
matusdrobuliak66 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| CHATBOT_EMBEDDING_MODEL: str = "openai/text-embedding-3-large" | ||
|
|
||
| @cached_property | ||
| def base_url(self) -> str: | ||
| # http://chatbot:8000 | ||
| return self._compose_url( | ||
| prefix="CHATBOT", | ||
| port=URLPart.REQUIRED, | ||
| vtag=URLPart.EXCLUDE, | ||
| ) | ||
|
|
||
|
|
||
| def get_plugin_settings(app: web.Application) -> ChatbotSettings: | ||
| settings = app[APP_SETTINGS_APPKEY].WEBSERVER_CHATBOT | ||
matusdrobuliak66 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| assert settings, "plugin.setup_chatbot not called?" # nosec | ||
| assert isinstance(settings, ChatbotSettings) # nosec | ||
| return settings | ||
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
72 changes: 72 additions & 0 deletions
72
services/web/server/tests/unit/with_dbs/04/test_chatbot_client.py
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,72 @@ | ||
| # pylint: disable=redefined-outer-name | ||
| # pylint: disable=unused-argument | ||
| # pylint: disable=unused-variable | ||
| # pylint: disable=too-many-arguments | ||
| # pylint: disable=too-many-statements | ||
|
|
||
| from collections.abc import Iterator | ||
|
|
||
| import httpx | ||
| import pytest | ||
| import respx | ||
| from aiohttp.test_utils import TestClient | ||
| from pytest_simcore.helpers.monkeypatch_envs import setenvs_from_dict | ||
| from pytest_simcore.helpers.typing_env import EnvVarsDict | ||
| from simcore_service_webserver.chatbot._client import ( | ||
| ChatResponse, | ||
| get_chatbot_rest_client, | ||
| ) | ||
| from simcore_service_webserver.chatbot.settings import ChatbotSettings | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def app_environment( | ||
matusdrobuliak66 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| monkeypatch: pytest.MonkeyPatch, | ||
| app_environment: EnvVarsDict, | ||
| ): | ||
| return app_environment | setenvs_from_dict( | ||
| monkeypatch, | ||
| { | ||
| "CHATBOT_HOST": "chatbot", | ||
| "CHATBOT_PORT": "8000", | ||
| }, | ||
| ) | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def mocked_chatbot_api() -> Iterator[respx.MockRouter]: | ||
| _BASE_URL = "http://chatbot:8000" | ||
|
|
||
| # Define responses in the order they will be called during the test | ||
| chatbot_answer_responses = [ | ||
| {"answer": "42"}, | ||
| ] | ||
|
|
||
| with respx.mock(base_url=_BASE_URL) as mock: | ||
| # Create a side_effect that returns responses in sequence | ||
| mock.post(path="/v1/chat").mock( | ||
| side_effect=[ | ||
| httpx.Response(200, json=response) | ||
| for response in chatbot_answer_responses | ||
| ] | ||
| ) | ||
| yield mock | ||
|
|
||
|
|
||
| async def test_chatbot_client( | ||
| app_environment: EnvVarsDict, | ||
| client: TestClient, | ||
| mocked_chatbot_api: respx.MockRouter, | ||
| ): | ||
| assert client.app | ||
|
|
||
| settings = ChatbotSettings.create_from_envs() | ||
| assert settings.CHATBOT_HOST | ||
| assert settings.CHATBOT_PORT | ||
|
|
||
| chatbot_client = get_chatbot_rest_client(client.app) | ||
| assert chatbot_client | ||
|
|
||
| output = await chatbot_client.ask_question("What is the meaning of life?") | ||
| assert isinstance(output, ChatResponse) | ||
| assert output.answer == "42" | ||
matusdrobuliak66 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
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.