Skip to content

Commit

Permalink
fix example
Browse files Browse the repository at this point in the history
  • Loading branch information
20081984 authored and 20081984 committed Feb 13, 2024
1 parent 79a2152 commit 6d76f04
Show file tree
Hide file tree
Showing 11 changed files with 187 additions and 197 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
class IntegrationRequestMessageName(SmartEnum):
"""Список наименований запросов интеграцию."""

GENERATE_TOKEN = "ECOM_GENERATE_TOKEN_REQUEST"
GENERATE_DATA = "GENERATE_DATA_REQUEST"


class IntegrationResponseMessageName(SmartEnum):
"""Список наименований ответов от интеграции."""

GENERATE_TOKEN = "ECOM_GENERATE_TOKEN_RESPONSE"
GENERATE_DATA = "GENERATE_DATA_RESPONSE"
58 changes: 29 additions & 29 deletions nlpf_statemachine/example/app/sc/example_2_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@
IntegrationRequestMessageName, IntegrationResponseMessageName,
)
from nlpf_statemachine.example.app.sc.models.context import ExampleContext
from nlpf_statemachine.example.app.sc.models.token_service_integration import GetTokenPayload, GetTokenRequest
from nlpf_statemachine.example.app.sc.models.integration import GetDataPayload, GetDataRequest
from nlpf_statemachine.kit import Scenario
from nlpf_statemachine.models import AnswerToUser, AssistantMessage, AssistantResponsePayload, Response

# 1. Определяем необходимые параметры.
INTEGRATION_TOPIC_KEY = "food_source"
GET_TOKEN = "GET_TOKEN"
GET_DATA = "GET_DATA"

# 2. Инициализируем сценарий для глобального сценария и отдельную страницу.
scenario = Scenario("IntegrationExample")
Expand All @@ -24,20 +24,20 @@


