livekit-plugins-langchain 1.3.5__tar.gz

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,179 @@
1
+ **/.vscode
2
+ **/.DS_Store
3
+
4
+ # Byte-compiled / optimized / DLL files
5
+ __pycache__/
6
+ *.py[cod]
7
+ *$py.class
8
+
9
+ # C extensions
10
+ *.so
11
+
12
+ # Distribution / packaging
13
+ .Python
14
+ build/
15
+ develop-eggs/
16
+ dist/
17
+ downloads/
18
+ eggs/
19
+ .eggs/
20
+ lib/
21
+ lib64/
22
+ parts/
23
+ sdist/
24
+ var/
25
+ wheels/
26
+ share/python-wheels/
27
+ *.egg-info/
28
+ .installed.cfg
29
+ *.egg
30
+ MANIFEST
31
+
32
+ # PyInstaller
33
+ # Usually these files are written by a python script from a template
34
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
35
+ *.manifest
36
+ *.spec
37
+
38
+ # Installer logs
39
+ pip-log.txt
40
+ pip-delete-this-directory.txt
41
+
42
+ # Unit test / coverage reports
43
+ htmlcov/
44
+ .tox/
45
+ .nox/
46
+ .coverage
47
+ .coverage.*
48
+ .cache
49
+ nosetests.xml
50
+ coverage.xml
51
+ *.cover
52
+ *.py,cover
53
+ .hypothesis/
54
+ .pytest_cache/
55
+ cover/
56
+
57
+ # Translations
58
+ *.mo
59
+ *.pot
60
+
61
+ # Django stuff:
62
+ *.log
63
+ local_settings.py
64
+ db.sqlite3
65
+ db.sqlite3-journal
66
+
67
+ # Flask stuff:
68
+ instance/
69
+ .webassets-cache
70
+
71
+ # Scrapy stuff:
72
+ .scrapy
73
+
74
+ # Sphinx documentation
75
+ docs/_build/
76
+
77
+ # PyBuilder
78
+ .pybuilder/
79
+ target/
80
+
81
+ # Jupyter Notebook
82
+ .ipynb_checkpoints
83
+
84
+ # IPython
85
+ profile_default/
86
+ ipython_config.py
87
+
88
+ # pyenv
89
+ # For a library or package, you might want to ignore these files since the code is
90
+ # intended to run in multiple environments; otherwise, check them in:
91
+ # .python-version
92
+
93
+ # pipenv
94
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
95
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
96
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
97
+ # install all needed dependencies.
98
+ #Pipfile.lock
99
+
100
+ # poetry
101
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
102
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
103
+ # commonly ignored for libraries.
104
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
105
+ #poetry.lock
106
+
107
+ # pdm
108
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
109
+ #pdm.lock
110
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
111
+ # in version control.
112
+ # https://pdm.fming.dev/#use-with-ide
113
+ .pdm.toml
114
+
115
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
116
+ __pypackages__/
117
+
118
+ # Celery stuff
119
+ celerybeat-schedule
120
+ celerybeat.pid
121
+
122
+ # SageMath parsed files
123
+ *.sage.py
124
+
125
+ # Environments
126
+ .env
127
+ .venv
128
+ env/
129
+ venv/
130
+ ENV/
131
+ env.bak/
132
+ venv.bak/
133
+
134
+ # Spyder project settings
135
+ .spyderproject
136
+ .spyproject
137
+
138
+ # Rope project settings
139
+ .ropeproject
140
+
141
+ # mkdocs documentation
142
+ /site
143
+
144
+ # mypy
145
+ .mypy_cache/
146
+ .dmypy.json
147
+ dmypy.json
148
+
149
+ # trunk
150
+ .trunk/
151
+
152
+ # Pyre type checker
153
+ .pyre/
154
+
155
+ # pytype static type analyzer
156
+ .pytype/
157
+
158
+ # Cython debug symbols
159
+ cython_debug/
160
+
161
+ # PyCharm
162
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
163
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
164
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
165
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
166
+ .idea/
167
+
168
+ node_modules
169
+
170
+ credentials.json
171
+ pyrightconfig.json
172
+ docs/
173
+
174
+ # Database files
175
+ *.db
176
+
177
+
178
+ # Examples for development
179
+ examples/dev/*
@@ -0,0 +1,61 @@
1
+ Metadata-Version: 2.4
2
+ Name: livekit-plugins-langchain
3
+ Version: 1.3.5
4
+ Summary: LangChain/LangGraph plugin for LiveKit agents
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 <hello@livekit.io>
9
+ License-Expression: Apache-2.0
10
+ Keywords: LangChain,LangGraph,ai,livekit,realtime,voice
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.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Multimedia :: Sound/Audio
18
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
19
+ Requires-Python: >=3.9.0
20
+ Requires-Dist: langchain-core>=0.3.0
21
+ Requires-Dist: langgraph>=0.3.0
22
+ Requires-Dist: livekit-agents>=1.3.5
23
+ Description-Content-Type: text/markdown
24
+
25
+ # LangChain plugin for LiveKit Agents
26
+
27
+ This plugin integrates capabilites from LangChain within LiveKit Agents
28
+
29
+ ## Installation
30
+
31
+ ```bash
32
+ pip install livekit-plugins-langchain
33
+ ```
34
+
35
+ ## Usage
36
+
37
+ ### Using LangGraph workflows
38
+
39
+ You can bring over any existing workflow in LangGraph as an Agents LLM with `langchain.LLMAdapter`. For example:
40
+
41
+ ```python
42
+ from langgraph.graph import StateGraph
43
+ from livekit.agents import Agent, AgentSession, JobContext
44
+ from livekit.plugins import langchain
45
+
46
+ ...
47
+
48
+ def entrypoint(ctx: JobContext):
49
+ graph = StateGraph(...).compile()
50
+
51
+ session = AgentSession(
52
+ vad=...,
53
+ stt=...,
54
+ tts=...,
55
+ )
56
+
57
+ await session.start(
58
+ agent=Agent(llm=langchain.LLMAdapter(graph)),
59
+ )
60
+ ...
61
+ ```
@@ -0,0 +1,37 @@
1
+ # LangChain plugin for LiveKit Agents
2
+
3
+ This plugin integrates capabilites from LangChain within LiveKit Agents
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pip install livekit-plugins-langchain
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ### Using LangGraph workflows
14
+
15
+ You can bring over any existing workflow in LangGraph as an Agents LLM with `langchain.LLMAdapter`. For example:
16
+
17
+ ```python
18
+ from langgraph.graph import StateGraph
19
+ from livekit.agents import Agent, AgentSession, JobContext
20
+ from livekit.plugins import langchain
21
+
22
+ ...
23
+
24
+ def entrypoint(ctx: JobContext):
25
+ graph = StateGraph(...).compile()
26
+
27
+ session = AgentSession(
28
+ vad=...,
29
+ stt=...,
30
+ tts=...,
31
+ )
32
+
33
+ await session.start(
34
+ agent=Agent(llm=langchain.LLMAdapter(graph)),
35
+ )
36
+ ...
37
+ ```
@@ -0,0 +1,39 @@
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
+ """LangChain plugin for LiveKit Agents."""
16
+
17
+ from .langgraph import LangGraphStream, LLMAdapter
18
+ from .version import __version__
19
+
20
+ __all__ = ["__version__", "LLMAdapter", "LangGraphStream"]
21
+
22
+ from livekit.agents import Plugin
23
+
24
+
25
+ class LangChainPlugin(Plugin):
26
+ def __init__(self) -> None:
27
+ super().__init__(__name__, __version__, __package__)
28
+
29
+
30
+ Plugin.register_plugin(LangChainPlugin())
31
+
32
+ # Cleanup docs of unexported modules
33
+ _module = dir()
34
+ NOT_IN_ALL = [m for m in _module if m not in __all__]
35
+
36
+ __pdoc__ = {}
37
+
38
+ for n in NOT_IN_ALL:
39
+ __pdoc__[n] = False
@@ -0,0 +1,208 @@
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
+ from __future__ import annotations
16
+
17
+ from typing import Any
18
+
19
+ from langchain_core.messages import AIMessage, BaseMessageChunk, HumanMessage, SystemMessage
20
+ from langchain_core.runnables import RunnableConfig
21
+ from langgraph.pregel.protocol import PregelProtocol
22
+
23
+ from livekit.agents import llm, utils
24
+ from livekit.agents.llm import ToolChoice
25
+ from livekit.agents.llm.chat_context import ChatContext, ChatMessage
26
+ from livekit.agents.llm.tool_context import FunctionTool, RawFunctionTool
27
+ from livekit.agents.types import (
28
+ DEFAULT_API_CONNECT_OPTIONS,
29
+ NOT_GIVEN,
30
+ APIConnectOptions,
31
+ NotGivenOr,
32
+ )
33
+
34
+
35
+ class LLMAdapter(llm.LLM):
36
+ def __init__(
37
+ self,
38
+ graph: PregelProtocol,
39
+ *,
40
+ config: RunnableConfig | None = None,
41
+ subgraphs: bool = False,
42
+ ) -> None:
43
+ super().__init__()
44
+ self._graph = graph
45
+ self._config = config
46
+ self._subgraphs = subgraphs
47
+
48
+ @property
49
+ def model(self) -> str:
50
+ return "unknown"
51
+
52
+ @property
53
+ def provider(self) -> str:
54
+ return "LangChain"
55
+
56
+ def chat(
57
+ self,
58
+ *,
59
+ chat_ctx: ChatContext,
60
+ tools: list[FunctionTool | RawFunctionTool] | None = None,
61
+ conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS,
62
+ # these are unused, since tool execution takes place in langgraph
63
+ parallel_tool_calls: NotGivenOr[bool] = NOT_GIVEN,
64
+ tool_choice: NotGivenOr[ToolChoice] = NOT_GIVEN,
65
+ extra_kwargs: NotGivenOr[dict[str, Any]] = NOT_GIVEN,
66
+ ) -> LangGraphStream:
67
+ return LangGraphStream(
68
+ self,
69
+ chat_ctx=chat_ctx,
70
+ tools=tools or [],
71
+ graph=self._graph,
72
+ conn_options=conn_options,
73
+ config=self._config,
74
+ subgraphs=self._subgraphs,
75
+ )
76
+
77
+
78
+ class LangGraphStream(llm.LLMStream):
79
+ def __init__(
80
+ self,
81
+ llm: LLMAdapter,
82
+ *,
83
+ chat_ctx: ChatContext,
84
+ tools: list[FunctionTool | RawFunctionTool],
85
+ conn_options: APIConnectOptions,
86
+ graph: PregelProtocol,
87
+ config: RunnableConfig | None = None,
88
+ subgraphs: bool = False,
89
+ ):
90
+ super().__init__(
91
+ llm,
92
+ chat_ctx=chat_ctx,
93
+ tools=tools,
94
+ conn_options=conn_options,
95
+ )
96
+ self._graph = graph
97
+ self._config = config
98
+ self._subgraphs = subgraphs
99
+
100
+ async def _run(self) -> None:
101
+ state = self._chat_ctx_to_state()
102
+
103
+ # Some LangGraph versions don't accept the `subgraphs` kwarg yet.
104
+ # Try with it first; fall back gracefully if it's unsupported.
105
+ try:
106
+ aiter = self._graph.astream(
107
+ state,
108
+ self._config,
109
+ stream_mode="messages",
110
+ subgraphs=self._subgraphs,
111
+ )
112
+ except TypeError:
113
+ aiter = self._graph.astream(
114
+ state,
115
+ self._config,
116
+ stream_mode="messages",
117
+ )
118
+
119
+ async for item in aiter:
120
+ token_like = _extract_message_chunk(item)
121
+ if token_like is None:
122
+ continue
123
+
124
+ chat_chunk = _to_chat_chunk(token_like)
125
+ if chat_chunk:
126
+ self._event_ch.send_nowait(chat_chunk)
127
+
128
+ def _chat_ctx_to_state(self) -> dict[str, Any]:
129
+ """Convert chat context to langgraph input"""
130
+
131
+ messages: list[AIMessage | HumanMessage | SystemMessage] = []
132
+ for item in self._chat_ctx.items:
133
+ # only support chat messages, ignoring tool calls
134
+ if isinstance(item, ChatMessage):
135
+ content = item.text_content
136
+ if content:
137
+ if item.role == "assistant":
138
+ messages.append(AIMessage(content=content, id=item.id))
139
+ elif item.role == "user":
140
+ messages.append(HumanMessage(content=content, id=item.id))
141
+ elif item.role in ["system", "developer"]:
142
+ messages.append(SystemMessage(content=content, id=item.id))
143
+
144
+ return {"messages": messages}
145
+
146
+
147
+ def _extract_message_chunk(item: Any) -> BaseMessageChunk | str | None:
148
+ """
149
+ Normalize outputs from graph.astream(..., stream_mode='messages', [subgraphs]).
150
+
151
+ Expected shapes:
152
+ - (token, meta)
153
+ - (namespace, (token, meta)) # with subgraphs=True
154
+ - (mode, (token, meta)) # future-friendly
155
+ - (namespace, mode, (token, meta)) # future-friendly
156
+ Also tolerate direct token-like values for robustness.
157
+ """
158
+ # Already a token-like thing?
159
+ if isinstance(item, (BaseMessageChunk, str)):
160
+ return item
161
+
162
+ if not isinstance(item, tuple):
163
+ return None
164
+
165
+ # token is usually BaseMessageChunk, but could be a str
166
+ # (token, meta)
167
+ if len(item) == 2 and not isinstance(item[1], tuple):
168
+ token, _meta = item
169
+ return token # type: ignore
170
+
171
+ # (namespace, (token, meta)) OR (mode, (token, meta))
172
+ if len(item) == 2 and isinstance(item[1], tuple):
173
+ inner = item[1]
174
+ if len(inner) == 2:
175
+ token, _meta = inner
176
+ return token # type: ignore
177
+
178
+ # (namespace, mode, (token, meta))
179
+ if len(item) == 3 and isinstance(item[2], tuple):
180
+ inner = item[2]
181
+ if len(inner) == 2:
182
+ token, _meta = inner
183
+ return token # type: ignore
184
+
185
+ return None
186
+
187
+
188
+ def _to_chat_chunk(msg: str | Any) -> llm.ChatChunk | None:
189
+ message_id = utils.shortuuid("LC_")
190
+ content: str | None = None
191
+
192
+ if isinstance(msg, str):
193
+ content = msg
194
+ elif isinstance(msg, BaseMessageChunk):
195
+ content = msg.text()
196
+ if getattr(msg, "id", None):
197
+ message_id = msg.id # type: ignore
198
+
199
+ if not content:
200
+ return None
201
+
202
+ return llm.ChatChunk(
203
+ id=message_id,
204
+ delta=llm.ChoiceDelta(
205
+ role="assistant",
206
+ content=content,
207
+ ),
208
+ )
@@ -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.3.5"
@@ -0,0 +1,44 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "livekit-plugins-langchain"
7
+ dynamic = ["version"]
8
+ description = "LangChain/LangGraph plugin for LiveKit agents"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ requires-python = ">=3.9.0"
12
+ authors = [
13
+ {name = "LiveKit", email = "hello@livekit.io"}
14
+ ]
15
+ keywords = ["voice", "ai", "realtime", "livekit", "LangChain", "LangGraph"]
16
+ classifiers = [
17
+ "Intended Audience :: Developers",
18
+ "License :: OSI Approved :: Apache Software License",
19
+ "Topic :: Multimedia :: Sound/Audio",
20
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
21
+ "Programming Language :: Python :: 3",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Programming Language :: Python :: 3 :: Only",
25
+ ]
26
+ dependencies = [
27
+ "livekit-agents>=1.3.5",
28
+ "langchain-core>=0.3.0",
29
+ "langgraph>=0.3.0",
30
+ ]
31
+
32
+ [project.urls]
33
+ Documentation = "https://docs.livekit.io"
34
+ Website = "https://livekit.io/"
35
+ Source = "https://github.com/livekit/agents"
36
+
37
+ [tool.hatch.version]
38
+ path = "livekit/plugins/langchain/version.py"
39
+
40
+ [tool.hatch.build.targets.wheel]
41
+ packages = ["livekit"]
42
+
43
+ [tool.hatch.build.targets.sdist]
44
+ include = ["/livekit"]