跨模态推理模式
将文本主张与图像建立依据联系,并综合多来源多模态上下文
跨模态推理模式 是 CoddyKit 上的免费 AI Agents 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Agents 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Agents 课程共包含 4 节课。
跨模态推理
当代理必须协调来自两种或更多模态的信息时,就会发生跨模态推理,这些模态包括文本、图像、图表和表格,它们可能彼此一致、相互矛盾或互为补充。例如:报告文本称收入增长了 20%,但随附图表显示收入保持平稳。
代理必须判断哪个来源是正确的,或将差异标记出来,交由人工审核。
文本-图像对齐验证
文本-图像对齐验证是指核实文本中的主张能否在配套图像中得到视觉确认。例如:产品描述是否与产品照片相符?文档中提到的表格是否确实出现在图像中?
import anthropic
import base64
def ground_text_in_image(
text_claim: str,
image_path: str
) -> dict:
client = anthropic.Anthropic(api_key='YOUR_API_KEY')
with open(image_path, 'rb') as f:
b64 = base64.standard_b64encode(f.read()).decode('utf-8')
prompt = (
f'Text claim: "{text_claim}"\n\n'
'Does the image above support, contradict, or partially support this claim?\n'
'Return JSON: {"verdict": "support|contradict|partial|insufficient_evidence", '
'"confidence": 0.0, "evidence": "..."}'
)
response = client.messages.create(
model='claude-opus-4-5', max_tokens=256,
messages=[{'role': 'user', 'content': [
{'type': 'image', 'source': {'type': 'base64',
'media_type': 'image/jpeg', 'data': b64}},
{'type': 'text', 'text': prompt}
]}]
)
import json
return json.loads(response.content[0].text)图表与文本矛盾检测
现实中常见的一种情况是:财务报告的正文表达一种内容,但文档中嵌入的图表却讲述了另一种情况。代理可以从视觉上提取图表数据,并将其与文本中的数值主张进行比较。
def compare_chart_to_text(
chart_image_path: str,
text_with_claims: str
) -> dict:
import anthropic, base64, json
client = anthropic.Anthropic(api_key='YOUR_API_KEY')
with open(chart_image_path, 'rb') as f:
b64 = base64.standard_b64encode(f.read()).decode('utf-8')
prompt = (
'The following text makes claims about data.\n'
f'TEXT: {text_with_claims}\n\n'
'Compare the chart image to the text claims. '
'List any contradictions and agreements. '
'Return JSON: {"agreements": [str], "contradictions": [str], '
'"verdict": "consistent|inconsistent|partial"}'
)
response = client.messages.create(
model='claude-opus-4-5', max_tokens=512,
messages=[{'role': 'user', 'content': [
{'type': 'image', 'source': {'type': 'base64',
'media_type': 'image/jpeg', 'data': b64}},
{'type': 'text', 'text': prompt}
]}]
)
return json.loads(response.content[0].text)信号组合策略
当来自多个模态的信号一致时,请提高置信度。当信号不一致时,请采用冲突解决策略:信任结构化程度更高的来源(对于数字,图表比正文更可靠)、标记出来交由人工审核,或要求 LLM 推理哪个来源更可靠。
SIGNAL_SOURCES = {
'chart': 0.9, # high trust for quantitative data
'table': 0.85,
'photo': 0.8,
'prose': 0.6, # lower trust — may be imprecise or outdated
'caption': 0.7
}
def combine_signals(signals: list) -> dict:
"""
signals: list of {'source': str, 'claim': str, 'supports': bool}
Returns weighted verdict.
"""
support_weight = 0.0
total_weight = 0.0
for sig in signals:
w = SIGNAL_SOURCES.get(sig['source'], 0.5)
total_weight += w
if sig['supports']:
support_weight += w
confidence = support_weight / total_weight if total_weight > 0 else 0.0
return {
'confidence': round(confidence, 3),
'verdict': 'supported' if confidence >= 0.6 else 'contested',
'needs_review': 0.4 <= confidence < 0.6
}
if __name__ == '__main__':
signals = [
{'source': 'chart', 'claim': 'Revenue grew 20%', 'supports': True},
{'source': 'prose', 'claim': 'Revenue grew 20%', 'supports': False},
]
print(combine_signals(signals))
文本到图像验证流程
产品验证流程如下:给定产品描述及其照片,检查文本中提到的每个关键属性是否都能在图像中看到。返回一份结构化报告,列出匹配项和不匹配项。
def verify_product_description(
description: str,
product_image_path: str
) -> dict:
import anthropic, base64, json
client = anthropic.Anthropic(api_key='YOUR_API_KEY')
with open(product_image_path, 'rb') as f:
b64 = base64.standard_b64encode(f.read()).decode('utf-8')
prompt = (
f'Product description:\n{description}\n\n'
'For each attribute mentioned in the description (color, shape, material, '
'size, features), check whether it is visible in the product photo.\n'
'Return JSON: {"verified": [{"attribute": str, "status": str}], '
'"unverified": [str], "overall_match": float}\n'
'status: confirmed / contradicted / not_visible\n'
'overall_match: 0.0-1.0'
)
response = client.messages.create(
model='claude-opus-4-5', max_tokens=512,
messages=[{'role': 'user', 'content': [
{'type': 'image', 'source': {'type': 'base64',
'media_type': 'image/jpeg', 'data': b64}},
{'type': 'text', 'text': prompt}
]}]
)
return json.loads(response.content[0].text)文档与图像交叉核对
分析扫描文档时,OCR 文本和底层图像同时存在。请将两者进行交叉核对:提取的文本是否与视觉上呈现的内容一致?不匹配可能表示存在需要更正的 OCR 错误。
def crossref_ocr_with_image(
ocr_text: str,
document_image_path: str
) -> dict:
import anthropic, base64, json
client = anthropic.Anthropic(api_key='YOUR_API_KEY')
with open(document_image_path, 'rb') as f:
b64 = base64.standard_b64encode(f.read()).decode('utf-8')
prompt = (
f'The OCR system produced this text from the document image:\n\n'
f'{ocr_text}\n\n'
'Compare the OCR text to what you actually see in the image. '
'Identify any OCR errors, missed text, or hallucinated characters.\n'
'Return JSON: {"ocr_errors": [{"incorrect": str, "correct": str}], '
'"missed_sections": [str], "accuracy_estimate": float}'
)
response = client.messages.create(
model='claude-opus-4-5', max_tokens=512,
messages=[{'role': 'user', 'content': [
{'type': 'image', 'source': {'type': 'base64',
'media_type': 'image/jpeg', 'data': b64}},
{'type': 'text', 'text': prompt}
]}]
)
return json.loads(response.content[0].text)多源推理代理
多源推理代理会系统地收集每种模态中的证据,组合各个信号,并生成带置信度分数的最终结论。它会指出哪些来源支持该结论,哪些来源与之矛盾。
def multi_source_reasoning(
claim: str,
evidence_sources: list # list of {'type': 'text'|'image', 'content': str|path}
) -> dict:
import anthropic, base64, json
client = anthropic.Anthropic(api_key='YOUR_API_KEY')
content_blocks = [
{'type': 'text',
'text': f'Evaluate this claim using ALL sources below:\nClaim: "{claim}"\n'}
]
for i, src in enumerate(evidence_sources):
if src['type'] == 'text':
content_blocks.append(
{'type': 'text', 'text': f'Source {i+1} (text): {src["content"]}'}
)
elif src['type'] == 'image':
with open(src['content'], 'rb') as f:
b64 = base64.standard_b64encode(f.read()).decode('utf-8')
content_blocks.append(
{'type': 'text', 'text': f'Source {i+1} (image):'}
)
content_blocks.append(
{'type': 'image', 'source': {'type': 'base64',
'media_type': 'image/jpeg', 'data': b64}}
)
content_blocks.append({'type': 'text', 'text':
'Return JSON: {"verdict": str, "confidence": float, '
'"supporting_sources": [int], "contradicting_sources": [int]}'
})
response = client.messages.create(
model='claude-opus-4-5', max_tokens=512,
messages=[{'role': 'user', 'content': content_blocks}]
)
return json.loads(response.content[0].text)图像到文本的事实生成
有时您会获得一张图像,需要从中生成结构化事实,以供后续基于文本的推理使用。请从图表和表格中提取定量事实并保存为 JSON,以便通过数学方式验证其是否与文本主张一致。
def extract_facts_from_chart(chart_path: str) -> dict:
import anthropic, base64, json
client = anthropic.Anthropic(api_key='YOUR_API_KEY')
with open(chart_path, 'rb') as f:
b64 = base64.standard_b64encode(f.read()).decode('utf-8')
prompt = (
'Extract all quantitative data from this chart. '
'Return JSON with: chart_type, x_axis_label, y_axis_label, '
'and data_points as [{label: str, value: float}].\n'
'Also extract any trend: increasing/decreasing/stable/volatile.'
)
response = client.messages.create(
model='claude-opus-4-5', max_tokens=512,
messages=[{'role': 'user', 'content': [
{'type': 'image', 'source': {'type': 'base64',
'media_type': 'image/jpeg', 'data': b64}},
{'type': 'text', 'text': prompt}
]}]
)
return json.loads(response.content[0].text)按置信度阈值路由
完成跨模态推理后,请根据置信度路由结果:高置信度 → 自动批准;中等置信度 → 标记供选择性审核;低置信度 → 提交人工处理。无论置信度分数如何,对于相互冲突的信号都绝不能自动批准。
def route_cross_modal_result(result: dict) -> str:
confidence = result.get('confidence', 0.0)
has_contradiction = bool(result.get('contradicting_sources'))
if has_contradiction:
return 'ESCALATE'
if confidence >= 0.85:
return 'AUTO_APPROVE'
if confidence >= 0.6:
return 'OPTIONAL_REVIEW'
return 'ESCALATE'
# Example routing table:
# confidence >= 0.85, no contradiction -> AUTO_APPROVE
# confidence 0.6-0.85, no contradiction -> OPTIONAL_REVIEW
# any contradiction, or confidence < 0.6 -> ESCALATE
def handle_routing(claim: str, evidence_sources: list):
result = multi_source_reasoning(claim, evidence_sources)
action = route_cross_modal_result(result)
print(f'Claim: "{claim}"')
print(f'Verdict: {result["verdict"]} (confidence={result["confidence"]:.2f})')
print(f'Action: {action}')
return action, result处理视觉证据不足
有时图像的分辨率过低、过于模糊或部分被遮挡,无法提供有用证据。代理必须检测到这种情况,并停止作出跨模态结论,而不是凭空生成一个结论。
def assess_image_evidence_quality(
image_path: str,
claim: str
) -> dict:
import anthropic, base64, json
client = anthropic.Anthropic(api_key='YOUR_API_KEY')
with open(image_path, 'rb') as f:
b64 = base64.standard_b64encode(f.read()).decode('utf-8')
prompt = (
f'Claim to verify: "{claim}"\n\n'
'Assess whether this image provides sufficient evidence to evaluate the claim.\n'
'Consider: image quality, relevance, completeness, and readability.\n'
'Return JSON: {"sufficient": bool, "quality_issues": [str], '
'"usable_evidence": str}'
)
response = client.messages.create(
model='claude-opus-4-5', max_tokens=256,
messages=[{'role': 'user', 'content': [
{'type': 'image', 'source': {'type': 'base64',
'media_type': 'image/jpeg', 'data': b64}},
{'type': 'text', 'text': prompt}
]}]
)
return json.loads(response.content[0].text)构建跨模态事实核查器
将所有内容结合起来:构建一个文档事实核查器,接收一份报告(文本和嵌入式图像),并根据支持性的图表和表格验证文本中的每个定量主张。返回一份结构化验证报告。
def fact_check_report(
report_text: str,
image_paths: list
) -> dict:
import re
# Extract numeric claims from text (simple regex pattern)
claim_pattern = r'[A-Z][^.!?]*[0-9][%$][^.!?]*[.!?]'
claims = re.findall(claim_pattern, report_text)
results = []
for claim in claims:
sources = [
{'type': 'text', 'content': report_text},
] + [{'type': 'image', 'content': p} for p in image_paths]
reasoning = multi_source_reasoning(claim, sources)
action = route_cross_modal_result(reasoning)
results.append({
'claim': claim,
'verdict': reasoning['verdict'],
'confidence': reasoning['confidence'],
'action': action
})
total = len(results)
auto_approved = sum(1 for r in results if r['action'] == 'AUTO_APPROVE')
return {
'total_claims': total,
'auto_approved': auto_approved,
'escalated': total - auto_approved,
'details': results
}知识检查
当文本信号与图表信号彼此矛盾时,根据最佳实践,跨模态代理应该怎么做?
回顾:跨模态推理模式
您已完成本课。要点如下:
- 文本-图像对齐验证:根据视觉证据验证文本主张
- 信号组合:采用加权信任(对于数字,图表 > 正文),结构化来源优于非结构化来源
- 矛盾检测:始终提交人工处理,绝不自动解决矛盾
- 按置信度路由:自动批准(高)→ 选择性审核(中)→ 提交人工处理(低或矛盾)
- 证据不足:宁可不作结论,也不要凭空生成跨模态结论
下一课程:物联网与传感器驱动的代理——使用 MQTT 处理现实世界的数据流。
常见问题解答
「跨模态推理模式」课时是免费的吗?
是的 — 「跨模态推理模式」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Agents 课程的其余内容,请升级到 CoddyKit PRO。 AI Agents 课程共包含 4 节课。
「跨模态推理模式」这节课中我会学到什么?
将文本主张与图像建立依据联系,并综合多来源多模态上下文 你通过在浏览器中直接运行的动手代码来练习 AI Agents,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 AI Agents 需要有经验吗?
无需任何先前经验。CoddyKit 上的 AI Agents 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「跨模态推理模式」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 AI Agents 课中编写并运行代码吗?
能。每节 AI Agents 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。