# 4. Описываем общие методы.
def get_ihapi_token(message: AssistantMessage) -> GetTokenRequest:
def get_ihapi_data(message: AssistantMessage) -> GetDataRequest:
"""
# Метод для генерации запроса в токен-сервис.
Args:
message (AssistantMessage): Запрос от ассистента
Returns:
GetTokenRequest: Запрос в токен-сервис.
GetTokenRequest: Запрос в интеграцию.
"""
return GetTokenRequest(
payload=GetTokenPayload(
return GetDataRequest(
payload=GetDataPayload(
uuid=message.uuid,
projectId=message.payload.app_info.projectId,
project=message.payload.app_info.projectId,
),
request_data={
"topic_key": INTEGRATION_TOPIC_KEY,
Expand All @@ -46,39 +46,39 @@ def get_ihapi_token(message: AssistantMessage) -> GetTokenRequest:


# 5. Добавим обработчики событии и тамйаута.
@scenario.on_event(event=GET_TOKEN)
def get_token_action(message: AssistantMessage, context: ExampleContext) -> Response:
@scenario.on_event(event=GET_DATA)
def get_data_action(message: AssistantMessage, context: ExampleContext) -> Response:
r"""
# Получение токена от TokenService.
# Получение токена от интеграции.
**Событие:** `GET_TOKEN`.
**Событие:** `GET_DATA`.
**Базовое событие:** Отсутствует (начинает транзакцию по получению токена).
Интеграция с токен-сервисом происходит через кафку.
## Возможные следующие шаги транзакции
1. Таймаут: `get_token_timeout_action`;
2. Успешный ответ от интеграции: `get_token_success_action` \n
(событие: `IntegrationResponseMessageName.GENERATE_TOKEN`);
1. Таймаут: `get_data_timeout_action`;
2. Успешный ответ от интеграции: `get_data_success_action` \n
(событие: `IntegrationResponseMessageName.GENERATE_DATA`);
Args:
message (AssistantMessage): Запрос от ассистента
context (ExampleContext): Контекст запроса от ассистента
Returns:
GetTokenRequest: Запрос на получение токена в токен-сервис.
GetTokenRequest: Запрос на получение данны в интеграцию.
"""
context.local.retry_index = 0
return get_ihapi_token(message)
return get_ihapi_data(message)


@scenario.on_timeout(request_name=IntegrationRequestMessageName.GENERATE_TOKEN)
def get_token_timeout_action(message: AssistantMessage, context: ExampleContext) -> Response:
@scenario.on_timeout(request_name=IntegrationRequestMessageName.GENERATE_DATA)
def get_data_timeout_action(message: AssistantMessage, context: ExampleContext) -> Response:
"""
# Таймаут при запросе токена из TokenService.
# Таймаут при запросе данных.
**Событие:** Таймаут на запрос `IntegrationRequestMessageName.GENERATE_TOKEN`.
**Событие:** Таймаут на запрос `IntegrationRequestMessageName.GENERATE_DATA`.
**Базовое событие:** Любое.
Expand All @@ -90,28 +90,28 @@ def get_token_timeout_action(message: AssistantMessage, context: ExampleContext)
context (ExampleContext): Контекст запроса от ассистента
Returns:
GetTokenRequest: Запрос на получение токена в токен-сервис.
GetTokenRequest: Запрос на получение данных в интеграцию.
AnswerToUser: Сообщение об ошибке.
"""
if context.local.retry_index < 1:
context.local.retry_index += 1
return get_ihapi_token(message)
return get_ihapi_data(message)

return AnswerToUser(
payload=AssistantResponsePayload(
pronounceText="К сожалению, произошёл таймаут получения данных от токен-сервиса",
pronounceText="К сожалению, произошёл таймаут получения данных от интеграции",
),
)


@scenario.on_event(event=IntegrationResponseMessageName.GENERATE_TOKEN, base_event=GET_TOKEN)
def get_token_success_action() -> Response:
@scenario.on_event(event=IntegrationResponseMessageName.GENERATE_DATA, base_event=GET_DATA)
def get_data_success_action() -> Response:
"""
# Успешный ответа от TokenService в случае GET_TOKEN.
# Успешный ответ.
**Событие:** `IntegrationResponseMessageName.GENERATE_TOKEN`.
**Событие:** `IntegrationResponseMessageName.GENERATE_DATA`.
**Базовое событие:** `ServerAction.GET_TOKEN`.
**Базовое событие:** `GET_DATA`.
В случае успешного овтета отдаём пользователю голосовй ответ и заканчиваем транзакцию.
Expand All @@ -120,6 +120,6 @@ def get_token_success_action() -> Response:
"""
return AnswerToUser(
payload=AssistantResponsePayload(
pronounceText="Токен получен! Я пришёл от GET_TOKEN",
pronounceText="Токен получен! Я пришёл от GET_DATA",
),
)
10 changes: 5 additions & 5 deletions nlpf_statemachine/example/app/sc/example_5_isolated_scenario.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@
from typing import Optional

from nlpf_statemachine.example.app.sc.enums.integration_message_names import IntegrationResponseMessageName
from nlpf_statemachine.example.app.sc.example_2_integration import get_ihapi_token
from nlpf_statemachine.example.app.sc.example_2_integration import get_ihapi_data
from nlpf_statemachine.example.app.sc.models.context import ExampleContext
from nlpf_statemachine.example.app.sc.models.token_service_integration import GetTokenResponse
from nlpf_statemachine.example.app.sc.models.integration import GetDataResponse
from nlpf_statemachine.kit import ConstClassifier, Scenario
from nlpf_statemachine.models import AssistantMessage, Response

Expand Down Expand Up @@ -68,11 +68,11 @@ def run_app(message: AssistantMessage, context: ExampleContext) -> Response:
GetTokenRequest: Запрос на получение токена в токен-сервис.
"""
context.local.retry_index = 0
return get_ihapi_token(message)
return get_ihapi_data(message)


@scenario.on_event(event=IntegrationResponseMessageName.GENERATE_TOKEN, base_event=RUN_APP)
def get_token_success_action(message: GetTokenResponse, context: ExampleContext) -> Optional[Response]:
@scenario.on_event(event=IntegrationResponseMessageName.GENERATE_DATA, base_event=RUN_APP)
def get_token_success_action(message: GetDataResponse, context: ExampleContext) -> Optional[Response]:
"""
# Успешный ответа от TokenService в случае RUN_APP.
Expand Down
4 changes: 2 additions & 2 deletions nlpf_statemachine/example/app/sc/models/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ class InitCommand(AssistantCommand):

command: str = "INIT"
"""Наименование команды."""
token: str
"""ihapi token."""
data: str
"""data."""


class CustomCommand(AssistantCommand):
Expand Down
4 changes: 2 additions & 2 deletions nlpf_statemachine/example/app/sc/models/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

from pydantic import Field

from nlpf_statemachine.example.app.sc.models.token_service_integration import GetTokenResponseData
from nlpf_statemachine.example.app.sc.models.integration import GetDataResponseData
from nlpf_statemachine.models import Context, LocalContext


Expand All @@ -20,7 +20,7 @@ class ExampleLocalContext(LocalContext):
Контекст создаётся при запуске транзакции и уничтожается при его завершении.
"""

ihapi_token: Optional[GetTokenResponseData] = None
data: Optional[GetDataResponseData] = None
"""Токен ihapi."""
retry_index: Optional[int] = None
"""Количество попыток загрузки данных из интеграции."""
Expand Down
53 changes: 53 additions & 0 deletions nlpf_statemachine/example/app/sc/models/integration.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
"""Описание моделей для интеграции."""
from typing import Optional

from pydantic import BaseModel

from nlpf_statemachine.example.app.sc.enums.integration_message_names import (
IntegrationRequestMessageName, IntegrationResponseMessageName,
)
from nlpf_statemachine.models import UUID, BaseMessage, IntegrationPayload, IntegrationResponse


class GetDataPayload(BaseModel):
"""Payload для запроса данных."""

uuid: UUID
"""UUID текущего запроса."""

project: str
"""Текущий project."""


class GetDataRequest(IntegrationResponse):
"""Описание запроса получения данных."""

messageName: str = IntegrationRequestMessageName.GENERATE_DATA
"""messageName запроса."""

payload: GetDataPayload
"""payload запроса."""


class GetDataResponseData(BaseModel):
"""Основная часть ответа от интеграции."""

data: str
"""Данные."""


class GetDataResponsePayload(IntegrationPayload):
"""Описание payload ответа от интеграции."""

data: Optional[GetDataResponseData]
"""Данные."""


class GetDataResponse(BaseMessage):
"""Описание ответа от интеграции."""

messageName: str = IntegrationResponseMessageName.GENERATE_DATA
"""Наименование (тип) запроса."""

payload: GetDataResponsePayload
"""payload ответа."""

This file was deleted.

2 changes: 1 addition & 1 deletion nlpf_statemachine/example/app/sc/pre_post_process.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def post_process(message: BaseMessage, response: AnswerToUser, context: ExampleC
items = [
generate_item(
smart_app_data=InitCommand(
token=context.local.ihapi_token.accessToken,
data=context.local.data.data,
)),
]

Expand Down
4 changes: 2 additions & 2 deletions nlpf_statemachine/example/app/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from nlpf_statemachine.example.app.sc.enums.integration_message_names import IntegrationResponseMessageName
from nlpf_statemachine.example.app.sc.models.context import ExampleContext
from nlpf_statemachine.example.app.sc.models.message import CustomAssistantMessageServerAction, CustomMessageToSkill
from nlpf_statemachine.example.app.sc.models.token_service_integration import GetTokenResponse
from nlpf_statemachine.example.app.sc.models.integration import GetDataResponse
from nlpf_statemachine.models import BaseMessage, RequestMessageName
from nlpf_statemachine.override import SMUser

Expand All @@ -35,7 +35,7 @@ def message_models(self) -> Dict[str, List[Type[BaseMessage]]]:
models = super(ExampleUser, self).message_models
models[RequestMessageName.MESSAGE_TO_SKILL] = [CustomMessageToSkill]
models[RequestMessageName.SERVER_ACTION] = [CustomAssistantMessageServerAction]
models[IntegrationResponseMessageName.GENERATE_TOKEN] = [GetTokenResponse]
models[IntegrationResponseMessageName.GENERATE_DATA] = [GetDataResponse]
return models

@property
Expand Down
Loading

0 comments on commit 6d76f04

Please sign in to comment.