himring-agent-hooks 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,43 @@
1
+ from .conversation import QUESTIONS_PER_TURN_MAXIMUM, AnswerConversation, SearchResult
2
+ from .delivery import DEFAULT_DELIVERY_ATTEMPTS, HimringRequestError, HimringTarget
3
+ from .events import (
4
+ ANSWER_BATCH_BODY_BUDGET_BYTES,
5
+ ANSWER_EVENTS_PER_REQUEST_MAXIMUM,
6
+ ANSWER_MAXIMUM_LENGTH,
7
+ CITED_CHUNKS_MAXIMUM,
8
+ FOLLOW_UP_MAXIMUM_LENGTH,
9
+ HANDOFF_REASON_MAXIMUM_LENGTH,
10
+ AnswerEventDraft,
11
+ )
12
+ from .recorder import (
13
+ DEFAULT_BUFFER_MAXIMUM,
14
+ DEFAULT_CLOSE_TIMEOUT_SECONDS,
15
+ DEFAULT_FLUSH_INTERVAL_SECONDS,
16
+ AnswerRecorder,
17
+ RecorderSettings,
18
+ default_spool_directory,
19
+ )
20
+ from .spool_files import SPOOL_ORPHAN_AFTER_SECONDS
21
+
22
+ __all__ = [
23
+ "ANSWER_BATCH_BODY_BUDGET_BYTES",
24
+ "ANSWER_EVENTS_PER_REQUEST_MAXIMUM",
25
+ "ANSWER_MAXIMUM_LENGTH",
26
+ "CITED_CHUNKS_MAXIMUM",
27
+ "DEFAULT_BUFFER_MAXIMUM",
28
+ "DEFAULT_CLOSE_TIMEOUT_SECONDS",
29
+ "DEFAULT_DELIVERY_ATTEMPTS",
30
+ "DEFAULT_FLUSH_INTERVAL_SECONDS",
31
+ "FOLLOW_UP_MAXIMUM_LENGTH",
32
+ "HANDOFF_REASON_MAXIMUM_LENGTH",
33
+ "QUESTIONS_PER_TURN_MAXIMUM",
34
+ "SPOOL_ORPHAN_AFTER_SECONDS",
35
+ "AnswerConversation",
36
+ "AnswerEventDraft",
37
+ "AnswerRecorder",
38
+ "HimringRequestError",
39
+ "HimringTarget",
40
+ "RecorderSettings",
41
+ "SearchResult",
42
+ "default_spool_directory",
43
+ ]
@@ -0,0 +1,152 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from collections.abc import Awaitable, Callable, Iterable, Sequence
5
+ from dataclasses import dataclass, field
6
+ from typing import Protocol
7
+
8
+ from .events import ANSWER_MAXIMUM_LENGTH, AnswerEventDraft, bounded_long_text, now_timestamp
9
+
10
+ QUESTIONS_PER_TURN_MAXIMUM = 50
11
+
12
+
13
+ @dataclass(frozen=True, slots=True)
14
+ class SearchResult:
15
+ question_id: str
16
+ chunk_ids: tuple[str, ...]
17
+ passages: tuple[dict[str, object], ...]
18
+
19
+
20
+ class ConversationHost(Protocol):
21
+ def record(self, drafts: Sequence[AnswerEventDraft]) -> None: ...
22
+
23
+ def search(
24
+ self, question: str, limit: int | None, end_user_id: str | None, call_id: str | None
25
+ ) -> Awaitable[SearchResult]: ...
26
+
27
+ def flush(self) -> Awaitable[None]: ...
28
+
29
+
30
+ @dataclass(slots=True)
31
+ class _Turn:
32
+ questions: dict[str, frozenset[str]] = field(default_factory=dict[str, frozenset[str]])
33
+ answer: str = ""
34
+
35
+
36
+ class AnswerConversation:
37
+ def __init__(
38
+ self,
39
+ host: ConversationHost,
40
+ logger: logging.Logger,
41
+ end_user_id: str | None = None,
42
+ call_id: str | None = None,
43
+ ) -> None:
44
+ self._host = host
45
+ self._logger = logger
46
+ self._end_user_id = end_user_id
47
+ self._call_id = call_id
48
+ self._current = _Turn()
49
+ self._answered: _Turn | None = None
50
+
51
+ async def search(self, question: str, limit: int | None = None) -> SearchResult:
52
+ result = await self._host.search(question, limit, self._end_user_id, self._call_id)
53
+ self.remember_search(result.question_id, result.chunk_ids)
54
+ return result
55
+
56
+ def remember_search(self, question_id: str, chunk_ids: Iterable[str]) -> None:
57
+ def remember() -> None:
58
+ if self._current.answer:
59
+ self._start_turn()
60
+ if len(self._current.questions) < QUESTIONS_PER_TURN_MAXIMUM:
61
+ self._current.questions[question_id] = frozenset(chunk_ids)
62
+
63
+ self._guarded("remember a search", remember)
64
+
65
+ def record_answer(self, text: str, cited_chunk_ids: Iterable[str] | None = None) -> None:
66
+ def record() -> None:
67
+ turn = self._current
68
+ piece = bounded_long_text(text, ANSWER_MAXIMUM_LENGTH)
69
+ if not turn.questions or piece is None:
70
+ return
71
+ joined = f"{turn.answer}\n{piece}" if turn.answer else piece
72
+ turn.answer = joined[:ANSWER_MAXIMUM_LENGTH]
73
+ occurred_at = now_timestamp()
74
+ cited = None if cited_chunk_ids is None else tuple(dict.fromkeys(cited_chunk_ids))
75
+ self._host.record(
76
+ [
77
+ AnswerEventDraft(
78
+ question_id=question_id,
79
+ answer=turn.answer,
80
+ occurred_at=occurred_at,
81
+ cited_chunk_ids=None
82
+ if cited is None
83
+ else tuple(chunk for chunk in cited if chunk in returned),
84
+ )
85
+ for question_id, returned in turn.questions.items()
86
+ ]
87
+ )
88
+ self._answered = turn
89
+
90
+ self._guarded("record an answer", record)
91
+
92
+ def record_user_message(self, text: str) -> None:
93
+ def record() -> None:
94
+ if not self._current.answer:
95
+ return
96
+ occurred_at = now_timestamp()
97
+ self._host.record(
98
+ [
99
+ AnswerEventDraft(
100
+ question_id=question_id, follow_up=text, occurred_at=occurred_at
101
+ )
102
+ for question_id in self._current.questions
103
+ ]
104
+ )
105
+ self._start_turn()
106
+
107
+ self._guarded("record a user message", record)
108
+
109
+ def record_thumbs_down(self, question_ids: Iterable[str] | None = None) -> None:
110
+ def record() -> None:
111
+ self._host.record(
112
+ [
113
+ AnswerEventDraft(question_id=question_id, thumbs_down=True)
114
+ for question_id in self._targets(question_ids, include_unanswered=False)
115
+ ]
116
+ )
117
+
118
+ self._guarded("record a thumbs-down", record)
119
+
120
+ def record_handoff(self, reason: str, question_ids: Iterable[str] | None = None) -> None:
121
+ def record() -> None:
122
+ self._host.record(
123
+ [
124
+ AnswerEventDraft(question_id=question_id, handoff_reason=reason)
125
+ for question_id in self._targets(question_ids, include_unanswered=True)
126
+ ]
127
+ )
128
+
129
+ self._guarded("record a handoff", record)
130
+
131
+ async def end(self) -> None:
132
+ await self._host.flush()
133
+
134
+ def _targets(self, question_ids: Iterable[str] | None, include_unanswered: bool) -> list[str]:
135
+ if question_ids is not None:
136
+ return list(question_ids)
137
+ current_counts = (
138
+ bool(self._current.questions) if include_unanswered else bool(self._current.answer)
139
+ )
140
+ turn = self._current if current_counts else self._answered
141
+ return [] if turn is None else list(turn.questions)
142
+
143
+ def _start_turn(self) -> None:
144
+ if self._current.answer:
145
+ self._answered = self._current
146
+ self._current = _Turn()
147
+
148
+ def _guarded(self, action: str, work: Callable[[], None]) -> None:
149
+ try:
150
+ work()
151
+ except Exception:
152
+ self._logger.warning("The answer recorder could not %s", action, exc_info=True)
@@ -0,0 +1,185 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import random
5
+ import threading
6
+ import time
7
+ import urllib.parse
8
+ from collections.abc import Callable, Sequence
9
+ from dataclasses import dataclass
10
+ from typing import Literal, TypeVar
11
+
12
+ from himring import Himring, HimringApiError
13
+
14
+ from .events import WireEvent
15
+ from .json_shapes import object_list, object_map
16
+
17
+ DEFAULT_REQUEST_TIMEOUT_SECONDS = 30.0
18
+ DEFAULT_DELIVERY_ATTEMPTS = 6
19
+ HTTP_OK_MINIMUM = 200
20
+ HTTP_OK_MAXIMUM = 299
21
+ HTTP_TOO_MANY_REQUESTS = 429
22
+ HTTP_SERVER_ERROR_MINIMUM = 500
23
+ NO_HTTP_STATUS = 0
24
+ RETRY_AFTER_CEILING_SECONDS = 60.0
25
+ BACKOFF_FIRST_SECONDS = 0.5
26
+ BACKOFF_CEILING_SECONDS = 30.0
27
+ ALLOWED_SCHEMES = frozenset({"http", "https"})
28
+
29
+ ResultT = TypeVar("ResultT")
30
+
31
+
32
+ class HimringRequestError(Exception):
33
+ def __init__(self, status: int, message: str) -> None:
34
+ super().__init__(message)
35
+ self.status = status
36
+
37
+
38
+ @dataclass(frozen=True, slots=True)
39
+ class HimringTarget:
40
+ base_url: str
41
+ api_key: str
42
+ project_id: str
43
+ knowledge_base_id: str
44
+ request_timeout_seconds: float = DEFAULT_REQUEST_TIMEOUT_SECONDS
45
+
46
+ def __post_init__(self) -> None:
47
+ scheme = urllib.parse.urlsplit(self.base_url).scheme
48
+ if scheme not in ALLOWED_SCHEMES:
49
+ raise ValueError("Give Himring's base URL with http or https.")
50
+
51
+
52
+ class HimringConnection:
53
+ def __init__(self, target: HimringTarget) -> None:
54
+ self.target = target
55
+ self._lock = threading.Lock()
56
+ self._client: Himring | None = None
57
+
58
+ def client(self) -> Himring:
59
+ with self._lock:
60
+ if self._client is None:
61
+ self._client = Himring(
62
+ api_key=self.target.api_key,
63
+ base_url=self.target.base_url,
64
+ timeout_seconds=self.target.request_timeout_seconds,
65
+ )
66
+ return self._client
67
+
68
+ async def call(self, work: Callable[[Himring], ResultT]) -> ResultT:
69
+ return await asyncio.to_thread(lambda: work(self.client()))
70
+
71
+ def close(self) -> None:
72
+ with self._lock:
73
+ client, self._client = self._client, None
74
+ if client is not None:
75
+ client.close()
76
+
77
+
78
+ @dataclass(frozen=True, slots=True)
79
+ class DeliveryReply:
80
+ status: int
81
+ answer: object
82
+ retry_after_seconds: float | None
83
+ refused_before_sending: bool = False
84
+
85
+
86
+ def is_success(status: int) -> bool:
87
+ return HTTP_OK_MINIMUM <= status <= HTTP_OK_MAXIMUM
88
+
89
+
90
+ def reply_status_of(error: HimringApiError) -> int:
91
+ return NO_HTTP_STATUS if error.status is None else error.status
92
+
93
+
94
+ def _record_events(connection: HimringConnection, events: Sequence[WireEvent]) -> DeliveryReply:
95
+ target = connection.target
96
+ try:
97
+ answer = connection.client().record_answer_events(
98
+ project_id=target.project_id,
99
+ knowledge_base_id=target.knowledge_base_id,
100
+ origin="sdk",
101
+ events=events,
102
+ )
103
+ except HimringApiError as error:
104
+ if error.kind == "invalid_input":
105
+ return DeliveryReply(NO_HTTP_STATUS, None, None, refused_before_sending=True)
106
+ return DeliveryReply(reply_status_of(error), None, error.retry_after_seconds)
107
+ return DeliveryReply(HTTP_OK_MINIMUM, answer, None)
108
+
109
+
110
+ def _is_retryable(status: int) -> bool:
111
+ return status in (NO_HTTP_STATUS, HTTP_TOO_MANY_REQUESTS) or status >= HTTP_SERVER_ERROR_MINIMUM
112
+
113
+
114
+ def _retry_delay(reply: DeliveryReply, attempt: int) -> float:
115
+ if reply.retry_after_seconds is not None:
116
+ return min(reply.retry_after_seconds, RETRY_AFTER_CEILING_SECONDS)
117
+ ceiling = min(BACKOFF_CEILING_SECONDS, BACKOFF_FIRST_SECONDS * 2**attempt)
118
+ return random.uniform(0, ceiling)
119
+
120
+
121
+ def _unknown_question_ids(answer: object) -> tuple[str, ...]:
122
+ reply = object_map(answer)
123
+ results = None if reply is None else object_list(reply.get("results"))
124
+ unknown: list[str] = []
125
+ for entry in results or []:
126
+ fields = object_map(entry)
127
+ if fields is None:
128
+ continue
129
+ question_id = fields.get("question_id")
130
+ if fields.get("outcome") == "question_not_found" and isinstance(question_id, str):
131
+ unknown.append(question_id)
132
+ return tuple(unknown)
133
+
134
+
135
+ class Waker:
136
+ def __init__(self) -> None:
137
+ self._waiting: set[asyncio.Future[None]] = set()
138
+
139
+ async def pause(self, seconds: float) -> None:
140
+ waiter: asyncio.Future[None] = asyncio.get_running_loop().create_future()
141
+ self._waiting.add(waiter)
142
+ try:
143
+ await asyncio.wait({waiter}, timeout=seconds)
144
+ finally:
145
+ self._waiting.discard(waiter)
146
+
147
+ def wake_all(self) -> None:
148
+ for waiter in self._waiting:
149
+ if not waiter.done():
150
+ waiter.set_result(None)
151
+
152
+
153
+ @dataclass(frozen=True, slots=True)
154
+ class DeliveryOutcome:
155
+ kind: Literal["delivered", "refused", "gave_up", "deadline_passed"]
156
+ unknown_question_ids: tuple[str, ...] = ()
157
+ reason: str = ""
158
+
159
+
160
+ async def deliver_batch(
161
+ connection: HimringConnection,
162
+ events: Sequence[WireEvent],
163
+ *,
164
+ maximum_attempts: int,
165
+ deadline: Callable[[], float],
166
+ waker: Waker,
167
+ ) -> DeliveryOutcome:
168
+ batch = list(events)
169
+ attempt = 0
170
+ while True:
171
+ reply = await asyncio.to_thread(_record_events, connection, batch)
172
+ if is_success(reply.status):
173
+ return DeliveryOutcome("delivered", _unknown_question_ids(reply.answer))
174
+ attempt += 1
175
+ if reply.refused_before_sending:
176
+ return DeliveryOutcome("refused", reason="the client refused the batch")
177
+ reason = f"status {reply.status}" if reply.status else "no connection"
178
+ if not _is_retryable(reply.status):
179
+ return DeliveryOutcome("refused", reason=reason)
180
+ if attempt >= maximum_attempts:
181
+ return DeliveryOutcome("gave_up", reason=reason)
182
+ delay = _retry_delay(reply, attempt)
183
+ if time.monotonic() + delay > deadline():
184
+ return DeliveryOutcome("deadline_passed")
185
+ await waker.pause(delay)
@@ -0,0 +1,165 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import re
5
+ import unicodedata
6
+ from collections.abc import Iterable
7
+ from dataclasses import dataclass
8
+ from datetime import UTC, datetime
9
+ from typing import TypeAlias
10
+
11
+ from himring.types import RecordAnswerEventsInputEventsItem
12
+
13
+ from .json_shapes import object_list, object_map
14
+
15
+ ANSWER_MAXIMUM_LENGTH = 20_000
16
+ FOLLOW_UP_MAXIMUM_LENGTH = 2_000
17
+ HANDOFF_REASON_MAXIMUM_LENGTH = 200
18
+ CITED_CHUNKS_MAXIMUM = 50
19
+ ANSWER_EVENTS_PER_REQUEST_MAXIMUM = 100
20
+ ANSWER_EVENTS_BODY_MAXIMUM_BYTES = 8 * 1024 * 1024
21
+ ANSWER_BATCH_BODY_BUDGET_BYTES = ANSWER_EVENTS_BODY_MAXIMUM_BYTES // 2
22
+
23
+ QUESTION_ID_PATTERN = re.compile(r"qst_[0-9a-f]{32}")
24
+ CHUNK_ID_PATTERN = re.compile(r"chk_[0-9a-f]{32}")
25
+ LINE_BREAKS_AND_TAB = frozenset("\n\r\t")
26
+ REPLACEMENT_CHARACTER = "�"
27
+ FIRST_SURROGATE = 0xD800
28
+ LAST_SURROGATE = 0xDFFF
29
+ FIRST_ASTRAL_CODE_POINT = 0x10000
30
+ JS_TRIMMED_EXTRA = ""
31
+
32
+ WireEvent: TypeAlias = RecordAnswerEventsInputEventsItem
33
+
34
+
35
+ @dataclass(frozen=True, slots=True)
36
+ class AnswerEventDraft:
37
+ question_id: str
38
+ answer: str | None = None
39
+ follow_up: str | None = None
40
+ cited_chunk_ids: tuple[str, ...] | None = None
41
+ thumbs_down: bool = False
42
+ handoff_reason: str | None = None
43
+ occurred_at: str | None = None
44
+
45
+
46
+ def now_timestamp() -> str:
47
+ return datetime.now(UTC).isoformat(timespec="milliseconds").replace("+00:00", "Z")
48
+
49
+
50
+ def _is_control(character: str) -> bool:
51
+ return unicodedata.category(character) == "Cc"
52
+
53
+
54
+ def _well_formed(text: str) -> str:
55
+ return "".join(
56
+ REPLACEMENT_CHARACTER if FIRST_SURROGATE <= ord(character) <= LAST_SURROGATE else character
57
+ for character in text
58
+ )
59
+
60
+
61
+ def _utf16_prefix(text: str, maximum_units: int) -> str:
62
+ kept: list[str] = []
63
+ units = 0
64
+ for character in text:
65
+ width = 2 if ord(character) >= FIRST_ASTRAL_CODE_POINT else 1
66
+ if units + width > maximum_units:
67
+ break
68
+ kept.append(character)
69
+ units += width
70
+ return "".join(kept)
71
+
72
+
73
+ def _trimmed(text: str) -> str:
74
+ return text.strip().strip(JS_TRIMMED_EXTRA).strip()
75
+
76
+
77
+ def bounded_long_text(text: str, maximum: int) -> str | None:
78
+ without_controls = "".join(
79
+ character
80
+ for character in text
81
+ if character in LINE_BREAKS_AND_TAB or not _is_control(character)
82
+ )
83
+ cleaned = _utf16_prefix(_trimmed(_well_formed(without_controls)), maximum)
84
+ return cleaned or None
85
+
86
+
87
+ def bounded_handoff_reason(reason: str) -> str | None:
88
+ spaced = "".join(" " if _is_control(character) else character for character in reason)
89
+ cleaned = _trimmed(_utf16_prefix(_trimmed(_well_formed(spaced)), HANDOFF_REASON_MAXIMUM_LENGTH))
90
+ return cleaned or None
91
+
92
+
93
+ def _cited(chunk_ids: Iterable[str]) -> list[str]:
94
+ unique = [
95
+ chunk_id for chunk_id in dict.fromkeys(chunk_ids) if CHUNK_ID_PATTERN.fullmatch(chunk_id)
96
+ ]
97
+ return unique[:CITED_CHUNKS_MAXIMUM]
98
+
99
+
100
+ def _valid_timestamp(value: str) -> bool:
101
+ try:
102
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
103
+ except ValueError:
104
+ return False
105
+ return parsed.tzinfo is not None
106
+
107
+
108
+ def wire_event(draft: AnswerEventDraft) -> WireEvent | None:
109
+ if not QUESTION_ID_PATTERN.fullmatch(draft.question_id):
110
+ return None
111
+ event: WireEvent = {"question_id": draft.question_id}
112
+ answer = (
113
+ None if draft.answer is None else bounded_long_text(draft.answer, ANSWER_MAXIMUM_LENGTH)
114
+ )
115
+ follow_up = (
116
+ None
117
+ if draft.follow_up is None
118
+ else bounded_long_text(draft.follow_up, FOLLOW_UP_MAXIMUM_LENGTH)
119
+ )
120
+ handoff = None if draft.handoff_reason is None else bounded_handoff_reason(draft.handoff_reason)
121
+ if answer is not None:
122
+ event["answer"] = answer
123
+ if follow_up is not None:
124
+ event["follow_up"] = follow_up
125
+ if handoff is not None:
126
+ event["handoff_reason"] = handoff
127
+ if draft.cited_chunk_ids is not None:
128
+ event["cited_chunk_ids"] = _cited(draft.cited_chunk_ids)
129
+ if draft.thumbs_down:
130
+ event["thumbs_down"] = True
131
+ if len(event) == 1:
132
+ return None
133
+ if draft.occurred_at is not None and _valid_timestamp(draft.occurred_at):
134
+ event["occurred_at"] = draft.occurred_at
135
+ return event
136
+
137
+
138
+ def _text_field(value: object) -> str | None:
139
+ return value if isinstance(value, str) else None
140
+
141
+
142
+ def wire_event_from_json(value: object) -> WireEvent | None:
143
+ fields = object_map(value)
144
+ if fields is None:
145
+ return None
146
+ question_id = _text_field(fields.get("question_id"))
147
+ if question_id is None:
148
+ return None
149
+ cited = object_list(fields.get("cited_chunk_ids"))
150
+ cited_ids = None if cited is None else tuple(item for item in cited if isinstance(item, str))
151
+ return wire_event(
152
+ AnswerEventDraft(
153
+ question_id=question_id,
154
+ answer=_text_field(fields.get("answer")),
155
+ follow_up=_text_field(fields.get("follow_up")),
156
+ cited_chunk_ids=cited_ids,
157
+ thumbs_down=fields.get("thumbs_down") is True,
158
+ handoff_reason=_text_field(fields.get("handoff_reason")),
159
+ occurred_at=_text_field(fields.get("occurred_at")),
160
+ )
161
+ )
162
+
163
+
164
+ def encoded(value: object) -> bytes:
165
+ return json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
@@ -0,0 +1,25 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from typing import cast
5
+
6
+
7
+ def object_map(value: object) -> dict[str, object] | None:
8
+ if not isinstance(value, dict):
9
+ return None
10
+ entries = cast("dict[object, object]", value)
11
+ return {key: item for key, item in entries.items() if isinstance(key, str)}
12
+
13
+
14
+ def object_list(value: object) -> list[object] | None:
15
+ if not isinstance(value, list):
16
+ return None
17
+ return list(cast("list[object]", value))
18
+
19
+
20
+ def parsed_object_map(text: str | bytes) -> dict[str, object] | None:
21
+ try:
22
+ value: object = json.loads(text)
23
+ except ValueError:
24
+ return None
25
+ return object_map(value)
@@ -0,0 +1,60 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ from collections.abc import Callable
5
+ from typing import Literal, Protocol
6
+
7
+ from livekit.agents import CloseEvent, ConversationItemAddedEvent, JobContext
8
+ from livekit.agents.llm import ChatMessage
9
+
10
+ from .conversation import AnswerConversation
11
+
12
+ LiveKitSessionEvent = Literal["conversation_item_added", "close"]
13
+
14
+
15
+ class LiveKitSession(Protocol):
16
+ def on(
17
+ self, event: LiveKitSessionEvent, callback: Callable[..., object] | None = None
18
+ ) -> object: ...
19
+
20
+
21
+ class LiveKitAnswerHook:
22
+ def __init__(self, conversation: AnswerConversation) -> None:
23
+ self._conversation = conversation
24
+ self._ending: set[asyncio.Task[None]] = set()
25
+
26
+ def on_conversation_item_added(self, event: ConversationItemAddedEvent) -> None:
27
+ item = event.item
28
+ if not isinstance(item, ChatMessage):
29
+ return
30
+ text = item.text_content
31
+ if not text:
32
+ return
33
+ if item.role == "assistant":
34
+ self._conversation.record_answer(text)
35
+ elif item.role == "user":
36
+ self._conversation.record_user_message(text)
37
+
38
+ def on_close(self, event: CloseEvent) -> None:
39
+ try:
40
+ task = asyncio.get_running_loop().create_task(self._conversation.end())
41
+ except RuntimeError:
42
+ return
43
+ self._ending.add(task)
44
+ task.add_done_callback(self._ending.discard)
45
+
46
+ async def on_shutdown(self) -> None:
47
+ await self._conversation.end()
48
+
49
+
50
+ def attach_livekit_session(
51
+ conversation: AnswerConversation,
52
+ session: LiveKitSession,
53
+ job_context: JobContext | None = None,
54
+ ) -> LiveKitAnswerHook:
55
+ hook = LiveKitAnswerHook(conversation)
56
+ session.on("conversation_item_added", hook.on_conversation_item_added)
57
+ session.on("close", hook.on_close)
58
+ if job_context is not None:
59
+ job_context.add_shutdown_callback(hook.on_shutdown)
60
+ return hook
@@ -0,0 +1,57 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Callable, Coroutine
4
+ from typing import Protocol
5
+
6
+ from pipecat.frames.frames import Frame
7
+ from pipecat.processors.aggregators.llm_response_universal import (
8
+ AssistantTurnStoppedMessage,
9
+ UserTurnMessageAddedMessage,
10
+ )
11
+
12
+ from .conversation import AnswerConversation
13
+
14
+ PipecatHandler = Callable[..., Coroutine[object, object, None]]
15
+
16
+
17
+ class PipecatEventSource(Protocol):
18
+ def add_event_handler(self, event_name: str, handler: PipecatHandler) -> None: ...
19
+
20
+
21
+ class PipecatAnswerHook:
22
+ def __init__(self, conversation: AnswerConversation) -> None:
23
+ self._conversation = conversation
24
+
25
+ async def on_assistant_turn_stopped(
26
+ self, aggregator: object, message: AssistantTurnStoppedMessage
27
+ ) -> None:
28
+ if message.content:
29
+ self._conversation.record_answer(message.content)
30
+
31
+ async def on_user_turn_message_added(
32
+ self, aggregator: object, message: UserTurnMessageAddedMessage
33
+ ) -> None:
34
+ if message.content:
35
+ self._conversation.record_user_message(message.content)
36
+
37
+ async def on_pipeline_finished(self, worker: object, frame: Frame) -> None:
38
+ await self._conversation.end()
39
+
40
+
41
+ def attach_pipecat_pipeline(
42
+ conversation: AnswerConversation,
43
+ assistant_aggregator: PipecatEventSource,
44
+ user_aggregator: PipecatEventSource | None = None,
45
+ worker: PipecatEventSource | None = None,
46
+ ) -> PipecatAnswerHook:
47
+ hook = PipecatAnswerHook(conversation)
48
+ assistant_aggregator.add_event_handler(
49
+ "on_assistant_turn_stopped", hook.on_assistant_turn_stopped
50
+ )
51
+ if user_aggregator is not None:
52
+ user_aggregator.add_event_handler(
53
+ "on_user_turn_message_added", hook.on_user_turn_message_added
54
+ )
55
+ if worker is not None:
56
+ worker.add_event_handler("on_pipeline_finished", hook.on_pipeline_finished)
57
+ return hook
File without changes