AI AgentsLangChain
How do you manage multimodal message content?
Question 308 of 324 · Updated
On this page
- Direct answer
- 1. Multimodal content is an ordered task input
- 2. Construct text and image blocks
- Base64 representation
- 3. Choose URL, inline bytes or uploaded-file reference
- 4. Handle audio, video and documents according to capability
- 5. Validate actual files before message construction
- 6. Capability-aware routing and context budgets
- 7. Tested Python: narrow WAV admission and safe routing
- 8. Secure asset handling, privacy and URL access
- 9. Fallback must preserve the requested evidence
- 10. Production testing and monitoring
- Interview-ready answer
- Official documentation research leads and verification status
Direct answer#
In LangChain, construct a message with an ordered list of typed content blocks for text and supported media, then use a model integration that supports the required modalities and source representations. Modern message APIs expose a standardized content_blocks view and can accept standard multimodal blocks such as image blocks with URL or Base64 data, subject to the installed adapter's compatibility. Provider-native blocks are also possible, but their schemas are not automatically portable.
In production, put a media admission and capability-selection boundary before constructing the message. Verify file ownership and disclosure permission, inspect actual file contents, impose byte and decoded-resource limits, choose a compatible provider profile, and account for media-specific context and cost. Preserve evidence identifiers and explicitly disclose modality loss when using an OCR, transcription or frame-extraction fallback. A model that received a transcript has not necessarily inspected the original audio.
LangChain #26 (#306) introduces message objects and content blocks; #27 (#307) establishes message role and trusted origin. This lesson focuses on the media lifecycle from upload or authorized reference through validated representation, model admission and evidence-grounded response. It does not repeat role taxonomy, general conversation storage or multimodal RAG indexing.
1. Multimodal content is an ordered task input#
Imagine a fictional maintenance-support agent receiving a photo of a control-panel label, a short recording of a machine, and a manual excerpt. The user's question identifies what information matters. Each asset may supply different evidence. A model that supports image input is not necessarily capable of interpreting audio, video or PDFs, even if all of these can be represented as message blocks.
| Modality | Example use | Information not captured by a simple text conversion |
|---|---|---|
| Text | User question and instructions | Not applicable |
| Image | Read a label or inspect a diagram | Layout, relative position, visual features |
| Audio | Transcribe speech or inspect a sound | Timing, pitch, background sounds, multiple speakers |
| Video | Understand a sequence of visible events | Motion, temporal order, changes between frames |
| Document | Read a manual or report | Page layout, scanned text, tables, diagrams and footnotes |
A document can contain several modalities internally. A PDF with selectable text is different from a scanned PDF, and an image of a table is different from the structured cells of a spreadsheet. Choose the processing representation according to the task's evidence requirements, not merely its file extension.
Keep media associated with a stable application-owned asset ID, source revision and the appropriate position in the message. For example, "Compare the first and second photos" depends on preserving their order and identity. If a file is replaced after the original upload, do not silently send the replacement under the old identity.
This diagram describes the application pipeline. It is not a built-in LangChain graph or proof that every adapter accepts the same media types.
2. Construct text and image blocks#
Modern LangChain message APIs provide standardized content representations for supported modalities. A common pattern is to construct HumanMessage with an ordered list of text and image blocks. The following illustration assumes the URL was generated by a trusted media service for an already authorized asset.
PYTHONfrom langchain_core.messages import HumanMessage def build_image_request(approved_https_url: str): return HumanMessage(content=[ {"type": "text", "text": "Read the visible fictional equipment label. " "Report uncertainty if it is not legible."}, {"type": "image", "url": approved_https_url}, ]) # In a compatible deployment: # result = agent.invoke({"messages": [build_image_request(approved_url)]})
The example uses a modern standard image-block representation. A compatible integration may also accept provider-specific image_url blocks or other native representations. Check the selected framework and model adapter; do not assume every integration can serialize every standard or native block.
SDK verification limitation: Local Python 3.13.5 inspection confirmed that langchain, langchain_core and langgraph are absent. All SDK snippets are illustrative and unexecuted. The standalone WAV validation and routing program in section 7 was actually executed and passed all 15 checks. Current provider support, block syntax, file upload APIs and live message conversion were not verified under the authorized offline research exception.
An image URL is not the image itself. The recipient must be able to retrieve the intended bytes, and the URL must remain usable for the required request lifetime. The media service should resolve an application-owned asset reference and issue a narrowly scoped, short-lived read URL if that delivery method is approved. Do not forward an arbitrary client-supplied URL as though it were a trusted internal asset.
Base64 representation#
For small validated files, inline Base64 can be useful when the provider supports that media type and source format. It represents binary data as ASCII characters. Base64 is not encryption or compression.
PYTHONimport base64 from langchain_core.messages import HumanMessage def build_inline_image(validated_png: bytes): data = base64.b64encode(validated_png).decode("ascii") return HumanMessage(content=[ {"type": "text", "text": "Describe the visible fictional label."}, {"type": "image", "base64": data, "mime_type": "image/png"}, ])
This SDK example assumes the bytes have already passed a real image parser and policy checks. It is not a PNG validator. The modern standardized image block shown here is illustrative; a provider-native adapter might require a data URI such as data:image/png;base64,... or a different nested object. Do not add a data URI prefix to a field that expects only Base64 data. Validate actual outbound conversion using synthetic media.
3. Choose URL, inline bytes or uploaded-file reference#
| Representation | Advantages | Operational concerns |
|---|---|---|
| Approved HTTPS URL | Smaller application JSON, possible separate asset lifetime | Expiry, remote access, redirects, disclosure to recipient, changing bytes |
| Inline Base64 | Self-contained request with exact encoded bytes | Request-size overhead, memory copies, accidental logging |
| Provider file ID | Reuse an uploaded asset where supported | Provider-specific lifetime, access, retention, region and deletion |
| Internal asset ID | Stable application reference, access and revision management | Must resolve to a supported provider representation before inference |
A provider file ID is not a universal LangChain file locator. It may be meaningful only to the service and account that created it. An internal asset ID should not be passed directly to a provider unless the adapter explicitly supports resolving it. Keep the mapping in trusted application code.
For n binary bytes, standard Base64 encoding with padding has 4 times the ceiling of n divided by 3 characters. An exactly 3 MiB file (3,145,728 bytes) becomes 4,194,304 Base64 characters, approximately 4 MiB before JSON and message overhead. This is a transport-size calculation, not an estimate of image tokens or model billing. Additional memory may be consumed by decoding, JSON serialization and network buffers.
A limit on encoded length can prevent some oversized decoding allocations, but also check the exact decoded length. Count all media and text in the complete request. Several individually valid files can collectively exceed an application or provider request budget.
4. Handle audio, video and documents according to capability#
A compatible modern standardized message interface can represent media blocks for supported types. In particular, an audio block may include Base64 data and MIME type. A document may use a file-type block, and video may have a dedicated representation. Exact keys and accepted formats vary by version and provider, so the following audio example is an illustrative use of a validated asset rather than a universal recipe.
PYTHONimport base64 from langchain_core.messages import HumanMessage # validated is the Audio object from section 7. def build_audio_request(validated): return HumanMessage(content=[ {"type": "text", "text": "Transcribe the spoken words if intelligible. " "Mark uncertain segments."}, {"type": "audio", "base64": base64.b64encode(validated.data).decode("ascii"), "mime_type": validated.mime}, ])
Check support for the actual audio encoding, sample rate, channels and duration. A container labeled WAV can contain different encodings; MIME type alone does not establish compatibility. Some models accept only a narrower set of audio formats or require uploaded file references.
For video, establish whether native temporal input is supported. A sampled-frame approach may be acceptable for a task that only asks what appears in selected frames. It may miss brief events, motion or audio. Preserve timestamps and document sampling coverage. Do not represent selected frames as complete inspection of the entire video.
For documents, establish whether the native integration accepts the exact type, size, page count and input representation. When extracting text or OCR, retain the original asset ID, page and region references. A text extractor may omit diagrams, tables, handwritten notes or scans. Use an appropriate image or document-processing path when these are required.
| Task | Candidate path | Acceptance limitation |
|---|---|---|
| Read text on a clear image | Native vision or approved OCR | OCR may lose layout and visual context |
| Transcribe a speech recording | Native audio or authorized transcription | Transcript must represent uncertainty |
| Compare two mechanical sounds | Native audio with verified capability | Transcript alone cannot preserve acoustic evidence |
| Describe a visible event in a video | Native video or reviewed frame sampling | Sampling can omit transient events |
| Find a clause in a text PDF | Native document input or page-aware text extraction | Page and version provenance required |
| Analyze a scanned diagram | Vision or native document processing that retains the diagram | Text-only extraction may be insufficient |
These are application design options, not verified claims about particular currently available models. A multimodal input capability also does not imply that the model can generate output in that modality.
5. Validate actual files before message construction#
Treat the filename, extension, client-provided MIME type and content-length header as hints, not trusted proof. Validate media using a suitable parser and resource limits. A signature check can identify obvious mismatches but cannot prove that a file is valid or safe.
A robust media policy imposes limits at several stages:
| Media type | Examples of independent limits |
|---|---|
| All files | Raw bytes, request count, aggregate bytes, upload deadline |
| Images | Decoded width, height, pixel count, animation frames, metadata size |
| Audio | Codec, sample rate, channels, duration, decoded samples |
| Video | Duration, dimensions, frame rate, decoded frame count, tracks |
| Documents | Pages, embedded images, expansion size, parser CPU and memory |
| URLs | Approved origin, access scope, redirects, response bytes and timeout |
A highly compressed file may expand to a very large decoded representation. For a hypothetical 10,000 by 10,000 RGBA image, a single uncompressed pixel buffer requires 400,000,000 bytes, roughly 381 MiB, before parser overhead or copies. A 5 MB compressed file limit does not prevent that allocation. Use parser-level pixel limits and reject oversized dimensions before decoding large buffers whenever possible.
Run complex parsers with appropriate process isolation, restricted filesystem and network access, timeouts and resource quotas. Use maintained libraries, pinned dependency versions and an update process. Disable active content and unexpected embedded operations; do not execute macros or scripts found inside a document.
The example in section 7 uses Python's wave module to inspect a narrow PCM format. It does not generalize to arbitrary image, document, audio or video formats and is not a comprehensive sandbox or malware scanner.
6. Capability-aware routing and context budgets#
The model capability contract must describe more than a boolean called multimodal. Maintain an approved profile for the exact model deployment and adapter version.
| Profile field | Example requirement |
|---|---|
| Accepted input modalities | Text and image, or text and audio |
| Accepted source forms | Inline data, authorized HTTPS URL or provider file reference |
| Supported MIME/codec | A reviewed subset of image or audio formats |
| Request constraints | Per-asset and aggregate size limits |
| Media resource constraints | Duration, pixels, page count or other measured bounds |
| Tool coexistence | Media input works with the agent's required tools |
| Structured output coexistence | The intended response contract works with media input |
| Privacy approval | Approved region, retention, service and data classification |
| Performance envelope | Tested quality, latency and cost for representative tasks |
A model may support images in a direct chat call but reject the same request with certain tool or structured-output settings. Test the complete deployed agent configuration. Use only verified approved profiles; do not route confidential media to another provider merely because its capability metadata suggests compatibility.
Media token accounting is provider-specific. Images may be charged according to dimensions or internal visual processing; audio may use duration, samples or audio tokens; documents may include text and rendered pages; video may use frame and audio representations. Base64 character count is not a reliable model-token estimate.
A production admission decision should reserve context for instructions, required conversation context, tools and the expected response, then estimate the remaining media budget according to the selected adapter and model. Confirm actual usage from supported provider telemetry. If the task cannot fit, reduce input only when that reduction preserves necessary evidence, or request a narrower task. Do not arbitrarily crop a relevant diagram or truncate an audio segment and present the answer as complete.
7. Tested Python: narrow WAV admission and safe routing#
The following standalone program accepts strict Base64-encoded WAV data, checks a fixed illustrative PCM profile, limits encoded and decoded sizes, verifies declared duration and sample availability, and attaches a SHA-256 digest. The routing policy chooses native audio or a transcript-only path based on trusted approval flags and whether the task needs acoustic evidence.
The code and all tests were actually executed locally. The limits (4,096 bytes, one second, mono 16-bit 8 kHz PCM) are intentionally small for a synthetic teaching fixture. They are not advertised provider limits.
PYTHONimport base64, binascii, hashlib, io, wave, struct, sys, importlib.util from dataclasses import dataclass @dataclass(frozen=True) class Audio: mime: str data: bytes sha256: str frames: int rate: int def validate_wav(encoded, mime, *, max_bytes=4096, max_seconds=1): if mime != 'audio/wav': raise ValueError('unsupported MIME') if not isinstance(encoded, str) or len(encoded) > 4*((max_bytes+2)//3): raise ValueError('encoded size or type') try: raw = base64.b64decode(encoded, validate=True) except (ValueError, binascii.Error) as exc: raise ValueError('invalid base64') from exc if not raw or len(raw) > max_bytes: raise ValueError('decoded size') try: with wave.open(io.BytesIO(raw), 'rb') as w: rate, frames = w.getframerate(), w.getnframes() if w.getnchannels() != 1 or w.getsampwidth() != 2 or rate != 8000: raise ValueError('unsupported PCM profile') if not 0 < frames <= rate*max_seconds: raise ValueError('duration limit') if len(w.readframes(frames)) != frames*2: raise ValueError('truncated samples') except (wave.Error, EOFError, struct.error) as exc: raise ValueError('invalid WAV') from exc return Audio(mime, raw, hashlib.sha256(raw).hexdigest(), frames, rate) def route(asset, *, authorized, native_approved, transcription_approved, needs_sound): if not authorized: return 'deny' if native_approved: return 'native_audio' if transcription_approved and not needs_sound: return 'transcript_only' return 'unsupported' def fixture(frames=80, channels=1): buf=io.BytesIO() with wave.open(buf,'wb') as w: w.setnchannels(channels); w.setsampwidth(2); w.setframerate(8000) w.writeframes(b'\0\0'*frames*channels) return buf.getvalue() def enc(raw): return base64.b64encode(raw).decode('ascii') def reject(fn): try: fn() except ValueError: return raise AssertionError('expected rejection') raw=fixture(); encoded=enc(raw); a=validate_wav(encoded,'audio/wav') assert a.data==raw and a.sha256==hashlib.sha256(raw).hexdigest() assert a.frames==80 and a.rate==8000 reject(lambda:validate_wav(encoded,'image/png')) reject(lambda:validate_wav('!!!!','audio/wav')) reject(lambda:validate_wav(encoded,'audio/wav',max_bytes=32)) reject(lambda:validate_wav(enc(b'not WAV'),'audio/wav')) reject(lambda:validate_wav(enc(fixture(channels=2)),'audio/wav')) reject(lambda:validate_wav(enc(fixture(0)),'audio/wav')) reject(lambda:validate_wav(encoded,'audio/wav',max_seconds=0.005)) reject(lambda:validate_wav(enc(raw[:-2]),'audio/wav')) assert route(a,authorized=False,native_approved=True,transcription_approved=True,needs_sound=False)=='deny' assert route(a,authorized=True,native_approved=True,transcription_approved=False,needs_sound=True)=='native_audio' assert route(a,authorized=True,native_approved=False,transcription_approved=True,needs_sound=False)=='transcript_only' assert route(a,authorized=True,native_approved=False,transcription_approved=True,needs_sound=True)=='unsupported' assert route(a,authorized=True,native_approved=False,transcription_approved=False,needs_sound=False)=='unsupported' print('15 checks passed') print(sys.version.split()[0], {p: importlib.util.find_spec(p) is not None for p in ['langchain','langchain_core','langgraph']})
Actual local output:
15 checks passed
3.13.5 {'langchain': False, 'langchain_core': False, 'langgraph': False}| Check | Result |
|---|---|
| Valid generated audio | Original bytes and computed digest preserved |
| PCM metadata | 80 frames at 8 kHz |
| Wrong declared MIME | Rejected |
| Invalid Base64 | Rejected |
| Encoded size limit | Rejected |
| Non-WAV bytes | Rejected |
| Stereo fixture | Rejected by narrow mono policy |
| Empty audio | Rejected |
| Duration over configured limit | Rejected |
| Truncated sample data | Rejected |
| Unauthorized asset | Denied even with compatible routes |
| Approved native path | Selected |
| Transcript adequate for task | Transcript-only path selected |
| Acoustic evidence required | Transcript fallback rejected |
| No approved compatible route | Unsupported |
The fixture is silence, not a real speech recording. No transcription or audio-model inference occurred. The route function accepts an asset parameter as a reminder of the application boundary but does not inspect it: it assumes prior validation and profile compatibility checks are complete. The approval flags and task evidence requirement must come from trusted policy and task analysis, not unchecked user or model claims.
The example does not authenticate the caller, scan for malware, validate every RIFF chunk or trailing byte, guarantee canonical Base64 encoding, perform general codec detection, or defend against every malicious file. It assumes valid configuration limits supplied by the host. A real ingress must bound bytes before reading them into memory and a worker should enforce resource limits independently. The sample-count check detects the particular truncated fixture; it is not proof of complete container integrity. SHA-256 identifies exact bytes but does not establish ownership or authenticity.
8. Secure asset handling, privacy and URL access#
In a production application, authorize access to a stable asset reference before resolving it to bytes or an external URL. An asset record can include tenant, owner or authorized sharing scope, verified digest, detected MIME, size, media metadata, source revision, privacy classification, retention deadline and processing status. Keep credentials and signed URL generation at the trusted service boundary.
Remote URL fetching presents server-side request forgery and data-disclosure risks. Prefer resolving application-owned objects rather than downloading arbitrary URLs. If remote ingestion is necessary, implement a separately reviewed fetch service with approved origins, HTTPS policy, restricted egress, validation of DNS and actual connection destinations, blocking of private/internal addresses, per-redirect revalidation, time and byte limits. A simple string prefix test or an initial DNS lookup is not sufficient; redirects and DNS changes can undermine it. Verify how the provider fetches URLs as well, because provider-side retrieval can expose the URL or asset to another processing system.
Store original media and derived representations only for a defined purpose. A signed URL is a bearer-like access capability; avoid logging it or storing it in a long-lived conversation when a stable internal reference would suffice. Restrict access, expiry and retention. Do not send media to an unapproved transcription or OCR provider. Base64 strings also contain the original sensitive bytes and must not be dumped into logs or traces.
Consider metadata minimization: photos may include location or device details; audio can contain voices and background conversations; videos may reveal bystanders; documents may contain hidden layers, comments or embedded attachments. Only remove or redact metadata using a reviewed transformation that preserves the evidence required by the task. Record derivative provenance so a response can be traced to the correct asset revision.
A file may contain text instructing the model to perform unrelated actions. Treat visible text, transcripts, OCR output and document content as untrusted evidence rather than privileged application instructions. Apply independent tool permissions and verify claims regardless of input modality.
9. Fallback must preserve the requested evidence#
A fallback is a different evidence path, not merely a different API.
For a task asking what words were spoken, an approved transcript may be sufficient if its accuracy and uncertainty are appropriate. For a task comparing sounds, a transcript cannot supply the required acoustic features. For an image asking about spatial layout, OCR text alone may be inadequate. For video, disclose which frames or time ranges were inspected rather than claiming whole-video analysis.
Preserve derived evidence provenance, including the extractor version, timestamps or page coordinates where available, and the original asset digest. If conversion loses information required to answer the question, return an explicit unsupported or incomplete outcome. Do not fabricate observations from a filename or a model's assumptions.
If a media upload expires during a run, reauthorize the asset and create a fresh approved reference where appropriate. If a different asset revision is available, require a reviewed decision instead of silently substituting it. Avoid unbounded upload retries and repeated external processing; use stable processing identities and reconcile ambiguous uploads through the provider's supported mechanisms.
10. Production testing and monitoring#
Test the exact installed LangChain and provider integration separately from the media validation and policy logic. Use synthetic non-sensitive fixtures with known text, layout, speech or temporal events. A successful HTTP request or valid message object does not prove the model received usable media.
| Test | Acceptance criterion |
|---|---|
| Text plus image | Actual request contains the correct supported image representation and preserves order |
| Inline Base64 | Decoded provider-bound bytes match approved asset or reviewed derivative |
| URL source | Only intended asset accessible; expiry and failure handled safely |
| Audio input | Supported codec, duration and media interpretation verified |
| Video input | Temporal coverage and any sampling limitations established |
| Document input | Correct pages, layouts and source references available |
| MIME mismatch and corrupt media | Rejected before provider submission |
| Decoded resource limit | Oversized image, long audio or document expansion rejected |
| Multiple assets | Aggregate input and context budgets enforced |
| Unauthorized or deleted asset | No retrieval or external transfer |
| Native modality unsupported | Only approved sufficient alternative selected |
| Tools and structured response together | Complete media-enabled agent task works with required capabilities |
| Embedded instruction-like content | No unauthorized operation or unsupported claim accepted |
| Retention and logging | Media bytes, signed URLs and private content not exposed unnecessarily |
Measure upload and validation latency, decoded resource sizes, rejection categories, conversion quality, provider failures, observed usage, cost per accepted task and unnecessary unsupported outcomes. Slice results by modality, format, media quality and task type. Evaluate false claims separately: a syntactically valid answer describing a nonexistent label is not an accepted task result.
Record safe asset aliases, digest or revision where appropriate, profile ID, transformation revision, media sizes, coverage and normalized failure codes. Avoid raw content logging. Re-run compatibility tests after changing adapter versions, model deployments, media parsers, source representation or privacy policy.
Interview-ready answer#
I represent multimodal inputs as ordered typed content blocks in a LangChain message and use a compatible model adapter. I choose URL, inline Base64 or provider file references based on verified capabilities and data-handling requirements. Before constructing the message, I resolve authorized asset references, inspect actual formats, enforce raw and decoded resource limits, and verify the complete model configuration including tools and structured output. I budget media using provider-specific accounting, preserve provenance and use OCR, transcription or frame extraction only when that alternative retains the required evidence. I explicitly disclose lost modality coverage, protect assets and signed URLs, and test actual provider-bound requests and evidence-supported outcomes rather than assuming a valid content block guarantees successful media understanding.
Official documentation research leads and verification status#
- LangChain messages
- LangChain models
- LangChain agents
- LangChain API reference
- Python Base64 documentation
- Python wave documentation
- Python hashlib documentation
- OWASP File Upload Cheat Sheet
- OWASP Server Side Request Forgery Prevention Cheat Sheet
Authorized offline research exception applied. These official documentation URLs are research leads, not live-accessed citations. The exact standalone Python program ran locally on Python 3.13.5 and printed 15 checks passed. Local inspection confirmed that langchain, langchain_core and langgraph were absent. The three SDK examples are illustrative and unexecuted; actual provider block conversion, image/audio/video/document capabilities, secure remote fetching, media parser isolation, transcription quality, live token accounting and public rendering were not verified. All assets used in tests were synthetic WAV fixtures; no network transfer or real user media was involved. Mermaid diagrams use standard triple-backtick fences; rendering was not tested.
References
- 1.LangChain messagesdocs.langchain.com
- 2.LangChain modelsdocs.langchain.com
- 3.LangChain agentsdocs.langchain.com
- 4.LangChain API referencereference.langchain.com
- 5.Python Base64 documentationdocs.python.org
- 6.Python wave documentationdocs.python.org
- 7.Python hashlib documentationdocs.python.org
- 8.OWASP File Upload Cheat Sheetcheatsheetseries.owasp.org
- 9.OWASP SSRF Prevention Cheat Sheetcheatsheetseries.owasp.org
Related questions
Explore other topics:Forward Deployed EngineeringLarge Language ModelsRetrieval-Augmented GenerationMLOps