惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

雷峰网
雷峰网
宝玉的分享
宝玉的分享
I
InfoQ
P
Privacy International News Feed
V
V2EX
IT之家
IT之家
S
SegmentFault 最新的问题
D
Darknet – Hacking Tools, Hacker News & Cyber Security
V2EX - 技术
V2EX - 技术
C
CERT Recently Published Vulnerability Notes
C
Check Point Blog
The Register - Security
The Register - Security
爱范儿
爱范儿
博客园 - 三生石上(FineUI控件)
AWS News Blog
AWS News Blog
M
MIT News - Artificial intelligence
C
Cyber Attacks, Cyber Crime and Cyber Security
F
Fortinet All Blogs
B
Blog
N
Netflix TechBlog - Medium
B
Blog RSS Feed
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Last Week in AI
Last Week in AI
T
Threatpost
Forbes - Security
Forbes - Security
U
Unit 42
A
Arctic Wolf
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
P
Palo Alto Networks Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Recorded Future
Recorded Future
L
Lohrmann on Cybersecurity
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
P
Proofpoint News Feed
月光博客
月光博客
Spread Privacy
Spread Privacy
MongoDB | Blog
MongoDB | Blog
Jina AI
Jina AI
I
Intezer
V
Visual Studio Blog
阮一峰的网络日志
阮一峰的网络日志
The Hacker News
The Hacker News
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
L
LangChain Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
博客园_首页
MyScale Blog
MyScale Blog
腾讯CDC
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
量子位

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Building a Multimodal AI Pipeline: Text Image Text Across Three Providers
YAIT · 2026-06-26 · via DEV Community

Three providers, three modalities, under 55 lines of Python — and a PNG file on disk at the end. Claude writes a sunset description, an image generation model paints it, and Qwen Vision analyzes the result. Each model does one thing well; the script wires them together.

This article walks through building exactly that pipeline using yait_aichain's Skill and Model primitives. We'll go step by step: generate text with Claude, turn that text into an image, then feed the image to Qwen Vision for analysis.

What We're Building

The pipeline has three stages:

  1. Text → Text (Claude claude-3-5-sonnet-20241022): Generate a one-sentence description of a sunset.
  2. Text → Image (imagine-image-pro): Turn that description into a 1024×1024 image.
  3. Image → Text (Qwen qwen-vl-max): Feed the generated image to a vision model and ask what it sees.

Each stage uses a different provider — Anthropic, xAI, and DashScope. The output of one stage becomes the input of the next.

Prerequisites

You need three API keys, each set as an environment variable:

export ANTHROPIC_API_KEY="your-anthropic-key"
export XAI_API_KEY="your-xai-key"
export DASHSCOPE_API_KEY="your-dashscope-key"

Install the library:

pip install yait_aichain

No extra dependencies for image handling — Python's base64 and pathlib modules cover the file I/O. yait_aichain handles provider routing internally, so you won't need to install Anthropic, xAI, or DashScope SDKs separately.

The Two Primitives You Need to Know

Model represents a connection to a specific model at a specific provider. You pass the model name and an API key — no provider-specific client classes, no adapter patterns to memorize.

Skill is a single unit of work. It takes a Model, an input (structured as messages), and optionally an output configuration. Call .run() and it executes. The message format uses a parts list inside each message, which is how yait_aichain handles multimodal content uniformly — text, images, and mixed content all go through the same structure.

Stage 1: Generating Text with Claude

import os, sys, base64, pathlib
from yait_aichain import Model, Skill

text_skill = Skill(
    model = Model("claude-3-5-sonnet-20241022", api_key=os.environ["ANTHROPIC_API_KEY"]),
    input = {"messages": [{"role": "user", "parts": ["Describe a sunset in one sentence."]}]},
)

description = text_skill.run()
print(f"[text → text · Claude]\n{description}\n")

