Skip to main content

Pydantic модели для протокола Алисы.

Project description

AliceTypes

Библиотека моделей Pydantic-V2 для валидации протокола Я.Диалогов

Установка:

pip install alice-types

Использование

Пример с FastApi
from alice_types.response import AliceResponse
from alice_types.request import AliceRequest
from fastapi import FastAPI

app = FastAPI()


@app.post(path="/")
async def handler(alice_request: AliceRequest):
    reply = AliceResponse()

    if alice_request.is_new_session():
        reply.response.text = "Привет, скажи что-нибудь и я это повторю"
        return reply

    reply.response.text = alice_request.request.original_utterance
    return reply
Пример с AIOHttp
from alice_types.response import AliceResponse
from alice_types.request import AliceRequest
from aiohttp import web


async def handler(request):
    body = await request.json()
    alice_request = AliceRequest.model_validate(body)

    reply = AliceResponse()

    if alice_request.is_new_session():
        reply.response.text = "Привет, скажи что-нибудь и я это повторю"
    else:
        reply.response.text = alice_request.request.original_utterance

    body = reply.model_dump()
    return web.json_response(body)


app = web.Application()
app.router.add_post('/', handler)

if __name__ == "__main__":
    web.run_app(app)

Расширение типов полей

В библиотеке имеются модели с динамически расширяемыми полями:

  • request.State
    • State.extend_session_model(model: BaseModel)
    • State.extend_user_model(model: BaseModel)
    • State.extend_application_model(model: BaseModel)
  • request.RequestPurchase.payload
    • RequestPurchase.extend_payload_model(model: BaseModel)

Ограничение размера хранилищ для модели ответа

В модели AliceResponse по умолчанию установлен стандартный размер хранилищ (1 КБ), который можно изменить при необходимости:

from alice_types.response import AliceResponse

AliceResponse.set_session_state_limit_size(1024 * 8)
AliceResponse.set_user_state_limit_size(1024 * 16)
AliceResponse.set_application_state_limit_size(1024 * 32)

Публичные методы

AliceRequest
  • AliceRequest.is_ping()
  • AliceRequest.is_new_session()
  • AliceRequest.authorization_is_completed()
from alice_types.response import AliceResponse, Response
from alice_types.request import AliceRequest


async def handler(alice_request: AliceRequest):
    if alice_request.is_ping():
        return AliceResponse(
            response=Response(
                text="pong"
            )
        )
    
    elif alice_request.is_new_session():
        return AliceResponse(
            response=Response(
                text="Привет, скажи что-нибудь и я это повторю"
            )
        )
    
    elif alice_request.authorization_is_completed():
        return AliceResponse(
            response=Response(
                text="Ты авторизован это хорошо 👍"
            )
        )
    ...
AliceRequest.request.nlu.entities
  • entities.get(entity_type: SlotsType | str) - Возвращает список сущностей заданного типа.
  • entity.available() - Возвращает список доступных атрибутов объекта, у которых значение не равно None. Метод доступен у всех сущностей.
  • EntityDatetime.to_datetime(timezone: pytz.BaseTzInfo | str | None = None)
from typing import List

from alice_types.request import AliceRequest, SlotsType, EntityFio, EntityDatetime


async def handler(alice_request: AliceRequest):
    fio_entities: List[EntityFio] = alice_request.request.nlu.entities.get(SlotsType.YANDEX_FIO)
    names = []
    for entity in fio_entities:
        if "first_name" in entity.value.available():
            names.append(entity.value.first_name)

    dates = []
    datetime_entities: List[EntityDatetime] = alice_request.request.nlu.entities.get(SlotsType.YANDEX_DATETIME)
    for entity in datetime_entities:
        dates.append(
            entity.to_datetime(
                timezone=alice_request.meta.timezone  # Default: None
            )
        )
    ...
AliceRequest.request.meta.interfaces
  • interfaces.has(interface: Union[InterfaceType, str]) - Проверяет, существует ли этот интерфейс.
  • interfaces.available() - Возвращает список доступных интерфейсов.
from alice_types.request import AliceRequest, InterfaceType


async def handler(alice_request: AliceRequest):
    if alice_request.meta.interfaces.has(InterfaceType.SCREEN):
        pass

Примеры

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

alice-types-1.0.1.tar.gz (21.0 kB view details)

Uploaded Source

Built Distribution

alice_types-1.0.1-py3-none-any.whl (27.1 kB view details)

Uploaded Python 3

File details

Details for the file alice-types-1.0.1.tar.gz.

File metadata

  • Download URL: alice-types-1.0.1.tar.gz
  • Upload date:
  • Size: 21.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.6

File hashes

Hashes for alice-types-1.0.1.tar.gz
Algorithm Hash digest
SHA256 d42a272e57b2b3fb8f4b044f3dab1388a1074a4bbb35f6551748465c043bb103
MD5 c3ff861866b8b8bf306860b4132a5274
BLAKE2b-256 23989dbab5750bda043aeb2951286e8d81596dab4e6e2ad501d1437229bf78a6

See more details on using hashes here.

File details

Details for the file alice_types-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: alice_types-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 27.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.6

File hashes

Hashes for alice_types-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 cf093a29600284f93029d105e941e533f257bbb2b78862e3a0838690a5f6abca
MD5 06cc9368ea98dbdbaa1c80f283a8a772
BLAKE2b-256 bf7bb7cc4f933bdf1e3c5a14c2cf1739eae251da9b062a7d365d076f8759a4c4

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page