-
Notifications
You must be signed in to change notification settings - Fork 153
feat(core): audio file/URL constructors and representation-aware capability guards #1601
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jakelorocco
wants to merge
3
commits into
generative-computing:main
Choose a base branch
from
jakelorocco:feat/audio-input
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,233 @@ | ||
| --- | ||
| title: "Use Speech and Audio Input" | ||
| description: "Pass audio to instruct() and chat() calls, and check which backends can send it." | ||
| sidebar_label: "Use Speech and Audio" | ||
| # diataxis: how-to | ||
| --- | ||
|
|
||
| Mellea can send audio alongside your text prompt: pass it to any `instruct()` or `chat()` | ||
| call using the `audio` parameter. | ||
|
|
||
| **Prerequisites:** an audio-capable model reachable through an OpenAI-compatible endpoint, | ||
| and an audio file. | ||
|
|
||
| > **Backend note:** Only the OpenAI-compatible backends can send audio. `OllamaModelBackend`, | ||
| > `WatsonxAIBackend`, and `LocalHFBackend` raise a `ValueError` rather than silently dropping | ||
| > the clip — see [Backend support](#backend-support) below. | ||
|
|
||
| --- | ||
|
|
||
| ## Basic usage | ||
|
|
||
| `audio` takes a list of audio blocks. Build one with the constructor that matches your | ||
| source — `from_file` for a path on disk: | ||
|
|
||
| ```python | ||
| # Requires: mellea | ||
| # Returns: str | ||
| from mellea import start_session | ||
| from mellea.core import AudioBlock | ||
|
|
||
| m = start_session("openai", model_id="gpt-audio-1.5") | ||
|
|
||
| result = m.instruct( | ||
| "Transcribe the speech in this clip.", | ||
| audio=[AudioBlock.from_file("speech.wav")], | ||
| ) | ||
| print(str(result)) | ||
| # Output will vary — LLM responses depend on model and temperature. | ||
| ``` | ||
|
|
||
| `audio` deliberately does **not** accept bare paths or URLs. Converting them is an | ||
| explicit step, so the type you pass says exactly what will be sent and any read or | ||
| download failure surfaces where you wrote it rather than mid-request. | ||
|
|
||
| --- | ||
|
|
||
| ## Choosing a constructor | ||
|
|
||
| | Source | Use | | ||
| | ------ | --- | | ||
| | A file on disk | `AudioBlock.from_file(path)` | | ||
| | Bytes in memory | `AudioBlock.from_bytes(data)` | | ||
| | A remote URL, fetched now | `AudioBlock.from_url(url)` | | ||
| | A remote URL, fetched at send time and cached | `AudioUrlBlock(url, format=...)` | | ||
| | Base64 you already have | `AudioBlock(value, format=...)` | | ||
|
|
||
| `from_file`, `from_bytes`, and `from_url` all detect the format from the data's magic | ||
| bytes, so a mislabelled file is reported accurately — a WAV named `.mp3` yields | ||
| `format == "wav"`: | ||
|
|
||
| ```python | ||
| # Requires: mellea | ||
| # Returns: str | ||
| from mellea.core import AudioBlock | ||
|
|
||
| # `speech.mp3` here is actually a WAV file that was given the wrong extension. | ||
| clip = AudioBlock.from_file("speech.mp3") | ||
| print(clip.format) # "wav" — read from the file's contents, not its name | ||
| ``` | ||
|
|
||
| ```python | ||
| # Requires: mellea, requests | ||
| # Returns: AudioBlock | ||
| import requests | ||
| from mellea.core import AudioBlock | ||
|
|
||
| wav = requests.get("https://cdn.openai.com/API/docs/audio/alloy.wav").content | ||
| clip = AudioBlock.from_bytes(wav) | ||
| ``` | ||
|
|
||
| Pass `format=` explicitly to skip detection when you already know it, or when the payload | ||
| is not one mellea recognises: | ||
|
|
||
| ```python | ||
| # Requires: mellea | ||
| # Returns: AudioBlock | ||
| from mellea.core import AudioBlock | ||
|
|
||
| clip = AudioBlock.from_file("recording.opus", format="opus") | ||
| ``` | ||
|
|
||
| You can also construct a block from base64 directly. With a data URI the format is read from | ||
| the MIME type; with raw base64 you must supply `format`: | ||
|
|
||
| ```python | ||
| # Requires: mellea | ||
| # Returns: None | ||
| import base64 | ||
| from mellea.core import AudioBlock | ||
|
|
||
| with open("speech.wav", "rb") as f: | ||
| b64 = base64.b64encode(f.read()).decode() | ||
|
|
||
| from_data_uri = AudioBlock(f"data:audio/wav;base64,{b64}") # format inferred | ||
| from_raw = AudioBlock(b64, format="wav") # format required | ||
| ``` | ||
|
|
||
| ### Remote audio | ||
|
|
||
| OpenAI Chat Completions has no audio-by-URL content part, so Mellea downloads the clip and | ||
| inlines it for you. There are two ways, differing only in *when* the fetch happens. | ||
|
|
||
| `AudioBlock.from_url()` downloads immediately, so a bad URL fails at the call site: | ||
|
|
||
| ```python | ||
| # Requires: mellea | ||
| # Returns: AudioBlock | ||
| from mellea.core import AudioBlock | ||
|
|
||
| clip = AudioBlock.from_url("https://example.com/speech.wav") | ||
| print(clip.format) # detected from the downloaded bytes | ||
| ``` | ||
|
|
||
| `AudioUrlBlock` defers the download to send time and memoizes it per URL, so a clip reused | ||
| across several turns is fetched once: | ||
|
|
||
| ```python | ||
| # Requires: mellea | ||
| # Returns: str | ||
| from mellea import start_session | ||
| from mellea.core import AudioUrlBlock | ||
|
|
||
| m = start_session("openai", model_id="gpt-audio-1.5") | ||
|
|
||
| clip = AudioUrlBlock("https://example.com/speech.wav", format="wav") | ||
| result = m.instruct("Transcribe this clip.", audio=[clip]) | ||
| print(str(result)) | ||
| # Output will vary — LLM responses depend on model and temperature. | ||
| ``` | ||
|
|
||
| Prefer `AudioUrlBlock` when the same URL is used repeatedly; prefer `from_url` when you | ||
| want the failure surfaced eagerly. Downloads are capped at 50 MB with a 30-second | ||
| timeout, and `AudioUrlBlock` requires an explicit `format` because nothing has been | ||
| fetched yet at construction time. | ||
|
|
||
| > **Note:** some servers do accept audio by URL through non-standard extensions to the | ||
| > OpenAI schema — [vLLM's `audio_url`](https://docs.vllm.ai/en/v0.6.2/getting_started/examples/openai_audio_api_client.html) | ||
| > is one. Mellea always downloads and inlines instead, which works everywhere. Passing a | ||
| > URL straight through to a server that supports it would be a future addition, gated on | ||
| > detecting such a server; it would let the download and cache be skipped. | ||
|
|
||
| --- | ||
|
|
||
| ## Supported formats | ||
|
|
||
| OpenAI Chat Completions accepts only `wav` and `mp3` for audio input. Other | ||
| OpenAI-compatible servers may accept more, so mellea does not restrict the format it sends — | ||
| `flac` and `ogg` are detected and passed through, and an explicit `format=` is always | ||
| honoured. If a server rejects a format, that surfaces as a server-side error. | ||
|
|
||
| **Mellea does not transcode audio.** Convert the file yourself (for example with `ffmpeg`), | ||
| or transcribe it to text and pass the transcript as part of your prompt. | ||
|
|
||
| Format detection covers `wav`, `mp3`, `flac`, and `ogg`. When the bytes match none of these | ||
| and you did not pass `format=`, construction raises: | ||
|
|
||
| ```python | ||
| # Requires: mellea | ||
| # Returns: None | ||
| from mellea.core import AudioBlock | ||
|
|
||
| try: | ||
| AudioBlock.from_file("notes.txt") | ||
| except ValueError as e: | ||
| print(e) | ||
| # Could not identify the audio format of 'notes.txt'. Pass format explicitly ... | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## Multi-turn audio with ChatContext | ||
|
|
||
| Audio passed to `instruct()` or `chat()` is stored in the | ||
| [`ChatContext`](../reference/glossary.md) turn history, so later calls in the same session | ||
| can refer back to the clip without passing it again: | ||
|
|
||
| ```python | ||
| # Requires: mellea | ||
| # Returns: None | ||
| from mellea import start_session | ||
| from mellea.core import AudioBlock | ||
| from mellea.stdlib.context import ChatContext | ||
|
|
||
| m = start_session("openai", model_id="gpt-audio-1.5", ctx=ChatContext()) | ||
|
|
||
| # First turn — attach the clip | ||
| r1 = m.instruct("Transcribe this clip.", audio=[AudioBlock.from_file("meeting.wav")]) | ||
| print(str(r1)) | ||
|
|
||
| # Second turn — the clip is still in context | ||
| r2 = m.instruct("Summarise the main point in one sentence.") | ||
| print(str(r2)) | ||
| ``` | ||
|
|
||
| > **Cost warning:** the clip is re-sent on the wire on *every* subsequent turn, not just the | ||
| > first. Audio is far larger than text — a few minutes of WAV is megabytes of base64 and | ||
| > thousands of audio tokens — so a long conversation over one clip gets expensive quickly. | ||
| > For extended multi-turn work over the same audio, consider transcribing once and | ||
| > continuing over the transcript. | ||
|
|
||
| --- | ||
|
|
||
| ## Backend support | ||
|
|
||
| | Backend | Audio support | Notes | | ||
| | ------- | ------------- | ----- | | ||
| | `OpenAIBackend` | ✓ | Requires an audio-capable model | | ||
| | `LiteLLMBackend` | ✓ | Depends on the underlying provider and model | | ||
| | `OllamaModelBackend` | ✗ | Ollama's chat API has no audio input | | ||
| | `WatsonxAIBackend` | ✗ | The chat path carries no audio | | ||
| | `LocalHFBackend` | ✗ | Would require a processor-based audio model | | ||
|
|
||
| The ✗ backends raise a `ValueError` when handed audio. This is deliberate: silently dropping | ||
| the clip would send a text-only prompt and produce a confident answer about audio the model | ||
| never received. | ||
|
|
||
| > **Full example:** [`docs/examples/audio_text_models/audio_examples.py`](https://github.com/generative-computing/mellea/blob/main/docs/examples/audio_text_models/audio_examples.py) | ||
| > **Serving audio via `m serve`:** [`docs/examples/m_serve/multimodal-audio/`](https://github.com/generative-computing/mellea/tree/main/docs/examples/m_serve/multimodal-audio) | ||
|
|
||
| --- | ||
|
|
||
| **See also:** [Use Images and Vision Models](../how-to/use-images-and-vision.md) | | ||
| [Working with Data](../how-to/working-with-data.md) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is something that Claude picked up, though it seems fairly minor as I don't think we would hit this very often. Mentioning it as better safe than sorry, but could also see ignoring this:
_generate_from_intrinsicserializes context messages atopenai.py:760without a prefetch, so anAudioUrlBlockthere resolves via the blockingresolve_base64()on the event loop.The cache added here (here being L1013) makes this a hit in almost every real ordering, since any prior generation on the standard path warms it. The one case it misses is an intrinsic called on a context no generation has touched, which is the documented pattern for the intrinsic helpers (
check_certainty(context, backend)over a hand-builtChatContext). Worst case is one bounded 30 s download, not wrong output.Suggest adding this after line 748 for symmetry with the standard path: