langchain-gnani 0.1.0__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.
- langchain_gnani-0.1.0/LICENSE +21 -0
- langchain_gnani-0.1.0/PKG-INFO +152 -0
- langchain_gnani-0.1.0/README.md +131 -0
- langchain_gnani-0.1.0/pyproject.toml +64 -0
- langchain_gnani-0.1.0/pyproject.toml.orig +60 -0
- langchain_gnani-0.1.0/src/langchain_gnani/__init__.py +20 -0
- langchain_gnani-0.1.0/src/langchain_gnani/_common.py +52 -0
- langchain_gnani-0.1.0/src/langchain_gnani/batch.py +57 -0
- langchain_gnani-0.1.0/src/langchain_gnani/py.typed +0 -0
- langchain_gnani-0.1.0/src/langchain_gnani/realtime.py +192 -0
- langchain_gnani-0.1.0/src/langchain_gnani/streaming.py +29 -0
- langchain_gnani-0.1.0/src/langchain_gnani/stt.py +213 -0
- langchain_gnani-0.1.0/src/langchain_gnani/tools.py +76 -0
- langchain_gnani-0.1.0/src/langchain_gnani/tts.py +272 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Gaurav Chaudhary and contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: langchain-gnani
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Gnani integrations for LangChain
|
|
5
|
+
Keywords: langchain,speech-to-text,text-to-speech,gnani
|
|
6
|
+
Author: Gaurav Chaudhary
|
|
7
|
+
Author-email: Gaurav Chaudhary <chaudharygaurav2004@gmail.com>
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Typing :: Typed
|
|
12
|
+
Requires-Dist: gnani-vachana>=0.11.0
|
|
13
|
+
Requires-Dist: httpx>=0.28,<1
|
|
14
|
+
Requires-Dist: langchain-core>=1.8.5,<2
|
|
15
|
+
Requires-Dist: pydantic>=2.7,<3
|
|
16
|
+
Requires-Dist: websockets>=14,<19
|
|
17
|
+
Requires-Python: >=3.11
|
|
18
|
+
Project-URL: Source, https://github.com/ANAMASGARD/langchain-gnani
|
|
19
|
+
Project-URL: Issues, https://github.com/ANAMASGARD/langchain-gnani/issues
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# langchain-gnani
|
|
23
|
+
|
|
24
|
+
Build Hindi, English, and multilingual voice agents with Gnani Prisma speech recognition, a LangChain chat model, and Gnani Timbre speech synthesis. The Python package is community-maintained and MIT-licensed.
|
|
25
|
+
|
|
26
|
+
## Your first spoken reply
|
|
27
|
+
|
|
28
|
+
Install the package on Python 3.11 or later and set `GNANI_API_KEY` in your environment. Obtain a speech-enabled key from the [Gnani platform](https://app.gnani.ai/voice).
|
|
29
|
+
|
|
30
|
+
```sh
|
|
31
|
+
pip install langchain-gnani
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
from pathlib import Path
|
|
36
|
+
from langchain_gnani import GnaniSTT, GnaniTTS
|
|
37
|
+
|
|
38
|
+
stt = GnaniSTT(model="prisma-v3.0", language_code="indic-auto")
|
|
39
|
+
tts = GnaniTTS(model="timbre-v3.0", voice="Shivani", language="auto")
|
|
40
|
+
|
|
41
|
+
question = stt.invoke(Path("question.wav"))
|
|
42
|
+
print(question)
|
|
43
|
+
Path("spoken.wav").write_bytes(tts.invoke(question))
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
`invoke` and `ainvoke` return transcript text or complete audio bytes. Pass a path or a `langchain_core.documents.base.Blob` with an audio MIME type or filename. `stt.transcribe` and `await stt.atranscribe` also return the request ID, detected language and timings when Gnani supplies them. `Runnable.batch` and `abatch` handle independent requests and honor `config={"max_concurrency": 1}` for accounts with a single active request.
|
|
47
|
+
|
|
48
|
+
## Run an agent
|
|
49
|
+
|
|
50
|
+
Clone this repository for the examples. Copy `.env.example` to `.env` on a new checkout. Set `GNANI_API_KEY`, `VOICE_CHAT_MODEL` and the corresponding chat provider credentials. The demo group includes the OpenAI partner package. For instance, `VOICE_CHAT_MODEL=openai:gpt-4.1-mini` uses `OPENAI_API_KEY`. You can also supply a LangChain chat model instance to `build_agent(model)`. Choose a model that can call tools.
|
|
51
|
+
|
|
52
|
+
```sh
|
|
53
|
+
uv sync --locked --group demo
|
|
54
|
+
uv run --no-sync --env-file .env python -m examples.voice_agent question.wav answer.wav
|
|
55
|
+
uv run --no-sync --env-file .env uvicorn examples.browser.server:app --host 127.0.0.1 --port 8000
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Open [the local voice demo](http://127.0.0.1:8000), start the microphone, and ask “What is the status of order 42?” The example agent looks up the sample order and speaks the result. Start speaking during a reply to interrupt it. The browser clears queued playback, and the backend cancels the previous generation. Both API keys stay on the backend. [LangChain voice agents](https://docs.langchain.com/oss/python/langchain/voice-agent)
|
|
59
|
+
|
|
60
|
+
## Speech capabilities
|
|
61
|
+
|
|
62
|
+
| Component | v2.5 | v3.0 | Input and output |
|
|
63
|
+
| --- | --- | --- | --- |
|
|
64
|
+
| Prisma REST | Language selection, number formatting, word boosting and substitution | Automatic language detection, 1–4 language hints, context, `codemix` and `transliterate` | One recording up to 30 seconds → transcript |
|
|
65
|
+
| Prisma WebSocket | VAD tuning, boosting, substitution and session updates | Language detection, context, mixed and transliterated output | Paced mono PCM16 frames → speech-start and completed-segment events |
|
|
66
|
+
| Prisma batch | Long recordings, multiple files, diarization and word boosting | Per-segment language, speaker segments, batch context and `codemix` | Uploaded files, ZIP or public HTTPS URLs → resumable job with per-file results |
|
|
67
|
+
| Timbre REST | Model-specific voices and speeds from 0.85 to 1.15 | Multilingual voices, inline audio tags, speeds 0.8, 1.0 or 1.2 | Text → complete audio in the chosen format |
|
|
68
|
+
| Timbre SSE | Same voices and formats as REST | Same voices and formats as REST | `stream` or `astream` → ordered audio chunks |
|
|
69
|
+
| Timbre WebSocket | Same voices and formats as REST | Same voices and formats as REST | `realtime(text)` → async audio chunks for one phrase |
|
|
70
|
+
|
|
71
|
+
The package defaults to Prisma v2.5 with `en-IN` and Timbre v2.5 with Pranav. Timbre v3.0 defaults to Shivani. Both speech families cover nine Indian languages and English. Voice catalogs are model-specific. Timbre accepts `auto`, regional language codes and `hi-en`. Its output options include WAV, raw PCM, MP3, Ogg Opus and G.711. For streaming WAV, chunks contain PCM samples suitable for playback. Use `invoke` for a complete WAV header. Ogg may arrive as a single chunk. [Prisma models](https://docs.gnani.ai/api/STT/models/overview) · [Timbre voices](https://docs.gnani.ai/api/TTS/available-voices) · [Audio output formats](https://docs.gnani.ai/api/TTS/tts-sse)
|
|
72
|
+
|
|
73
|
+
When composed with an upstream text Runnable, Timbre starts speaking on completed phrases, even while the chat model is still producing tokens. For example, `chat_model | StrOutputParser() | tts` supports sync and async audio streaming. Calling `tts.stream(text)` directly sends the entire supplied text in one synthesis request.
|
|
74
|
+
|
|
75
|
+
### Realtime recognition and synthesis
|
|
76
|
+
|
|
77
|
+
```python
|
|
78
|
+
# Inside an async function; frames come from a microphone or telephony stream.
|
|
79
|
+
async for event in stt.as_streaming_runnable().atransform(frames):
|
|
80
|
+
if event.type == "transcript":
|
|
81
|
+
print(event.text)
|
|
82
|
+
|
|
83
|
+
from contextlib import aclosing
|
|
84
|
+
|
|
85
|
+
async with aclosing(tts.realtime("आपका ऑर्डर तैयार है।")) as chunks:
|
|
86
|
+
async for chunk in chunks:
|
|
87
|
+
await player.write(chunk)
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
At 16 kHz, send one 1,024-byte mono PCM16 frame every 32 ms. For bidirectional control, use `async with stt.realtime(sample_rate=16000) as session`, send frames with `send_audio` while consuming events in a second task, and call `commit()` to finish the current utterance. `update_settings(format="codemix")` updates an open v3.0 session. Context hints (`keyterms`, `topic`, `previous_text` and `speaker_names`) are set when opening the session. Close the TTS iterator when the consumer stops listening. [Prisma realtime protocol](https://docs.gnani.ai/api/STT/stt-websocket)
|
|
91
|
+
|
|
92
|
+
### Batch jobs
|
|
93
|
+
|
|
94
|
+
```python
|
|
95
|
+
from langchain_gnani import GnaniBatchSTT
|
|
96
|
+
|
|
97
|
+
batch = GnaniBatchSTT()
|
|
98
|
+
job = batch.create_job(["call.wav"], model="prisma-v3.0", language_code="indic-auto",
|
|
99
|
+
diarization=True, start=False)
|
|
100
|
+
job.start()
|
|
101
|
+
job = batch.get_job(job.id) # Also works after restarting the application.
|
|
102
|
+
job.wait(timeout=600)
|
|
103
|
+
for recording in job.files():
|
|
104
|
+
print(recording.name, recording.text if recording.ok else recording.error)
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Use `list_jobs`, `job.cancel()`, or the async `acreate_job`, `aget_job`, `alist_jobs` and `atranscribe` methods. Job handles expose speaker segments, file errors and results even when only some files succeed. Batch accepts `keywords` as the SDK spelling of keyterms. It supports `topic`, `topic` with keywords, or speaker names separately. Previous-text hints and transliterated output are available on REST and realtime.
|
|
108
|
+
|
|
109
|
+
Direct file uploads and public HTTPS audio URLs passed live tests. The documented large-file presigned creation route returned HTTP 404 on December 1, 2026. For larger files, provide an accessible HTTPS audio URL subject to Gnani's batch limits. [Batch inputs and limits](https://docs.gnani.ai/api/STTBatch/Introduction)
|
|
110
|
+
|
|
111
|
+
### LangChain tools and tracing
|
|
112
|
+
|
|
113
|
+
Pass application-owned audio storage functions to the tools. Full LangChain tool calls return a `ToolMessage`. Its artifact carries metadata or an audio ID, and the model receives a short text result.
|
|
114
|
+
|
|
115
|
+
```python
|
|
116
|
+
from langchain_gnani.tools import GnaniTranscribeTool, GnaniTextToSpeechTool
|
|
117
|
+
|
|
118
|
+
transcribe = GnaniTranscribeTool(stt=stt, resolve_audio=recordings.__getitem__)
|
|
119
|
+
speak = GnaniTextToSpeechTool(tts=tts, store_audio=save_blob_and_return_id)
|
|
120
|
+
agent = create_agent(chat_model, tools=[transcribe, speak])
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
Runnable configuration supports callbacks, tags and metadata. To trace timings and provider request IDs, mask inputs and outputs on the LangSmith client around the entire voice turn. Configure any application callbacks and LangGraph checkpoints for your own retention requirements. [LangSmith masking](https://docs.langchain.com/langsmith/mask-inputs-outputs)
|
|
124
|
+
|
|
125
|
+
```python
|
|
126
|
+
from langsmith import Client, trace, tracing_context
|
|
127
|
+
|
|
128
|
+
with tracing_context(enabled=True, client=Client(hide_inputs=True, hide_outputs=True)):
|
|
129
|
+
with trace("voice_turn") as run:
|
|
130
|
+
heard = stt.transcribe("question.wav")
|
|
131
|
+
run.add_metadata({"gnani_request_id": heard.request_id,
|
|
132
|
+
"gnani_latency_seconds": heard.end_to_end_latency})
|
|
133
|
+
reply = agent.invoke({"messages": [{"role": "user", "content": heard.text}]})
|
|
134
|
+
audio = tts.invoke(reply["messages"][-1].text)
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
## Development and release checks
|
|
138
|
+
|
|
139
|
+
Develop with Python 3.15 and uv. Ordinary tests use local fixtures, an actual agent graph and LangChain's standard tool suites.
|
|
140
|
+
|
|
141
|
+
```sh
|
|
142
|
+
uv sync --locked
|
|
143
|
+
uv run ruff check .
|
|
144
|
+
uv run mypy src
|
|
145
|
+
uv run pytest -m "not live"
|
|
146
|
+
uv build --no-sources
|
|
147
|
+
uv run python scripts/check_distributions.py
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
For short billable provider tests, set `GNANI_RUN_LIVE=1` and run `uv run --env-file .env pytest tests/test_live.py`. Set `GNANI_TEST_OUTPUT` to a private temporary directory to retain two synthetic recordings. For the browser end-to-end check, start the local demo, install the `browser-test` group and Chromium, set `GNANI_BROWSER_URL` and reuse that recordings directory. Then run `uv run --no-sync pytest tests/test_browser_live.py`. Set `GNANI_CHROME` to use an existing Chrome executable.
|
|
151
|
+
|
|
152
|
+
This standalone integration is licensed under MIT. Voice cloning and Evon chat models are planned follow-ons. [License](LICENSE)
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
# langchain-gnani
|
|
2
|
+
|
|
3
|
+
Build Hindi, English, and multilingual voice agents with Gnani Prisma speech recognition, a LangChain chat model, and Gnani Timbre speech synthesis. The Python package is community-maintained and MIT-licensed.
|
|
4
|
+
|
|
5
|
+
## Your first spoken reply
|
|
6
|
+
|
|
7
|
+
Install the package on Python 3.11 or later and set `GNANI_API_KEY` in your environment. Obtain a speech-enabled key from the [Gnani platform](https://app.gnani.ai/voice).
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
pip install langchain-gnani
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from langchain_gnani import GnaniSTT, GnaniTTS
|
|
16
|
+
|
|
17
|
+
stt = GnaniSTT(model="prisma-v3.0", language_code="indic-auto")
|
|
18
|
+
tts = GnaniTTS(model="timbre-v3.0", voice="Shivani", language="auto")
|
|
19
|
+
|
|
20
|
+
question = stt.invoke(Path("question.wav"))
|
|
21
|
+
print(question)
|
|
22
|
+
Path("spoken.wav").write_bytes(tts.invoke(question))
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
`invoke` and `ainvoke` return transcript text or complete audio bytes. Pass a path or a `langchain_core.documents.base.Blob` with an audio MIME type or filename. `stt.transcribe` and `await stt.atranscribe` also return the request ID, detected language and timings when Gnani supplies them. `Runnable.batch` and `abatch` handle independent requests and honor `config={"max_concurrency": 1}` for accounts with a single active request.
|
|
26
|
+
|
|
27
|
+
## Run an agent
|
|
28
|
+
|
|
29
|
+
Clone this repository for the examples. Copy `.env.example` to `.env` on a new checkout. Set `GNANI_API_KEY`, `VOICE_CHAT_MODEL` and the corresponding chat provider credentials. The demo group includes the OpenAI partner package. For instance, `VOICE_CHAT_MODEL=openai:gpt-4.1-mini` uses `OPENAI_API_KEY`. You can also supply a LangChain chat model instance to `build_agent(model)`. Choose a model that can call tools.
|
|
30
|
+
|
|
31
|
+
```sh
|
|
32
|
+
uv sync --locked --group demo
|
|
33
|
+
uv run --no-sync --env-file .env python -m examples.voice_agent question.wav answer.wav
|
|
34
|
+
uv run --no-sync --env-file .env uvicorn examples.browser.server:app --host 127.0.0.1 --port 8000
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Open [the local voice demo](http://127.0.0.1:8000), start the microphone, and ask “What is the status of order 42?” The example agent looks up the sample order and speaks the result. Start speaking during a reply to interrupt it. The browser clears queued playback, and the backend cancels the previous generation. Both API keys stay on the backend. [LangChain voice agents](https://docs.langchain.com/oss/python/langchain/voice-agent)
|
|
38
|
+
|
|
39
|
+
## Speech capabilities
|
|
40
|
+
|
|
41
|
+
| Component | v2.5 | v3.0 | Input and output |
|
|
42
|
+
| --- | --- | --- | --- |
|
|
43
|
+
| Prisma REST | Language selection, number formatting, word boosting and substitution | Automatic language detection, 1–4 language hints, context, `codemix` and `transliterate` | One recording up to 30 seconds → transcript |
|
|
44
|
+
| Prisma WebSocket | VAD tuning, boosting, substitution and session updates | Language detection, context, mixed and transliterated output | Paced mono PCM16 frames → speech-start and completed-segment events |
|
|
45
|
+
| Prisma batch | Long recordings, multiple files, diarization and word boosting | Per-segment language, speaker segments, batch context and `codemix` | Uploaded files, ZIP or public HTTPS URLs → resumable job with per-file results |
|
|
46
|
+
| Timbre REST | Model-specific voices and speeds from 0.85 to 1.15 | Multilingual voices, inline audio tags, speeds 0.8, 1.0 or 1.2 | Text → complete audio in the chosen format |
|
|
47
|
+
| Timbre SSE | Same voices and formats as REST | Same voices and formats as REST | `stream` or `astream` → ordered audio chunks |
|
|
48
|
+
| Timbre WebSocket | Same voices and formats as REST | Same voices and formats as REST | `realtime(text)` → async audio chunks for one phrase |
|
|
49
|
+
|
|
50
|
+
The package defaults to Prisma v2.5 with `en-IN` and Timbre v2.5 with Pranav. Timbre v3.0 defaults to Shivani. Both speech families cover nine Indian languages and English. Voice catalogs are model-specific. Timbre accepts `auto`, regional language codes and `hi-en`. Its output options include WAV, raw PCM, MP3, Ogg Opus and G.711. For streaming WAV, chunks contain PCM samples suitable for playback. Use `invoke` for a complete WAV header. Ogg may arrive as a single chunk. [Prisma models](https://docs.gnani.ai/api/STT/models/overview) · [Timbre voices](https://docs.gnani.ai/api/TTS/available-voices) · [Audio output formats](https://docs.gnani.ai/api/TTS/tts-sse)
|
|
51
|
+
|
|
52
|
+
When composed with an upstream text Runnable, Timbre starts speaking on completed phrases, even while the chat model is still producing tokens. For example, `chat_model | StrOutputParser() | tts` supports sync and async audio streaming. Calling `tts.stream(text)` directly sends the entire supplied text in one synthesis request.
|
|
53
|
+
|
|
54
|
+
### Realtime recognition and synthesis
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
# Inside an async function; frames come from a microphone or telephony stream.
|
|
58
|
+
async for event in stt.as_streaming_runnable().atransform(frames):
|
|
59
|
+
if event.type == "transcript":
|
|
60
|
+
print(event.text)
|
|
61
|
+
|
|
62
|
+
from contextlib import aclosing
|
|
63
|
+
|
|
64
|
+
async with aclosing(tts.realtime("आपका ऑर्डर तैयार है।")) as chunks:
|
|
65
|
+
async for chunk in chunks:
|
|
66
|
+
await player.write(chunk)
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
At 16 kHz, send one 1,024-byte mono PCM16 frame every 32 ms. For bidirectional control, use `async with stt.realtime(sample_rate=16000) as session`, send frames with `send_audio` while consuming events in a second task, and call `commit()` to finish the current utterance. `update_settings(format="codemix")` updates an open v3.0 session. Context hints (`keyterms`, `topic`, `previous_text` and `speaker_names`) are set when opening the session. Close the TTS iterator when the consumer stops listening. [Prisma realtime protocol](https://docs.gnani.ai/api/STT/stt-websocket)
|
|
70
|
+
|
|
71
|
+
### Batch jobs
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
from langchain_gnani import GnaniBatchSTT
|
|
75
|
+
|
|
76
|
+
batch = GnaniBatchSTT()
|
|
77
|
+
job = batch.create_job(["call.wav"], model="prisma-v3.0", language_code="indic-auto",
|
|
78
|
+
diarization=True, start=False)
|
|
79
|
+
job.start()
|
|
80
|
+
job = batch.get_job(job.id) # Also works after restarting the application.
|
|
81
|
+
job.wait(timeout=600)
|
|
82
|
+
for recording in job.files():
|
|
83
|
+
print(recording.name, recording.text if recording.ok else recording.error)
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Use `list_jobs`, `job.cancel()`, or the async `acreate_job`, `aget_job`, `alist_jobs` and `atranscribe` methods. Job handles expose speaker segments, file errors and results even when only some files succeed. Batch accepts `keywords` as the SDK spelling of keyterms. It supports `topic`, `topic` with keywords, or speaker names separately. Previous-text hints and transliterated output are available on REST and realtime.
|
|
87
|
+
|
|
88
|
+
Direct file uploads and public HTTPS audio URLs passed live tests. The documented large-file presigned creation route returned HTTP 404 on December 1, 2026. For larger files, provide an accessible HTTPS audio URL subject to Gnani's batch limits. [Batch inputs and limits](https://docs.gnani.ai/api/STTBatch/Introduction)
|
|
89
|
+
|
|
90
|
+
### LangChain tools and tracing
|
|
91
|
+
|
|
92
|
+
Pass application-owned audio storage functions to the tools. Full LangChain tool calls return a `ToolMessage`. Its artifact carries metadata or an audio ID, and the model receives a short text result.
|
|
93
|
+
|
|
94
|
+
```python
|
|
95
|
+
from langchain_gnani.tools import GnaniTranscribeTool, GnaniTextToSpeechTool
|
|
96
|
+
|
|
97
|
+
transcribe = GnaniTranscribeTool(stt=stt, resolve_audio=recordings.__getitem__)
|
|
98
|
+
speak = GnaniTextToSpeechTool(tts=tts, store_audio=save_blob_and_return_id)
|
|
99
|
+
agent = create_agent(chat_model, tools=[transcribe, speak])
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
Runnable configuration supports callbacks, tags and metadata. To trace timings and provider request IDs, mask inputs and outputs on the LangSmith client around the entire voice turn. Configure any application callbacks and LangGraph checkpoints for your own retention requirements. [LangSmith masking](https://docs.langchain.com/langsmith/mask-inputs-outputs)
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
from langsmith import Client, trace, tracing_context
|
|
106
|
+
|
|
107
|
+
with tracing_context(enabled=True, client=Client(hide_inputs=True, hide_outputs=True)):
|
|
108
|
+
with trace("voice_turn") as run:
|
|
109
|
+
heard = stt.transcribe("question.wav")
|
|
110
|
+
run.add_metadata({"gnani_request_id": heard.request_id,
|
|
111
|
+
"gnani_latency_seconds": heard.end_to_end_latency})
|
|
112
|
+
reply = agent.invoke({"messages": [{"role": "user", "content": heard.text}]})
|
|
113
|
+
audio = tts.invoke(reply["messages"][-1].text)
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
## Development and release checks
|
|
117
|
+
|
|
118
|
+
Develop with Python 3.15 and uv. Ordinary tests use local fixtures, an actual agent graph and LangChain's standard tool suites.
|
|
119
|
+
|
|
120
|
+
```sh
|
|
121
|
+
uv sync --locked
|
|
122
|
+
uv run ruff check .
|
|
123
|
+
uv run mypy src
|
|
124
|
+
uv run pytest -m "not live"
|
|
125
|
+
uv build --no-sources
|
|
126
|
+
uv run python scripts/check_distributions.py
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
For short billable provider tests, set `GNANI_RUN_LIVE=1` and run `uv run --env-file .env pytest tests/test_live.py`. Set `GNANI_TEST_OUTPUT` to a private temporary directory to retain two synthetic recordings. For the browser end-to-end check, start the local demo, install the `browser-test` group and Chromium, set `GNANI_BROWSER_URL` and reuse that recordings directory. Then run `uv run --no-sync pytest tests/test_browser_live.py`. Set `GNANI_CHROME` to use an existing Chrome executable.
|
|
130
|
+
|
|
131
|
+
This standalone integration is licensed under MIT. Voice cloning and Evon chat models are planned follow-ons. [License](LICENSE)
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "langchain-gnani"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Gnani integrations for LangChain"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.11"
|
|
7
|
+
license = "MIT"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
9
|
+
keywords = [
|
|
10
|
+
"langchain",
|
|
11
|
+
"speech-to-text",
|
|
12
|
+
"text-to-speech",
|
|
13
|
+
"gnani",
|
|
14
|
+
]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Typing :: Typed",
|
|
18
|
+
]
|
|
19
|
+
dependencies = [
|
|
20
|
+
"gnani-vachana>=0.11.0",
|
|
21
|
+
"httpx>=0.28,<1",
|
|
22
|
+
"langchain-core>=1.8.5,<2",
|
|
23
|
+
"pydantic>=2.7,<3",
|
|
24
|
+
"websockets>=14,<19",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
[[project.authors]]
|
|
28
|
+
name = "Gaurav Chaudhary"
|
|
29
|
+
email = "chaudharygaurav2004@gmail.com"
|
|
30
|
+
|
|
31
|
+
[project.urls]
|
|
32
|
+
Source = "https://github.com/ANAMASGARD/langchain-gnani"
|
|
33
|
+
Issues = "https://github.com/ANAMASGARD/langchain-gnani/issues"
|
|
34
|
+
|
|
35
|
+
[build-system]
|
|
36
|
+
requires = ["uv_build>=0.13.8,<0.14.0"]
|
|
37
|
+
build-backend = "uv_build"
|
|
38
|
+
|
|
39
|
+
[tool.pytest.ini_options]
|
|
40
|
+
pythonpath = ["."]
|
|
41
|
+
asyncio_mode = "auto"
|
|
42
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
43
|
+
markers = ["live: calls the billable Gnani service when explicitly enabled"]
|
|
44
|
+
|
|
45
|
+
[[tool.mypy.overrides]]
|
|
46
|
+
module = ["gnani.*"]
|
|
47
|
+
follow_untyped_imports = true
|
|
48
|
+
|
|
49
|
+
[dependency-groups]
|
|
50
|
+
browser-test = ["playwright>=1.48,<2"]
|
|
51
|
+
demo = [
|
|
52
|
+
"fastapi>=0.165.0",
|
|
53
|
+
"langchain>=1,<2",
|
|
54
|
+
"langchain-openai>=1,<2",
|
|
55
|
+
"uvicorn>=0.55.0",
|
|
56
|
+
]
|
|
57
|
+
dev = [
|
|
58
|
+
"langchain>=1,<2",
|
|
59
|
+
"langchain-tests==1.2.0",
|
|
60
|
+
"mypy>=2.4.1",
|
|
61
|
+
"pytest>=9.2.0",
|
|
62
|
+
"pytest-asyncio>=1.5.0",
|
|
63
|
+
"ruff>=0.17.6",
|
|
64
|
+
]
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "langchain-gnani"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Gnani integrations for LangChain"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
authors = [
|
|
7
|
+
{ name = "Gaurav Chaudhary", email = "chaudharygaurav2004@gmail.com" }
|
|
8
|
+
]
|
|
9
|
+
requires-python = ">=3.11"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
keywords = ["langchain", "speech-to-text", "text-to-speech", "gnani"]
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Programming Language :: Python :: 3",
|
|
15
|
+
"Typing :: Typed",
|
|
16
|
+
]
|
|
17
|
+
dependencies = [
|
|
18
|
+
"gnani-vachana>=0.11.0",
|
|
19
|
+
"httpx>=0.28,<1",
|
|
20
|
+
"langchain-core>=1.8.5,<2",
|
|
21
|
+
"pydantic>=2.7,<3",
|
|
22
|
+
"websockets>=14,<19",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
[build-system]
|
|
26
|
+
requires = ["uv_build>=0.13.8,<0.14.0"]
|
|
27
|
+
build-backend = "uv_build"
|
|
28
|
+
|
|
29
|
+
[project.urls]
|
|
30
|
+
Source = "https://github.com/ANAMASGARD/langchain-gnani"
|
|
31
|
+
Issues = "https://github.com/ANAMASGARD/langchain-gnani/issues"
|
|
32
|
+
|
|
33
|
+
[tool.pytest.ini_options]
|
|
34
|
+
pythonpath = ["."]
|
|
35
|
+
asyncio_mode = "auto"
|
|
36
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
37
|
+
markers = ["live: calls the billable Gnani service when explicitly enabled"]
|
|
38
|
+
|
|
39
|
+
[[tool.mypy.overrides]]
|
|
40
|
+
module = ["gnani.*"]
|
|
41
|
+
follow_untyped_imports = true
|
|
42
|
+
|
|
43
|
+
[dependency-groups]
|
|
44
|
+
browser-test = [
|
|
45
|
+
"playwright>=1.48,<2",
|
|
46
|
+
]
|
|
47
|
+
demo = [
|
|
48
|
+
"fastapi>=0.165.0",
|
|
49
|
+
"langchain>=1,<2",
|
|
50
|
+
"langchain-openai>=1,<2",
|
|
51
|
+
"uvicorn>=0.55.0",
|
|
52
|
+
]
|
|
53
|
+
dev = [
|
|
54
|
+
"langchain>=1,<2",
|
|
55
|
+
"langchain-tests==1.2.0",
|
|
56
|
+
"mypy>=2.4.1",
|
|
57
|
+
"pytest>=9.2.0",
|
|
58
|
+
"pytest-asyncio>=1.5.0",
|
|
59
|
+
"ruff>=0.17.6",
|
|
60
|
+
]
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""Gnani integrations for LangChain."""
|
|
2
|
+
|
|
3
|
+
from gnani.tts import AudioConfig
|
|
4
|
+
|
|
5
|
+
from ._common import GnaniStreamError
|
|
6
|
+
from .batch import GnaniBatchSTT
|
|
7
|
+
from .realtime import TranscriptEvent
|
|
8
|
+
from .stt import GnaniSTT, Substitution, Transcript
|
|
9
|
+
from .tts import GnaniTTS
|
|
10
|
+
|
|
11
|
+
__all__ = [
|
|
12
|
+
"AudioConfig",
|
|
13
|
+
"GnaniBatchSTT",
|
|
14
|
+
"GnaniSTT",
|
|
15
|
+
"GnaniStreamError",
|
|
16
|
+
"GnaniTTS",
|
|
17
|
+
"Substitution",
|
|
18
|
+
"Transcript",
|
|
19
|
+
"TranscriptEvent",
|
|
20
|
+
]
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Shared authentication and transport settings for LangChain speech components."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from typing import Generic, TypeVar
|
|
7
|
+
from urllib.parse import urlsplit, urlunsplit
|
|
8
|
+
from uuid import uuid4
|
|
9
|
+
|
|
10
|
+
from langchain_core.runnables import RunnableSerializable
|
|
11
|
+
from pydantic import ConfigDict, Field, SecretStr
|
|
12
|
+
|
|
13
|
+
Input = TypeVar("Input")
|
|
14
|
+
Output = TypeVar("Output")
|
|
15
|
+
DEFAULT_BASE_URL = "https://api.vachana.ai"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class GnaniStreamError(RuntimeError):
|
|
19
|
+
"""The speech service reported an error or the stream ended prematurely."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class SpeechRunnable(RunnableSerializable[Input, Output], Generic[Input, Output]):
|
|
23
|
+
model_config = ConfigDict(extra="forbid")
|
|
24
|
+
api_key: SecretStr | None = Field(default=None, exclude=True, repr=False)
|
|
25
|
+
base_url: str = DEFAULT_BASE_URL
|
|
26
|
+
timeout: int = Field(default=60, gt=0)
|
|
27
|
+
|
|
28
|
+
def _key(self) -> str:
|
|
29
|
+
key = (
|
|
30
|
+
self.api_key.get_secret_value()
|
|
31
|
+
if self.api_key
|
|
32
|
+
else os.getenv("GNANI_API_KEY")
|
|
33
|
+
)
|
|
34
|
+
if not key:
|
|
35
|
+
raise ValueError(
|
|
36
|
+
"Set GNANI_API_KEY or pass api_key to the speech component"
|
|
37
|
+
)
|
|
38
|
+
return key
|
|
39
|
+
|
|
40
|
+
def _headers(self) -> dict[str, str]:
|
|
41
|
+
return {"X-API-Key-ID": self._key(), "X-API-Request-ID": str(uuid4())}
|
|
42
|
+
|
|
43
|
+
def _url(self, path: str) -> str:
|
|
44
|
+
return self.base_url.rstrip("/") + path
|
|
45
|
+
|
|
46
|
+
def _ws_url(self, path: str) -> str:
|
|
47
|
+
url = urlsplit(self._url(path))
|
|
48
|
+
if url.scheme not in {"http", "https"}:
|
|
49
|
+
raise ValueError("base_url must be an HTTP or HTTPS URL")
|
|
50
|
+
return urlunsplit(
|
|
51
|
+
("wss" if url.scheme == "https" else "ws", url.netloc, url.path, "", "")
|
|
52
|
+
)
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""Provider batch jobs, kept separate from LangChain Runnable.batch()."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import AsyncIterator
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from gnani.stt import (
|
|
9
|
+
AsyncBatchJob,
|
|
10
|
+
AsyncBatchResult,
|
|
11
|
+
AsyncGnaniSTTBatchClient,
|
|
12
|
+
GnaniSTTBatchClient,
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
from ._common import DEFAULT_BASE_URL
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class GnaniBatchSTT(GnaniSTTBatchClient):
|
|
19
|
+
"""Sync and async access to Prisma jobs and their per-file transcript results.
|
|
20
|
+
|
|
21
|
+
create_job(), get_job() and list_jobs() return SDK job handles. Each handle
|
|
22
|
+
can start, wait, cancel, refresh and fetch files. Use the a-prefixed methods
|
|
23
|
+
for async handles and await their operations.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
def __init__(
|
|
27
|
+
self,
|
|
28
|
+
api_key: str | None = None,
|
|
29
|
+
*,
|
|
30
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
31
|
+
timeout: int = 60,
|
|
32
|
+
upload_timeout: int = 600,
|
|
33
|
+
) -> None:
|
|
34
|
+
super().__init__(
|
|
35
|
+
api_key, base_url=base_url, timeout=timeout, upload_timeout=upload_timeout
|
|
36
|
+
)
|
|
37
|
+
self._async_client = AsyncGnaniSTTBatchClient(
|
|
38
|
+
api_key, base_url=base_url, timeout=timeout, upload_timeout=upload_timeout
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
async def acreate_job(
|
|
42
|
+
self, files: Any, language_code: str = "en-IN", **options: Any
|
|
43
|
+
) -> AsyncBatchJob:
|
|
44
|
+
return await self._async_client.create_job(files, language_code, **options)
|
|
45
|
+
|
|
46
|
+
async def aget_job(self, job_id: str) -> AsyncBatchJob:
|
|
47
|
+
return await self._async_client.get_job(job_id)
|
|
48
|
+
|
|
49
|
+
def alist_jobs(
|
|
50
|
+
self, *, status: str | None = None, limit: int = 20
|
|
51
|
+
) -> AsyncIterator[AsyncBatchJob]:
|
|
52
|
+
return self._async_client.list_jobs(status=status, limit=limit)
|
|
53
|
+
|
|
54
|
+
async def atranscribe(
|
|
55
|
+
self, files: Any, language_code: str = "en-IN", **options: Any
|
|
56
|
+
) -> AsyncBatchResult:
|
|
57
|
+
return await self._async_client.transcribe(files, language_code, **options)
|
|
File without changes
|