Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,9 @@ uv run mkdocs build --strict
Сервис принимает только `calendar.create_event`. Для готового предложения нужны `title`, `startAt`,
`endAt` и `timeZone`. Доступны `fake-calendar` и `google-calendar`; demo-модель выбирает Google, если
клиент передал его в `availableConnectors`, иначе использует fake. Если полей не хватает, ответ
содержит `clarification`, а `proposal` остаётся `null`. Готовое предложение всегда содержит
`requiresApproval: true`.
содержит `clarification`, а `proposal` остаётся `null`. Если модель не распознала действие или
выбрала недоступный коннектор, пользователь получает просьбу описать задачу снова. Готовое
предложение всегда содержит `requiresApproval: true`.

Внешний запрос использует поля `text`, `timeZone` и `availableConnectors`. Проверенная копия схемы
лежит в `contracts/agent-runtime-api.yaml`; безопасное обновление выполняет
Expand Down
3 changes: 2 additions & 1 deletion docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@ Completions API и проверяет JSON-ответ через внутрен

Разрешено только действие `calendar.create_event` через `fake-calendar` или `google-calendar`.
Обязательны название, начало, конец и часовой пояс. Результат содержит либо `proposal`, либо
`clarification`; обе части могут быть `null`, если модель не нашла действие или коннектор недоступен.
`clarification`. Если модель не нашла действие или коннектор недоступен, сервис возвращает
`clarification` с просьбой описать задачу ещё раз.
Создание встречи всегда требует явного подтверждения в `action-service`.

Публичный API соответствует `portable-agent/contracts` версии `3.0.0`. Поля называются `text`,
Expand Down
17 changes: 13 additions & 4 deletions src/portable_agent/services/proposal_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,11 @@ def __init__(self, model: IntentModel, policy: PolicyRepository) -> None:
async def propose(self, text: str, context: UserContext) -> ProposalResult:
reply = await self._model.propose(text, context)
if reply is None:
return ProposalResult()
return _unsupported_reply()
if reply.kind != "calendar.create_event":
return ProposalResult()
return _unsupported_reply()
if reply.connector not in context.available_tools:
return ProposalResult()
return _unsupported_reply()

missing_fields = _get_missing_fields(reply.payload)
if missing_fields:
Expand All @@ -37,7 +37,7 @@ async def propose(self, text: str, context: UserContext) -> ProposalResult:
try:
event = CalendarEvent.model_validate(reply.payload)
except ValidationError:
return ProposalResult()
return _unsupported_reply()

risk = await self._policy.get_risk(reply, context)
return ProposalResult(
Expand Down Expand Up @@ -78,3 +78,12 @@ def _get_question(missing_fields: list[str]) -> str:
names = [_FIELD_NAMES[field] for field in missing_fields]
fields_text = names[0] if len(names) == 1 else f"{', '.join(names[:-1])} и {names[-1]}"
return f"Укажи {fields_text} встречи."


def _unsupported_reply() -> ProposalResult:
return ProposalResult(
clarification=Clarification(
question="Не удалось распознать задачу. Опиши, что нужно сделать.", # noqa: RUF001
missing_fields=[],
)
)
14 changes: 9 additions & 5 deletions tests/test_proposal_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,13 +74,17 @@ async def test_propose_incomplete_calendar_event_returns_clarification() -> None


@pytest.mark.asyncio
async def test_propose_when_model_returns_no_call_returns_none() -> None:
async def test_propose_when_model_returns_no_call_returns_clarification() -> None:
service = ProposalService(FakeModel(None), FakePolicy(Risk.LOW))

result = await service.propose("Привет", context("fake-calendar"))

assert result.proposal is None
assert result.clarification is None
assert result.clarification is not None
assert result.clarification.question == (
"Не удалось распознать задачу. Опиши, что нужно сделать."
)
assert result.clarification.missing_fields == []


@pytest.mark.asyncio
Expand All @@ -101,7 +105,7 @@ async def test_propose_when_connector_unavailable_rejects_proposal() -> None:
result = await service.propose("Создай встречу", context("google-calendar"))

assert result.proposal is None
assert result.clarification is None
assert result.clarification is not None


@pytest.mark.asyncio
Expand All @@ -117,7 +121,7 @@ async def test_propose_when_action_is_not_allowed_returns_empty_result() -> None
result = await service.propose("Переведи деньги", context("wallet"))

assert result.proposal is None
assert result.clarification is None
assert result.clarification is not None


@pytest.mark.asyncio
Expand Down Expand Up @@ -191,4 +195,4 @@ async def test_propose_when_calendar_payload_is_invalid_returns_empty_result(
result = await service.propose("Создай встречу", context("fake-calendar"))

assert result.proposal is None
assert result.clarification is None
assert result.clarification is not None
6 changes: 3 additions & 3 deletions uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading