M5 智能体式人工智能 - 市场调研团队
2026/8/5 17:04:19
动手实验:编排一支由四个智能体组成的团队(市场调研、图形设计师、文案撰写、打包),构成一条流水线,把太阳镜营销简报转化为一份可呈报高层的营销活动报告。
M5 智能体式人工智能 - 市场调研团队
1. 简介
1.1. 实验概览
在这个实验中,你将扮演一家时尚品牌的技术 AI 负责人,为一场夏季太阳镜营销活动做准备。你的任务是设计一条全自动的创意流水线,还原一个真实的商业场景。你不会手动处理每一个环节,而是引导一个系统去扫描网络信息源、发现新兴的时尚趋势,将这些趋势与内部产品目录中的太阳镜相匹配,设计一张营销活动视觉图,生成一句简短的营销文案,最后把这一切打包成一份可直接呈报高层的报告。
这个实验的目标是体验多个智能体、工具和模型如何被编排成一条统一、连贯的工作流。完成本实验后,你将构建出一条流水线,它给人的感觉不再是一堆孤立步骤的脚本,而更像一个小团队协作解决一项创意挑战。
1.2. 🎯 学习目标
通过完成本实验,你将看到如何从与模型的单轮交互,迈向设计能够协调规划、研究和创意生成的多智能体流水线。你将学习如何将智能体的推理建立在外部工具之上,从而让输出不仅富有想象力,还有真实数据的支撑。你还将实验反思和打包步骤,它们能强制执行质量把控,并为高层受众准备好结果。
简而言之,这个实验教你如何将大语言模型的想象力与结构化工作流的严谨性结合起来,为你提供一种构建既有创造力、又足够可靠的自主系统的实用模式。
2. 环境搭建:导入库并加载环境
与之前的实验一样,你现在将导入所需的库、加载环境变量,并搭建辅助工具。
# =========================
# Imports
# =========================
# --- Standard library ---
import base64
import json
import os
import re
from datetime import datetime
from io import BytesIO
# --- Third-party ---
import requests
import openai
from PIL import Image
from dotenv import load_dotenv
from IPython.display import Markdown, display
import aisuite
# --- Local / project ---
import tools
import utils
# =========================
# Environment & Client
# =========================
load_dotenv()
client = aisuite.Client()
3. 可用工具
只有当模型被赋予明确的能力、超越其基础推理时,智能体流水线才会真正发挥作用。提前声明这些工具,能让智能体的行动空间变得清晰明确,确保提示词能自然地引导工具选择,并通过定义良好的接口,让编排和测试保持透明。
你将组建一支市场调研团队——一组协作设计夏季太阳镜营销活动的专业化智能体。为了赋予它们能力,我们首先定义能让它们的推理建立在真实数据之上的工具。
第一个工具是 tools.tavily_search_tool,它会执行实时的网络搜索,挖掘当前时尚趋势的证据。现在就运行一次简单的查询,试试搜索*“trends in sunglasses fashion”*(太阳镜时尚趋势):
tools.tavily_search_tool('trends in sunglasses fashion')
第二个工具是 tools.product_catalog_tool,它会返回内部的太阳镜产品目录。每个条目都包含产品名称、ID、描述、库存数量和价格等详情。这份结构化数据将让各个智能体能够把线上时尚趋势与实际在库商品联系起来:
tools.product_catalog_tool()
有了这些工具,你就定义好了一个清晰的行动空间和可靠的数据来源。在下一节中,你将构建使用这些工具、把原始的时尚信号转化为结构化洞见和营销素材的智能体。
4. 智能体定义 — 组建你的团队
既然你已经定义好了工具,现在是时候让它们发挥作用了。在这个阶段,你将组建一支市场调研团队——一组由你用自然语言指令直接指挥的专业化智能体。
每个智能体都依赖你之前介绍的工具,它们共同把原始的趋势数据转化为一份精美的营销活动报告。我们将逐一定义它们,介绍各自的角色,并展示实现每个角色的代码。
4.1. 市场调研智能体
有了市场调研智能体(Market Research Agent),你迈出了构建营销活动的第一步。你要求它用 tavily_search_tool 扫描网络,发现当前太阳镜时尚领域正在流行什么。然后你指示它用 product_catalog_tool 将这些信号与你的内部产品目录进行交叉核对,从而了解你的哪些产品符合当下的潮流。
这个智能体会给你一份简明的简报:它发现的主要时尚洞见、与这些洞见相符的产品,以及一段简短的说明,解释为什么这些选品适合你的夏季营销活动。这为你规划营销活动的其余部分,提供了一个清晰、数据驱动的基础。
现在你可以运行下方单元格,用代码定义市场调研智能体。
def market_research_agent(return_messages: bool = False):
utils.log_agent_title_html("Market Research Agent", "🕵️♂️")
prompt_ = f"""
You are a fashion market research agent tasked with preparing a trend analysis for a summer sunglasses campaign.
Your goal:
1. Explore current fashion trends related to sunglasses using web search.
2. Review the internal product catalog to identify items that align with those trends.
3. Recommend one or more products from the catalog that best match emerging trends.
4. If needed, today date is {datetime.now().strftime("%Y-%m-%d")}.
You can call the following tools:
- tavily_search_tool: to discover external web trends.
- product_catalog_tool: to inspect the internal sunglasses catalog.
Once your analysis is complete, summarize:
- The top 2–3 trends you found.
- The product(s) from the catalog that fit these trends.
- A justification of why they are a good fit for the summer campaign.
"""
messages = [{"role": "user", "content": prompt_}]
tools_ = tools.get_available_tools()
while True:
response = client.chat.completions.create(
model="openai:o4-mini",
messages=messages,
tools=tools_,
tool_choice="auto"
)
msg = response.choices[0].message
if msg.content:
utils.log_final_summary_html(msg.content)
return (msg.content, messages) if return_messages else msg.content
if msg.tool_calls:
for tool_call in msg.tool_calls:
utils.log_tool_call_html(tool_call.function.name, tool_call.function.arguments)
result = tools.handle_tool_call(tool_call)
utils.log_tool_result_html(result)
messages.append(msg)
messages.append(tools.create_tool_response_message(tool_call, result))
else:
utils.log_unexpected_html()
return ("[⚠️ Unexpected: No tool_calls or content returned]", messages) if return_messages else "[⚠️ Unexpected: No tool_calls or content returned]"
我们来试着让市场调研智能体为我们的夏季太阳镜营销活动提供一些建议。
market_research_result = market_research_agent()
接下来,你将借助图形设计师智能体,把这份简报转化为一个视觉概念。
4.2. 图形设计师智能体
有了图形设计师智能体(Graphic Designer Agent),你就从分析阶段迈向了创意阶段。
你拿着市场调研智能体给出的简报,让这个智能体把它转化为一个视觉概念。
由于 aisuite 目前还不支持直接生成图像(例如 gpt-image-1-mini),你需要分两个阶段来引导这个过程:
- 首先,智能体使用
aisuite搭配一个 OpenAI 文本模型(o4-mini),构思出一段生动的提示词和一句简短、吸引人的文案。 - 然后,这段提示词会被发送给 OpenAI 的
gpt-image-1-miniAPI,生成营销活动图像本身。
最终结果会给你带来所需要的一切:生成的图像(本地保存以便复用)、产生该图像的确切提示词(便于迭代),以及一句用于营销活动叙事的精炼文案。
现在你可以运行下方单元格,用代码定义图形设计师智能体。
import base64
def graphic_designer_agent(trend_insights: str, caption_style: str = "short punchy", size: str = "1024x1024") -> dict:
utils.log_agent_title_html("Graphic Designer Agent", "🎨")
# Step 1: Generate prompt and caption using aisuite
system_message = (
"You are a visual marketing assistant. Based on the input trend insights, "
"write a creative and visual prompt for an AI image generation model, and also a short caption."
)
user_prompt = f"""
Trend insights:
{trend_insights}
Please output:
1. A vivid, descriptive prompt to guide image generation.
2. A marketing caption in style: {caption_style}.
Respond in this format:
{{"prompt": "...", "caption": "..."}}
"""
chat_response = client.chat.completions.create(
model="openai:o4-mini",
messages=[
{"role": "system", "content": system_message},
{"role": "user", "content": user_prompt}
]
)
content = chat_response.choices[0].message.content.strip()
match = re.search(r'\{.*\}', content, re.DOTALL)
parsed = json.loads(match.group(0)) if match else {"error": "No JSON returned", "raw": content}
prompt = parsed["prompt"]
caption = parsed["caption"]
# Step 2: Generate image with gpt-image-1-mini (returns base64, not URL)
openai_client = openai.OpenAI()
image_response = openai_client.images.generate(
model="gpt-image-1-mini",
prompt=prompt,
size=size,
quality="medium", # gpt-image-1 accepts: low | medium | high | auto
n=1,
# no response_format — gpt-image-1 always returns b64_json
)
b64 = image_response.data[0].b64_json
img_bytes = base64.b64decode(b64)
img = Image.open(BytesIO(img_bytes))
image_path = "generated_image.png"
img.save(image_path)
utils.log_final_summary_html(f"""
<h3>Generated Image and Caption</h3>
<p><strong>Image Path:</strong> <code>{image_path}</code></p>
<p><strong>Generated Image:</strong></p>
<img src="{image_path}" alt="Generated Image" style="max-width: 100%; height: auto; border: 1px solid #ccc; border-radius: 8px; margin-top: 10px; margin-bottom: 10px;">
<p><strong>Prompt:</strong> {prompt}</p>
""")
return {
"image_path": image_path,
"prompt": prompt,
"caption": caption,
}
现在,让我们运行 graphic_designer_agent,使用市场调研智能体提供的趋势洞见,生成一张营销活动图像。
graphic_designer_agent_result = graphic_designer_agent(
trend_insights=market_research_result,
)
有了视觉图之后,你将使用文案撰写智能体来打造营销活动的文字风格。
4.3. 文案撰写智能体
在市场调研智能体和图形设计师智能体完成各自的工作之后,你现在转向文案撰写智能体(Copywriter Agent)。手握营销活动图像和趋势摘要,你要求这个智能体创作出营销活动的“声音”。
它把图像和分析结果一起作为多模态输入,构思出一句简短、优雅、能够捕捉信息精髓的营销文案。除了这句文案之外,它还会给出一段清晰的说明——解释为什么这句话适合这张图,以及它是如何呼应这些趋势的。
这样一来,你得到的不只是一句吸引人的文案,还有其背后的推理依据,让你在面对利益相关者时,更容易为其辩护和加以完善。
def copywriter_agent(image_path: str, trend_summary: str, model: str = "openai:o4-mini") -> dict:
"""
Uses aisuite (OpenAI only) to send an image and a trend summary and return a campaign quote.
Args:
image_path (str): URL of the image to be analyzed.
trend_summary (str): Text from the researcher agent.
model (str): OpenAI model (e.g., openai:o4-mini, openai:gpt-4o)
Returns:
dict: {
"quote": "...",
"justification": "...",
"image_path": "..."
}
"""
utils.log_agent_title_html("Copywriter Agent", "✍️")
# Step 1: Load local image and encode as base64
with open(image_path, "rb") as f:
img_bytes = f.read()
b64_img = base64.b64encode(img_bytes).decode("utf-8")
# Step 2: Build OpenAI-compliant multimodal message
messages = [
{
"role": "system",
"content": "You are a copywriter that creates elegant campaign quotes based on an image and a marketing trend summary."
},
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": f"data:image/png;base64,{b64_img}",
"detail": "auto"
}
},
{
"type": "text",
"text": f"""
Here is a visual marketing image and a trend analysis:
Trend summary:
\"\"\"{trend_summary}\"\"\"
Please return a JSON object like:
{{
"quote": "A short, elegant campaign phrase (max 12 words)",
"justification": "Why this quote matches the image and trend"
}}"""
}
]
}
]
# Step 3: Send request via aisuite
response = client.chat.completions.create(
model=model,
messages=messages,
)
# Step 4: Parse JSON response
content = response.choices[0].message.content.strip()
utils.log_final_summary_html(content)
try:
match = re.search(r'\{.*\}', content, re.DOTALL)
parsed = json.loads(match.group(0)) if match else {"error": "No valid JSON returned"}
except Exception as e:
parsed = {"error": f"Failed to parse: {e}", "raw": content}
parsed["image_path"] = image_path
return parsed
接下来,我们调用文案撰写智能体,基于营销活动图像和之前生成的趋势洞见,生成一句简短的营销活动文案。
copywriter_agent_result = copywriter_agent(
image_path=graphic_designer_agent_result["image_path"],
trend_summary=market_research_result,
)
有了文案和说明之后,你将使用打包智能体,把这一切整合成一份可直接呈报高层的成果。
4.4. 打包智能体
最后,你请出打包智能体(Packaging Agent),把一切整合在一起。在市场调研智能体、图形设计师智能体和文案撰写智能体各自贡献了自己的部分之后,这个智能体会把整个故事汇编成一份精美的成果。
你要求它把趋势摘要、营销活动视觉图、精心撰写的文案和说明整合起来,组装成一份可直接呈报高层的 Markdown 报告。在这个过程中,它会重写趋势洞见的表述,使其更清晰、语气更得体,确保文案与图像的样式搭配得当,并把一切组织得专业、有说服力。
完成这一步之后,你就得到了一份完整的营销活动素材包——易于分享、视觉吸引人,并且已经准备好接受 CEO 级别的审阅。
def packaging_agent(trend_summary: str, image_url: str, quote: str, justification: str, output_path: str = "campaign_summary.md") -> str:
"""
Packages the campaign assets into a beautifully formatted markdown report for executive review.
Args:
trend_summary (str): Summary of the market trends.
image_url (str): URL of the campaign image.
quote (str): Marketing quote to overlay.
justification (str): Explanation for the quote.
output_path (str): Path to save the markdown report.
Returns:
str: Path to the saved markdown file.
"""
utils.log_agent_title_html("Packaging Agent", "📦")
# We use this path in the src of the <img>
styled_image_html = f"""

"""
beautified_summary = client.chat.completions.create(
model="openai:o4-mini",
messages=[
{"role": "system", "content": "You are a marketing communication expert writing elegant campaign summaries for executives."},
{"role": "user", "content": f"""
Please rewrite the following trend summary to be clear, professional, and engaging for a CEO audience:
\"\"\"{trend_summary.strip()}\"\"\"
"""}
]
).choices[0].message.content.strip()
utils.log_tool_result_html(beautified_summary)
# Combine all parts into markdown
markdown_content = f"""# 🕶️ Summer Sunglasses Campaign – Executive Summary
## 📊 Refined Trend Insights
{beautified_summary}
## 🎯 Campaign Visual
{styled_image_html}
## ✍️ Campaign Quote
{quote.strip()}
## ✅ Why This Works
{justification.strip()}
---
*Report generated on {datetime.now().strftime('%Y-%m-%d')}*
"""
with open(output_path, "w", encoding="utf-8") as f:
f.write(markdown_content)
return output_path
有了趋势摘要、营销活动图像和文案,你现在把一切交给打包智能体。它的任务是把这些素材汇编成一份精美的、可呈报高层的报告。运行下一个单元格来生成它。
packaging_agent_result = packaging_agent(
trend_summary=market_research_result,
image_url=graphic_designer_agent_result["image_path"],
quote=copywriter_agent_result["quote"],
justification=copywriter_agent_result["justification"],
output_path=f"campaign_summary_{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.md"
)
最终结果将是一份格式精美的营销活动报告,你可以直接在笔记本中查看它。它将包括:
- 一份为便于高层阅读而重写的趋势摘要
- 一张经过样式处理、叠加了你营销活动文案的图像(使用 HTML 实现)
- 一段清晰的说明,让你理解为什么这张视觉图和这句文案与当前趋势相符
- 一个时间戳,准确显示这份报告的生成时间
你可以通过以下方式查看它:
# Load and render the markdown content
with open(packaging_agent_result, "r", encoding="utf-8") as f:
md_content = f.read()
display(Markdown(md_content))
最后,你将把整个工作流封装成一个可调用的函数,一步运行整条流水线。
5. 完整的营销活动流水线 – run_sunglasses_campaign_pipeline
在这一步,你将定义一个函数 run_sunglasses_campaign_pipeline,把所有环节整合成一条统一、顺畅的工作流,用于你的夏季太阳镜营销活动。
该函数将:
- 运行市场调研,扫描时尚趋势并将其与你的产品目录匹配。
- 生成一张风格化的图像和一句文案。
- 创作一句简短、优雅、带有说明的营销活动文案。
- 把一切打包成一份为高层审阅量身定制的精美 Markdown 报告。
通过定义这个函数,你可以一次调用即可运行整条流水线,同时仍然能够追踪中间结果并查看最终报告。
def run_sunglasses_campaign_pipeline(output_path: str = "campaign_summary.md") -> dict:
"""
Runs the full summer sunglasses campaign pipeline:
1. Market research (search trends + match products)
2. Generate visual + caption
3. Generate quote based on image + trend
4. Create executive markdown report
Returns:
dict: Dictionary containing all intermediate results + path to final report
"""
# 1. Run market research agent
trend_summary = market_research_agent()
print("✅ Market research completed")
# 2. Generate image + caption
visual_result = graphic_designer_agent(trend_insights=trend_summary)
image_path = visual_result["image_path"]
print("🖼️ Image generated")
# 3. Generate quote based on image + trends
quote_result = copywriter_agent(image_path=image_path, trend_summary=trend_summary)
quote = quote_result.get("quote", "")
justification = quote_result.get("justification", "")
print("💬 Quote created")
# 4. Generate markdown report
md_path = packaging_agent(
trend_summary=trend_summary,
image_url=image_path,
quote=quote,
justification=justification,
output_path=f"campaign_summary_{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.md"
)
print(f"📦 Report generated: {md_path}")
return {
"trend_summary": trend_summary,
"visual": visual_result,
"quote": quote_result,
"markdown_path": md_path
}
现在你可以通过一次调用来运行整条流水线,生成一份完整的营销活动报告。只需执行下一个单元格:
results = run_sunglasses_campaign_pipeline()
5.1. 结果
运行下方单元格,查看完整营销活动流水线生成的输出。
with open(results["markdown_path"], "r", encoding="utf-8") as f:
md_content = f.read()
display(Markdown(md_content))
6. 关键要点
通过完成这个实验,你已经看到了如何:
- 使用多智能体大模型流水线端到端地自动化一条创意工作流。
- 结合推理、工具调用与外部数据,让你的输出立足于现实。
- 应用能够同时处理文本和图像的多模态模型(如
gpt-4o),完成诸如生成营销活动文案之类的任务。 - 用工具(
tavily_search_tool、product_catalog_tool)扩展模型的能力,让你的输出不仅富有想象力,也切实可行。 - 借助结构化的日志和 HTML 样式的信息块,保持执行过程的透明与可调试。
- 以 Markdown 格式交付一份精美的、可直接呈报高层的报告,将洞见、视觉图和说明融合成一份统一的成果。
🎉 <strong>恭喜!</strong> 🎉
现在你已经成功构建并运行了一条多智能体流水线:你研究了趋势、生成了视觉图、创作了一句营销活动文案,并将一切打包成了一份可直接呈报高层的报告。
这条工作流向你展示了如何把大模型的创造力与结构化编排的严谨性结合起来,为你提供了一种可复用的模式,能够适配到许多现实世界的场景中。🌟
学习地图
本页是「DeepLearningAI > Agentic AI Lab」的第 7 / 7 页——这是一份真实的 DeepLearning.AI 笔记本(代码 + 讲解文字),而非「Agentic AI」板块中那种模板化内容。顺序上接在「M5 智能体式人工智能 - 客服智能体」之后。这是本板块的最后一个实验。代码单元格完全保留了源笔记本中的原样——请在你自己的 Python 环境中按顺序运行它们(它们依赖 utils.py 等本地辅助模块,这里并未包含)。
动手实践——分步指南
搭建好这份笔记本所需的本地依赖(代码单元格中导入的辅助模块,例如 utils.py、display_functions.py,以及文中引用的各个工具模块),然后按照「M5 智能体式人工智能 - 市场调研团队」自身的分步讲解,从上到下依次运行每个代码单元格。在进入下一个实验之前,先尝试文中建议的实验(更换模型、修改提示词、提出你自己的请求)。
三大推荐资源
- 1aisuite (GitHub)
The unified multi-provider LLM client used throughout these labs for chat completions and tool calling.
https://github.com/andrewyng/aisuite
- 2Anthropic Engineering Blog
Practical write-ups on building, evaluating, and operating agentic systems.
https://www.anthropic.com/engineering
链接由 AI 推荐——使用前建议快速核实。