Metadata-Version: 2.4
Name: langchain-gnani
Version: 0.1.1
Summary: Gnani integrations for LangChain
Keywords: langchain,speech-to-text,text-to-speech,gnani
Author: Gaurav Chaudhary
Author-email: Gaurav Chaudhary <chaudharygaurav2004@gmail.com>
License-Expression: MIT
License-File: LICENSE
Classifier: Programming Language :: Python :: 3
Classifier: Typing :: Typed
Requires-Dist: gnani-vachana>=0.11.0
Requires-Dist: httpx>=0.28,<1
Requires-Dist: langchain-core>=1.8.5,<2
Requires-Dist: pydantic>=2.7,<3
Requires-Dist: websockets>=14,<19
Requires-Python: >=3.11
Project-URL: Source, https://github.com/ANAMASGARD/langchain-gnani
Project-URL: Issues, https://github.com/ANAMASGARD/langchain-gnani/issues
Description-Content-Type: text/markdown

![Gnani AI and LangChain](https://raw.githubusercontent.com/ANAMASGARD/langchain-gnani/v0.1.1/assets/gnani-langchain-banner.png)

# langchain-gnani

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.

## Your first spoken reply

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).

```sh
pip install langchain-gnani
```

```python
from pathlib import Path
from langchain_gnani import GnaniSTT, GnaniTTS

stt = GnaniSTT(model="prisma-v3.0", language_code="indic-auto")
tts = GnaniTTS(model="timbre-v3.0", voice="Shivani", language="auto")

question = stt.invoke(Path("question.wav"))
print(question)
Path("spoken.wav").write_bytes(tts.invoke(question))
```

`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.

## Run an agent

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.

```sh
uv sync --locked --group demo
uv run --no-sync --env-file .env python -m examples.voice_agent question.wav answer.wav
uv run --no-sync --env-file .env uvicorn examples.browser.server:app --host 127.0.0.1 --port 8000
```

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)

## Speech capabilities

| Component | v2.5 | v3.0 | Input and output |
| --- | --- | --- | --- |
| 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 |
| 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 |
| 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 |
| 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 |
| Timbre SSE | Same voices and formats as REST | Same voices and formats as REST | `stream` or `astream` → ordered audio chunks |
| Timbre WebSocket | Same voices and formats as REST | Same voices and formats as REST | `realtime(text)` → async audio chunks for one phrase |

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)

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.

### Realtime recognition and synthesis

```python
# Inside an async function; frames come from a microphone or telephony stream.
async for event in stt.as_streaming_runnable().atransform(frames):
    if event.type == "transcript":
        print(event.text)

from contextlib import aclosing

async with aclosing(tts.realtime("आपका ऑर्डर तैयार है।")) as chunks:
    async for chunk in chunks:
        await player.write(chunk)
```

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)

### Batch jobs

```python
from langchain_gnani import GnaniBatchSTT

batch = GnaniBatchSTT()
job = batch.create_job(["call.wav"], model="prisma-v3.0", language_code="indic-auto",
                       diarization=True, start=False)
job.start()
job = batch.get_job(job.id)  # Also works after restarting the application.
job.wait(timeout=600)
for recording in job.files():
    print(recording.name, recording.text if recording.ok else recording.error)
```

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.

For recordings above the Python SDK's 10 MiB direct-upload limit, pass an HTTPS **download URL**. Gnani can fetch a public audio file or a time-limited GET URL from your object store. Allow enough time for the job to start and the download to finish. Gnani documents a four-hour recording limit and a 30-minute download limit. [Batch inputs and limits](https://docs.gnani.ai/api/STTBatch/Introduction#limits)

```python
result = batch.transcribe([download_url], language_code="en-IN", model="prisma-v3.0")
print(result[0].text)
```

On December 1, 2026, Prisma v2.5 and v3.0 each completed an 11.30 MiB WAV using this method. Gnani also documents a separate route for obtaining an **upload URL**, `POST /stt/v3/batch/v2/jobs`. The production API returned HTTP 404 at job creation, before issuing any storage URL. [Presigned upload instructions](https://docs.gnani.ai/api/STTBatch/Create_Job#presigned-upload-large-files) · [Upstream issue #8](https://github.com/Gnani-AI-Mintlify/gnani-vachana/issues/8)

### LangChain tools and tracing

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.

```python
from langchain_gnani.tools import GnaniTranscribeTool, GnaniTextToSpeechTool

transcribe = GnaniTranscribeTool(stt=stt, resolve_audio=recordings.__getitem__)
speak = GnaniTextToSpeechTool(tts=tts, store_audio=save_blob_and_return_id)
agent = create_agent(chat_model, tools=[transcribe, speak])
```

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)

```python
from langsmith import Client, trace, tracing_context

with tracing_context(enabled=True, client=Client(hide_inputs=True, hide_outputs=True)):
    with trace("voice_turn") as run:
        heard = stt.transcribe("question.wav")
        run.add_metadata({"gnani_request_id": heard.request_id,
                          "gnani_latency_seconds": heard.end_to_end_latency})
        reply = agent.invoke({"messages": [{"role": "user", "content": heard.text}]})
        audio = tts.invoke(reply["messages"][-1].text)
```

## Development and release checks

Develop with Python 3.15 and uv. Ordinary tests use local fixtures, an actual agent graph and LangChain's standard tool suites.

```sh
uv sync --locked
uv run ruff check .
uv run mypy src
uv run pytest -m "not live"
uv build --no-sources
uv run python scripts/check_distributions.py
```

For billable provider tests, set `GNANI_RUN_LIVE=1` and run `uv run --env-file .env pytest tests/test_live.py`. Use `-k large_batch` to exercise the presigned upload and HTTPS download paths with a three-minute recording, or `-k "not large_batch"` to run just the short fixtures. 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.

This standalone integration is licensed under MIT. Voice cloning and Evon chat models are planned follow-ons. [License](LICENSE)
