livekit-plugins-anam 1.2.2__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,37 @@
1
+ # Copyright 2023 LiveKit, Inc.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from .avatar import AvatarSession
16
+ from .errors import AnamException
17
+ from .types import PersonaConfig
18
+ from .version import __version__
19
+
20
+ __all__ = [
21
+ "AnamException",
22
+ "AvatarSession",
23
+ "PersonaConfig",
24
+ "__version__",
25
+ ]
26
+
27
+ from livekit.agents import Plugin
28
+
29
+ from .log import logger
30
+
31
+
32
+ class AnamPlugin(Plugin):
33
+ def __init__(self) -> None:
34
+ super().__init__(__name__, __version__, __package__, logger)
35
+
36
+
37
+ Plugin.register_plugin(AnamPlugin())
@@ -0,0 +1,154 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ from typing import Any
5
+
6
+ import aiohttp
7
+
8
+ from livekit.agents import (
9
+ DEFAULT_API_CONNECT_OPTIONS,
10
+ APIConnectionError,
11
+ APIConnectOptions,
12
+ APIStatusError,
13
+ )
14
+
15
+ from .errors import AnamException
16
+ from .log import logger
17
+ from .types import PersonaConfig
18
+
19
+ DEFAULT_API_URL = "https://api.anam.ai"
20
+
21
+
22
+ class AnamAPI:
23
+ """
24
+ An asynchronous client for interacting with the Anam API.
25
+
26
+ This class handles authentication, request signing, and retries.
27
+ """
28
+
29
+ def __init__(
30
+ self,
31
+ api_key: str,
32
+ api_url: str,
33
+ *,
34
+ conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS,
35
+ session: aiohttp.ClientSession | None = None,
36
+ ) -> None:
37
+ """
38
+ Initializes the AnamAPI client.
39
+
40
+ Args:
41
+ api_key: Your Anam API key. If not provided, it will be read from
42
+ the ANAM_API_KEY environment variable.
43
+ api_url: The base URL of the Anam API.
44
+ conn_options: Connection options for the aiohttp session.
45
+ session: An optional existing aiohttp.ClientSession to use for requests.
46
+ """
47
+ self._api_key = api_key
48
+ self._api_url = api_url
49
+ self._conn_options = conn_options
50
+ self._session = session
51
+ self._own_session = session is None
52
+
53
+ async def __aenter__(self) -> AnamAPI:
54
+ if self._own_session:
55
+ self._session = aiohttp.ClientSession()
56
+ return self
57
+
58
+ async def __aexit__(
59
+ self, exc_type: type | None, exc_val: Exception | None, exc_tb: Any
60
+ ) -> None:
61
+ if self._own_session and self._session:
62
+ await self._session.close()
63
+
64
+ async def create_session_token(
65
+ self, persona_config: PersonaConfig, livekit_url: str, livekit_token: str
66
+ ) -> str:
67
+ """
68
+ Creates a session token to authorize starting an engine session.
69
+
70
+ Returns:
71
+ The created session token (a JWT string).
72
+ """
73
+ payload = {
74
+ "personaConfig": {
75
+ "type": "ephemeral",
76
+ "name": persona_config.name,
77
+ "avatarId": persona_config.avatarId,
78
+ "llmId": "CUSTOMER_CLIENT_V1",
79
+ },
80
+ }
81
+ payload["environment"] = {
82
+ "livekitUrl": livekit_url,
83
+ "livekitToken": livekit_token,
84
+ }
85
+ headers = {
86
+ "Authorization": f"Bearer {self._api_key}", # Use API Key here
87
+ "Content-Type": "application/json",
88
+ }
89
+ response_data = await self._post("/v1/auth/session-token", payload, headers)
90
+
91
+ session_token: str | None = response_data.get("sessionToken")
92
+ if not session_token:
93
+ raise AnamException("Failed to retrieve sessionToken from API response.")
94
+ return session_token
95
+
96
+ async def start_engine_session(
97
+ self,
98
+ session_token: str,
99
+ ) -> dict[str, Any]:
100
+ """
101
+ Starts the engine session using a previously created session token.
102
+
103
+ Args:
104
+ session_token: The temporary token from create_session_token.
105
+ livekit_url: The URL of the LiveKit instance.
106
+ livekit_token: The access token for the LiveKit room.
107
+
108
+ Returns:
109
+ The session details, including sessionId and engine host info.
110
+ """
111
+ headers = {
112
+ "Authorization": f"Bearer {session_token}", # Use Session Token here
113
+ "Content-Type": "application/json",
114
+ }
115
+ return await self._post("/v1/engine/session", {}, headers)
116
+
117
+ async def _post(
118
+ self, endpoint: str, payload: dict[str, Any], headers: dict[str, str]
119
+ ) -> dict[str, Any]:
120
+ """
121
+ Internal method to make a POST request with retry logic.
122
+ """
123
+ url = f"{self._api_url}{endpoint}"
124
+ session = self._session or aiohttp.ClientSession()
125
+ try:
126
+ for attempt in range(self._conn_options.max_retry):
127
+ try:
128
+ async with session.post(
129
+ url,
130
+ headers=headers,
131
+ json=payload,
132
+ timeout=aiohttp.ClientTimeout(sock_connect=self._conn_options.timeout),
133
+ ) as response:
134
+ if not response.ok:
135
+ text = await response.text()
136
+ raise APIStatusError(
137
+ f"Server returned an error for {url}: {response.status}",
138
+ status_code=response.status,
139
+ body=text,
140
+ )
141
+ return await response.json() # type: ignore
142
+ except (aiohttp.ClientError, asyncio.TimeoutError) as e:
143
+ logger.warning(
144
+ f"API request to {url} failed on attempt {attempt + 1}",
145
+ extra={"error": str(e)},
146
+ )
147
+ if attempt >= self._conn_options.max_retry - 1:
148
+ raise APIConnectionError(f"Failed to connect to Anam API at {url}") from e
149
+ await asyncio.sleep(self._conn_options.retry_interval)
150
+ finally:
151
+ if not self._session: # if we created the session, we close it
152
+ await session.close()
153
+
154
+ raise APIConnectionError("Failed to call Anam API after all retries.")
@@ -0,0 +1,127 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+
5
+ import aiohttp
6
+
7
+ from livekit import api, rtc
8
+ from livekit.agents import (
9
+ DEFAULT_API_CONNECT_OPTIONS,
10
+ NOT_GIVEN,
11
+ AgentSession,
12
+ APIConnectOptions,
13
+ NotGivenOr,
14
+ get_job_context,
15
+ utils,
16
+ )
17
+ from livekit.agents.voice.avatar import DataStreamAudioOutput
18
+ from livekit.agents.voice.room_io import ATTRIBUTE_PUBLISH_ON_BEHALF
19
+
20
+ from .api import DEFAULT_API_URL, AnamAPI
21
+ from .errors import AnamException
22
+ from .log import logger
23
+ from .types import PersonaConfig
24
+
25
+ SAMPLE_RATE = 24000
26
+ _AVATAR_AGENT_IDENTITY = "anam-avatar-agent"
27
+ _AVATAR_AGENT_NAME = "anam-avatar-agent"
28
+
29
+
30
+ class AvatarSession:
31
+ """A Anam avatar session"""
32
+
33
+ def __init__(
34
+ self,
35
+ *,
36
+ persona_config: PersonaConfig,
37
+ api_url: NotGivenOr[str] = NOT_GIVEN,
38
+ api_key: NotGivenOr[str] = NOT_GIVEN,
39
+ avatar_participant_identity: NotGivenOr[str] = NOT_GIVEN,
40
+ avatar_participant_name: NotGivenOr[str] = NOT_GIVEN,
41
+ conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS,
42
+ ) -> None:
43
+ self._http_session: aiohttp.ClientSession | None = None
44
+ self._conn_options = conn_options
45
+ self.session_id: str | None = None
46
+ self._avatar_participant_identity = avatar_participant_identity or _AVATAR_AGENT_IDENTITY
47
+ self._avatar_participant_name = avatar_participant_name or _AVATAR_AGENT_NAME
48
+ self._persona_config: PersonaConfig = persona_config
49
+
50
+ api_url_val = (
51
+ api_url if utils.is_given(api_url) else os.getenv("ANAM_API_URL", DEFAULT_API_URL)
52
+ )
53
+ api_key_val = api_key if utils.is_given(api_key) else os.getenv("ANAM_API_KEY")
54
+
55
+ if not api_key_val:
56
+ raise AnamException("ANAM_API_KEY must be set by arguments or environment variables")
57
+
58
+ self._api_url = api_url_val
59
+ self._api_key = api_key_val
60
+
61
+ def _ensure_http_session(self) -> aiohttp.ClientSession:
62
+ if self._http_session is None:
63
+ self._http_session = utils.http_context.http_session()
64
+
65
+ return self._http_session
66
+
67
+ async def start(
68
+ self,
69
+ agent_session: AgentSession,
70
+ room: rtc.Room,
71
+ *,
72
+ livekit_url: NotGivenOr[str] = NOT_GIVEN,
73
+ livekit_api_key: NotGivenOr[str] = NOT_GIVEN,
74
+ livekit_api_secret: NotGivenOr[str] = NOT_GIVEN,
75
+ ) -> None:
76
+ livekit_url = livekit_url or (os.getenv("LIVEKIT_URL") or NOT_GIVEN)
77
+ livekit_api_key = livekit_api_key or (os.getenv("LIVEKIT_API_KEY") or NOT_GIVEN)
78
+ livekit_api_secret = livekit_api_secret or (os.getenv("LIVEKIT_API_SECRET") or NOT_GIVEN)
79
+ if not livekit_url or not livekit_api_key or not livekit_api_secret:
80
+ raise AnamException(
81
+ "livekit_url, livekit_api_key, and livekit_api_secret must be set "
82
+ "by arguments or environment variables"
83
+ )
84
+
85
+ try:
86
+ job_ctx = get_job_context()
87
+ local_participant_identity = job_ctx.token_claims().identity
88
+ except RuntimeError as e:
89
+ if not room.isconnected():
90
+ raise AnamException("failed to get local participant identity") from e
91
+ local_participant_identity = room.local_participant.identity
92
+
93
+ livekit_token = (
94
+ api.AccessToken(
95
+ api_key=livekit_api_key,
96
+ api_secret=livekit_api_secret,
97
+ )
98
+ .with_kind("agent")
99
+ .with_identity(self._avatar_participant_identity)
100
+ .with_name(self._avatar_participant_name)
101
+ .with_grants(api.VideoGrants(room_join=True, room=room.name))
102
+ # allow the avatar agent to publish audio and video on behalf of your local agent
103
+ .with_attributes({ATTRIBUTE_PUBLISH_ON_BEHALF: local_participant_identity})
104
+ .to_jwt()
105
+ )
106
+ async with AnamAPI(
107
+ api_key=self._api_key, api_url=self._api_url, conn_options=self._conn_options
108
+ ) as anam_api:
109
+ session_token = await anam_api.create_session_token(
110
+ persona_config=self._persona_config,
111
+ livekit_url=livekit_url,
112
+ livekit_token=livekit_token,
113
+ )
114
+ logger.debug("Anam session token created successfully.")
115
+
116
+ logger.debug("Starting Anam engine session...")
117
+ session_details = await anam_api.start_engine_session(
118
+ session_token=session_token,
119
+ )
120
+ self.session_id = session_details.get("sessionId")
121
+
122
+ agent_session.output.audio = DataStreamAudioOutput(
123
+ room=room,
124
+ destination_identity=self._avatar_participant_identity,
125
+ sample_rate=SAMPLE_RATE,
126
+ wait_remote_track=rtc.TrackKind.KIND_VIDEO,
127
+ )
@@ -0,0 +1,4 @@
1
+ class AnamException(Exception):
2
+ """Custom exception for Anam API errors."""
3
+
4
+ pass
@@ -0,0 +1,3 @@
1
+ import logging
2
+
3
+ logger = logging.getLogger("livekit.plugins.anam")
File without changes
@@ -0,0 +1,9 @@
1
+ from dataclasses import dataclass
2
+
3
+
4
+ @dataclass
5
+ class PersonaConfig:
6
+ """Configuration for Anam avatar persona"""
7
+
8
+ name: str
9
+ avatarId: str
@@ -0,0 +1,15 @@
1
+ # Copyright 2025 LiveKit, Inc.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ __version__ = "1.2.2"
@@ -0,0 +1,25 @@
1
+ Metadata-Version: 2.4
2
+ Name: livekit-plugins-anam
3
+ Version: 1.2.2
4
+ Summary: Agent Framework plugin for anam
5
+ Project-URL: Documentation, https://docs.livekit.io
6
+ Project-URL: Website, https://livekit.io/
7
+ Project-URL: Source, https://github.com/livekit/agents
8
+ Author-email: LiveKit <support@livekit.io>
9
+ License-Expression: Apache-2.0
10
+ Keywords: audio,livekit,realtime,video,webrtc
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Topic :: Multimedia :: Sound/Audio
18
+ Classifier: Topic :: Multimedia :: Video
19
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
20
+ Requires-Python: >=3.9.0
21
+ Requires-Dist: livekit-agents>=1.2.2
22
+ Description-Content-Type: text/markdown
23
+
24
+ # livekit-plugins-anam
25
+ Support for the [Anam](https://anam.ai/) virtual avatar.
@@ -0,0 +1,11 @@
1
+ livekit/plugins/anam/__init__.py,sha256=MI_yAAR_UOQR_Ln3p27zPml02ZkNDCXC2mpn5wxhPwo,1037
2
+ livekit/plugins/anam/api.py,sha256=zc5WSq_DfFF8Fq7DF93vqeWuCMpBVv5J3eTVwywoH2c,5439
3
+ livekit/plugins/anam/avatar.py,sha256=H4lh90GJTg-2IbB18QsdRWUh8ha-IspMj5nSq2O_xAs,4790
4
+ livekit/plugins/anam/errors.py,sha256=3B83wAdOufnqjKM0vNtmk0KYBUgMYPvmvxLsM2I9UHI,90
5
+ livekit/plugins/anam/log.py,sha256=-YtMyPRFZ2Etshon45g6m44GQtxHIhZZcaF4ZpK1Iik,67
6
+ livekit/plugins/anam/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ livekit/plugins/anam/types.py,sha256=O1wtKYZe7cxuxID5ozncp0oyd6ZA3Th6jALHbROxbfU,149
8
+ livekit/plugins/anam/version.py,sha256=HEPfsPSBZ3rIkyBj712Ik9tN1Z2rZUKSzUk3uWa0unA,600
9
+ livekit_plugins_anam-1.2.2.dist-info/METADATA,sha256=hHODbXB5of1tb0C6OX7hpayWEo_zPIllAesvF1MxEH8,1028
10
+ livekit_plugins_anam-1.2.2.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
11
+ livekit_plugins_anam-1.2.2.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any