title: "LangChain Integration" description: "Use MuAPI inside LangChain and LangGraph agents — generative media tools, a document loader, a cost-tracking callback, and a turnkey Deep Agents recipe."
LangChain Integration
The official muapi-langchain package wraps MuAPI's 390+ generative-media models, 40+ named skills, and creative agent into idiomatic LangChain primitives. Drop them into a ReAct agent, a LangGraph node, or a Deep Agent — your LLM gains the ability to create images, videos, audio, edits, and full multi-asset campaigns.
| Package | Purpose |
|---|---|
| muapi-langchain | LangChain tools + document loader + cost callback + Deep Agents example |
Installation
The package currently ships from source in the muapi-cli repository
(PyPI release is coming):
pip install "git+https://github.com/SamurAIGPT/muapi-cli.git#subdirectory=integrations/langchain"
# Optional: for the Deep Agents recipe below
pip install "deepagents langgraph langchain-openai"
Set your API key (or use muapi auth configure):
export MUAPI_API_KEY="..."
What's included
The integration exposes four tools that form a capability gradient — cheap discovery on one end, open-ended creative planning on the other:
| Tool | What it does | Cost |
|---|---|---|
muapi_select | Rank models and named skills for a brief | Free |
muapi_generate | Single-shot generation (image / video / audio / edit / enhance) | Per call |
muapi_run_skill | Run a named multi-step recipe (UGC ad, storyboard, product video, …) | Per recipe |
muapi_creative_agent | Hand a multi-asset brief to MuAPI's planning agent | Variable |
Plus two non-tool primitives:
MuapiAssetLoader— load prior generations as LangChainDocuments for RAGMuapiCostCallback— track credit spend across a run, enforce a hard budget cap
Quick Start
from muapi_langchain import muapi_select, muapi_generate
import json
# Discover candidates (free — no credits spent)
result = muapi_select.invoke({
"intent": "cinematic product photo of a sneaker",
"kind": "image",
"tier": "best",
"limit": 3,
})
print(json.loads(result)["models"])
# Generate
out = muapi_generate.invoke({
"prompt": "A glossy sneaker on a wet street, neon-lit night",
"kind": "image",
"tier": "best",
})
print(json.loads(out)["url"])
The tools are plain @tool-decorated functions, so they work in any LangChain agent framework — create_react_agent, LangGraph custom graphs, Deep Agents, or direct tool-calling via the OpenAI / Anthropic SDKs.
Tool Reference
muapi_select(intent, kind?, tier?, limit=5)
Rank candidate models and skills for an intent. Free — runs locally using a keyword-overlap ranker against the bundled 390-model registry.
intent: Plain-English description of what the user wants.kind: Optional — one of"image","image_edit","video","i2v","video_edit","lipsync","audio","enhance","3d".tier: Optional —"best","balanced","fast", or"budget".
Use this first when you don't know which model fits, or to surface a named skill that matches the brief.
muapi_generate(prompt, kind="image", model="auto", input_asset_url?, tier="balanced", extra?)
Generate one asset. With model="auto", MuAPI picks a sensible default for the kind + tier. For edits / image-to-video / lipsync / enhance, pass input_asset_url.
muapi_generate.invoke({
"prompt": "make the cat wear a top hat",
"kind": "image_edit",
"input_asset_url": "https://...source.png",
})
muapi_run_skill(skill_name, inputs)
Run one of 40+ pre-baked multi-step recipes (ugc-ads-workflow, storyboard, product-ad-cinematic, 3d-logo-animation, etc.). Discover skill names and their input schemas via muapi_select.
muapi_creative_agent(brief, budget_credits=300)
Hand a free-form multi-asset brief to MuAPI's planning agent. The agent decomposes the brief into a DAG, executes it, and returns the assets. Can spend significant credits — gate this with interrupt_on in production.
Document Loader
MuapiAssetLoader hydrates previous generations as LangChain Documents, with page_content set to the original prompt and metadata carrying the asset URL, model, kind, and credit cost. Useful for RAG ("do another in that style") and for evaluations over a user's generation history.
from muapi_langchain import MuapiAssetLoader
docs = MuapiAssetLoader(request_ids=["req_abc", "req_def"]).load()
for d in docs:
print(d.metadata["url"], "·", d.page_content[:80])
Cost Tracking
MuapiCostCallback plugs into any LangChain / LangGraph run. It inspects each MuAPI tool result, accumulates credits, fires a custom event per call, and (optionally) raises BudgetExceeded once a cap is hit — aborting the agent cleanly before runaway spend.
from muapi_langchain import MuapiCostCallback
cost_cb = MuapiCostCallback(
budget_credits=500,
on_event=lambda evt, payload: print(evt, payload),
)
agent.invoke(
{"messages": [{"role": "user", "content": "make me a 3-shot carousel ..."}]},
config={"callbacks": [cost_cb]},
)
print(cost_cb.summary())
# {'total_credits': 78, 'calls': 4, 'by_tool': {'muapi_generate': 78}, ...}
Deep Agents Recipe
The recommended production pattern splits the tools across a planner (cheap discovery + single-shot generation) and a creative-specialist subagent (multi-step skills + the creative agent). Open-ended creative work is gated for human approval via interrupt_on.
import os, uuid
from deepagents import create_deep_agent
from langchain_openai import ChatOpenAI
from langgraph.checkpoint.memory import MemorySaver
from langgraph.types import Command
from muapi_langchain import (
MuapiCostCallback, PLANNER_TOOLS, SPECIALIST_TOOLS,
)
CREATIVE_SPECIALIST = {
"name": "creative-specialist",
"description": (
"Handles multi-step MuAPI workflows: named skills (UGC ads, "
"storyboards, product videos) and open-ended creative briefs."
),
"system_prompt": (
"You are a MuAPI creative specialist. "
"Prefer muapi_run_skill when the brief matches a named recipe. "
"Escalate to muapi_creative_agent only for open-ended multi-asset briefs."
),
"tools": SPECIALIST_TOOLS,
}
agent = create_deep_agent(
model=ChatOpenAI(model="gpt-4o", api_key=os.environ["OPENAI_API_KEY"]),
tools=PLANNER_TOOLS,
subagents=[CREATIVE_SPECIALIST],
system_prompt=(
"Start with muapi_select to discover models and skills. "
"Call muapi_generate yourself for single-asset asks. "
"Delegate multi-step work to the creative-specialist."
),
interrupt_on={
"muapi_creative_agent": {"allowed_decisions": ["approve", "edit", "reject"]},
},
checkpointer=MemorySaver(),
)
cost_cb = MuapiCostCallback(budget_credits=500)
config = {"configurable": {"thread_id": str(uuid.uuid4())}, "callbacks": [cost_cb]}
result = agent.invoke(
{"messages": [{"role": "user", "content":
"Make a 3-shot Instagram carousel for SunFizz mango sparkling water."
}]},
config=config,
version="v2",
)
# Resume after each interrupt
while getattr(result, "interrupts", None):
action = result.interrupts[0].value["action_requests"][0]
print(f"Pending: {action['name']}")
print(f"Args: {action['args']}")
decision = input("approve / edit / reject: ").strip().lower()
result = agent.invoke(
Command(resume={"decisions": [{"type": decision}]}),
config=config,
version="v2",
)
print(cost_cb.summary())
A complete runnable version lives at integrations/langchain/examples/deep_agents_demo.py.
Decision Tree
User brief
├─ Don't know which model/skill? → muapi_select (free, planner)
├─ Single asset, clear prompt? → muapi_generate (planner)
├─ Matches a known recipe? → muapi_run_skill (specialist)
└─ Multi-asset / multi-modal? → muapi_creative_agent (specialist, gated)
Environment Variables
| Variable | Required | Notes |
|---|---|---|
MUAPI_API_KEY | Yes | Your MuAPI key, or set via muapi auth configure |
OPENAI_API_KEY | For Deep Agents | Powers the planner LLM in the example |
MUAPI_BASE_URL | No | Defaults to https://api.muapi.ai/api/v1 |
For development, you can mint a sandbox key (is_test=true) that returns mock URLs instantly and never charges credits — see the CLI docs for how to create one.
Related
- MuAPI CLI — same auth, same client; the integration depends on
muapi-cli - MCP Server — alternative for Claude / Cursor / Windsurf via Model Context Protocol
- n8n — drag-and-drop visual workflows
- Agents — overview of MuAPI's agentic surfaces