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
7 changes: 5 additions & 2 deletions homeassistant/components/almond/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from datetime import timedelta
import logging
import time
from typing import Optional

import async_timeout
from aiohttp import ClientSession, ClientError
Expand Down Expand Up @@ -205,9 +206,11 @@ def __init__(self, api: WebAlmondAPI):
"""Initialize the agent."""
self.api = api

async def async_process(self, text: str) -> intent.IntentResponse:
async def async_process(
self, text: str, conversation_id: Optional[str] = None
) -> intent.IntentResponse:
"""Process a sentence."""
response = await self.api.async_converse_text(text)
response = await self.api.async_converse_text(text, conversation_id)

buffer = ""
for message in response["messages"]:
Expand Down
14 changes: 9 additions & 5 deletions homeassistant/components/conversation/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,22 +53,22 @@ def async_set_agent(hass: core.HomeAssistant, agent: AbstractConversationAgent):
async def async_setup(hass, config):
"""Register the process service."""

async def process(hass, text):
async def process(hass, text, conversation_id):
"""Process a line of text."""
agent = hass.data.get(DATA_AGENT)

if agent is None:
agent = hass.data[DATA_AGENT] = DefaultAgent(hass)
await agent.async_initialize(config)

return await agent.async_process(text)
return await agent.async_process(text, conversation_id)

async def handle_service(service):
"""Parse text into commands."""
text = service.data[ATTR_TEXT]
_LOGGER.debug("Processing: <%s>", text)
try:
await process(hass, text)
await process(hass, text, service.context.id)
except intent.IntentHandleError as err:
_LOGGER.error("Error processing %s: %s", text, err)

Expand All @@ -91,13 +91,17 @@ def __init__(self, process):
"""Initialize the conversation process view."""
self._process = process

@RequestDataValidator(vol.Schema({vol.Required("text"): str}))
@RequestDataValidator(
vol.Schema({vol.Required("text"): str, vol.Optional("conversation_id"): str})
)
async def post(self, request, data):
"""Send a request for processing."""
hass = request.app["hass"]

try:
intent_result = await self._process(hass, data["text"])
intent_result = await self._process(
hass, data["text"], data.get("conversation_id")
)
except intent.IntentHandleError as err:
intent_result = intent.IntentResponse()
intent_result.async_set_speech(str(err))
Expand Down
5 changes: 4 additions & 1 deletion homeassistant/components/conversation/agent.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Agent foundation for conversation integration."""
from abc import ABC, abstractmethod
from typing import Optional

from homeassistant.helpers import intent

Expand All @@ -8,5 +9,7 @@ class AbstractConversationAgent(ABC):
"""Abstract conversation agent."""

@abstractmethod
async def async_process(self, text: str) -> intent.IntentResponse:
async def async_process(
self, text: str, conversation_id: Optional[str] = None
) -> intent.IntentResponse:
"""Process a sentence."""
5 changes: 4 additions & 1 deletion homeassistant/components/conversation/default_agent.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Standard conversastion implementation for Home Assistant."""
import logging
import re
from typing import Optional

from homeassistant import core
from homeassistant.components.cover import INTENT_CLOSE_COVER, INTENT_OPEN_COVER
Expand Down Expand Up @@ -107,7 +108,9 @@ def register_utterances(self, component):
for intent_type, sentences in UTTERANCES[component].items():
async_register(self.hass, intent_type, sentences)

async def async_process(self, text) -> intent.IntentResponse:
async def async_process(
self, text: str, conversation_id: Optional[str] = None
) -> intent.IntentResponse:
"""Process a sentence."""
intents = self.hass.data[DOMAIN]

Expand Down
14 changes: 12 additions & 2 deletions tests/components/conversation/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -266,11 +266,14 @@ async def test_http_api_wrong_data(hass, hass_client):
async def test_custom_agent(hass, hass_client):
"""Test a custom conversation agent."""

calls = []

class MyAgent(conversation.AbstractConversationAgent):
"""Test Agent."""

async def async_process(self, text):
async def async_process(self, text, conversation_id):
"""Process some text."""
calls.append((text, conversation_id))
response = intent.IntentResponse()
response.async_set_speech("Test response")
return response
Expand All @@ -281,9 +284,16 @@ async def async_process(self, text):

client = await hass_client()

resp = await client.post("/api/conversation/process", json={"text": "Test Text"})
resp = await client.post(
"/api/conversation/process",
json={"text": "Test Text", "conversation_id": "test-conv-id"},
)
assert resp.status == 200
assert await resp.json() == {
"card": {},
"speech": {"plain": {"extra_data": None, "speech": "Test response"}},
}

assert len(calls) == 1
assert calls[0][0] == "Test Text"
assert calls[0][1] == "test-conv-id"