The input dictionary contains a messages list — identical in shape to what you'd see in a chat API. Each message has a role and a parts list. For plain text, parts is just a list of strings.

Notice the use of os.environ["KEY"] rather than os.getenv("KEY"). This is a deliberate choice I prefer for multi-provider scripts: os.getenv silently returns None when a key is missing, which pushes the error down to the provider's API where the message is far less useful. os.environ raises a KeyError immediately with the variable name. When you're juggling three different API keys for the first time, you want to know which one is missing.

text_skill.run() returns the model's response as a string. On a typical call, you'll get something like:

"The sun melted into the horizon, painting the sky in layered bands of amber, rose, and deep violet as the ocean mirrored its fading warmth."

That string becomes the input for Stage 2.

Why parts Instead of content?

The parts list is the design decision that makes multimodal work without special-casing. A text-only message uses ["some string"]. A message with an image uses a dictionary inside parts. A message with both uses both. Same field, same structure, every modality.

Stage 2: Turning Text Into an Image

We take Claude's text output and pass it to the image generation model as a prompt:

image_skill = Skill(
    model  = Model("imagine-image-pro", api_key=os.environ["XAI_API_KEY"]),
    input  = {"messages": [{"role": "user", "parts": [description]}]},
    output = {"modalities": ["image"], "format": {"type": "image", "size": "1024x1024"}},
)

image    = image_skill.run()
img_path = pathlib.Path("output_sunset.png")
img_path.write_bytes(base64.b64decode(image["base64"]))
print(f"[text → image]\nsaved → {img_path}\n")

Two things to notice here.

The output configuration. This is the first time we specify how the response should come back. "modalities": ["image"] tells the Skill we expect an image. The "format" dictionary specifies the type and dimensions. Without this, the model might return text describing how it would generate an image — which is not helpful.

The return value. When a Skill produces an image, .run() returns a dictionary with at least two keys: "base64" (the image data) and "mime_type" (e.g., "image/png"). We decode the base64 data and write it to disk.

pathlib.Path("output_sunset.png") writes to the current working directory rather than using __file__. That's deliberate — __file__ is undefined in interactive environments like Jupyter notebooks or a REPL and raises a NameError. A relative path works consistently across all contexts.

A Note on Image Sizes

"1024x1024" is a common default for image generation models. If you pass a size the model doesn't support, you'll get an error at runtime rather than a silently resized image. Check your provider's documentation for supported dimensions before you assume.

Stage 3: Analyzing the Image with Qwen Vision

The image from Stage 2 goes into Qwen's vision-language model:

vision_skill = Skill(
    model = Model("qwen-vl-max", api_key=os.environ["DASHSCOPE_API_KEY"]),
    input = {
        "messages": [{
            "role": "user",
            "parts": [
                {"type": "image", "source": {"kind": "base64",
                                              "data": image["base64"],
                                              "mime": image["mime_type"]}},
                {"type": "text",  "text": "What do you see in this image?"},
            ],
        }]
    },
)

analysis = vision_skill.run()
print(f"[image → text · Qwen]\n{analysis}")

The parts list now contains two items:

  1. An image part — a dictionary with "type": "image" and a "source" object. The source specifies "kind": "base64", the actual base64 data, and the MIME type — both pulled directly from Stage 2's output dictionary.

  2. A text part — a dictionary with "type": "text" and the question.

Same parts structure as Stage 1. The only difference is that instead of bare strings, we use typed dictionaries to describe each piece of content. The vision model receives the image and the question in a single message and Qwen's response comes back as a plain string — something like:

"The image shows a vivid sunset over an ocean. The sky displays gradients of orange, pink, and purple. The sun is partially below the horizon, with its reflection stretching across calm water."

The Complete Script

"""
Multimodal pipeline: Text → Image → Text, three different providers.

  1. text  → text   Claude  (claude-3-5-sonnet-20241022)
  2. text  → image           (imagine-image-pro)
  3. image → text   Qwen    (qwen-vl-max)

Required env vars:
    ANTHROPIC_API_KEY
    XAI_API_KEY
    DASHSCOPE_API_KEY
"""

import os, sys, base64, pathlib
from yait_aichain import Model, Skill

# ── 1. Text → Text (Claude) ──────────────────────────────────────────────────
text_skill = Skill(
    model = Model("claude-3-5-sonnet-20241022", api_key=os.environ["ANTHROPIC_API_KEY"]),
    input = {"messages": [{"role": "user", "parts": ["Describe a sunset in one sentence."]}]},
)

try:
    description = text_skill.run()
except Exception as e:
    print(f"Stage 1 failed: {e}"); sys.exit(1)
print(f"[text → text · Claude]\n{description}\n")

# ── 2. Text → Image ──────────────────────────────────────────────────────────
image_skill = Skill(
    model  = Model("imagine-image-pro", api_key=os.environ["XAI_API_KEY"]),
    input  = {"messages": [{"role": "user", "parts": [description]}]},
    output = {"modalities": ["image"], "format": {"type": "image", "size": "1024x1024"}},
)

try:
    image = image_skill.run()
except Exception as e:
    print(f"Stage 2 failed: {e}"); sys.exit(1)
img_path = pathlib.Path("output_sunset.png")
img_path.write_bytes(base64.b64decode(image["base64"]))
print(f"[text → image]\nsaved → {img_path}\n")

# ── 3. Image → Text (Qwen Vision) ────────────────────────────────────────────
vision_skill = Skill(
    model = Model("qwen-vl-max", api_key=os.environ["DASHSCOPE_API_KEY"]),
    input = {
        "messages": [{
            "role": "user",
            "parts": [
                {"type": "image", "source": {"kind": "base64",
                                              "data": image["base64"],
                                              "mime": image["mime_type"]}},
                {"type": "text",  "text": "What do you see in this image?"},
            ],
        }]
    },
)

try:
    analysis = vision_skill.run()
except Exception as e:
    print(f"Stage 3 failed: {e}"); sys.exit(1)
print(f"[image → text · Qwen]\n{analysis}")

Three providers. Two modality transitions. Each stage wrapped in its own try/except so a failure at Stage 2 tells you it was Stage 2 — not a cryptic traceback from somewhere inside a provider SDK you didn't even know you were calling.

How the Stages Connect

There's no special "chaining" API. The variable description (a string) goes directly into image_skill's input. The variable image (a dictionary) gets its fields plucked out for vision_skill's input. Regular Python variables carry data between stages.

When you need to transform data between stages — truncating a description to 200 characters before image generation, for instance — you write normal Python between the calls. No callbacks, no middleware, no pipeline DSL. This is actually one of the things I like about this approach: the "pipeline" is just a script.

The parts list is what keeps the interface uniform across modalities:

  • Text-only: "parts": ["your string here"]
  • Image-only: "parts": [{"type": "image", "source": {...}}]
  • Mixed: "parts": [image_dict, text_dict]

One structure, every model, every modality.

Swapping Providers

Notice what's absent from the Skill configurations: no Anthropic client initialization, no provider-specific headers, no DashScope SDK imports. The Model constructor takes a model name and an API key; provider routing happens internally. Swapping the image generation model means changing one string and one environment variable — nothing else in the script changes.

Extending the Pipeline

Once you have this pattern, extensions are straightforward.

  • Add a fourth stage. Take Qwen's analysis and feed it to a text model for summarization or translation. Another Skill, another Model, same shape.
  • Branch instead of chain. Generate 3 different images from the same description using 3 different models. Compare the results by feeding all of them to the vision model in separate Skill calls.
  • Save intermediate results. The script already saves the image to disk. Add JSON logging for the text outputs and you have a full audit trail of the pipeline's execution.

The models do the hard work. The code connects them — and stays out of the way.