以编程方式使用文档

概述

本指南演示如何使用 Deep Agents.

你构建的智能体将:

  1. 从以下位置加载语音和工作流规则 AGENTS.md 以及技能文件夹
  2. 将网络研究委托给专门的子智能体,使用 web_search
  3. 根据加载的技能起草博客或社交内容
  4. 使用 Gemini 生成封面或社交图片,并保存文件到项目目录

本教程中的代码连接了图像生成工具和文件系统后端,使智能体能够在项目目录下读取和写入帖子、研究笔记和图片。完整的可运行项目,请参阅 content-builder-agent example.

关键概念

本教程涵盖:

前提条件

API 密钥:

  • - Anthropic (Claude) 或其他提供商 API 密钥
  • - Google (Gemini) 用于图像生成,配合 gemini-2.5-flash-image
  • - Tavily 用于网络搜索(免费层)
  • - LangSmith 用于追踪(可选)

Python 3.11 或更高版本。

设置

Create project directory

mkdir content-builder-agent
cd content-builder-agent

Install dependencies

pip install deepagents google-genai pillow pyyaml rich tavily-python langchain
uv init
uv add deepagents google-genai pillow pyyaml rich tavily-python langchain
uv sync

固定 deepagents 到你自己的项目中的一个支持范围(例如 >=0.3.5,<0.4.0)以匹配上游示例。

Set API keys

添加配置文件

该示例将行为保存在三种文件中:记忆、技能和子智能体定义。

Add AGENTS.md

在项目根目录创建 AGENTS.md 。 当你稍后创建智能体并将此文件指定为 记忆 参数的一部分时,它会被加载到系统提示中,以便品牌声音和研究期望适用于每次运行。

# Content Writer Agent

You are a content writer for a technology company. Your job is to create engaging, informative content that educates readers about AI, software development, and emerging technologies.

## Brand Voice

- **Professional but approachable**: Write like a knowledgeable colleague, not a textbook
- **Clear and direct**: Avoid jargon unless necessary; explain technical concepts simply
- **Confident but not arrogant**: Share expertise without being condescending
- **Engaging**: Use concrete examples, analogies, and stories to illustrate points

## Writing Standards

1. **Use active voice**: "The agent processes requests" not "Requests are processed by the agent"
2. **Lead with value**: Start with what matters to the reader, not background
3. **One idea per paragraph**: Keep paragraphs focused and scannable
4. **Concrete over abstract**: Use specific examples, numbers, and case studies
5. **End with action**: Every piece should leave the reader knowing what to do next

## Content Pillars

Our content focuses on:
- AI agents and automation
- Developer tools and productivity
- Software architecture and best practices
- Emerging technologies and trends

## Formatting Guidelines

- Use headers (H2, H3) to break up long content
- Include code examples where relevant (with syntax highlighting)
- Add bullet points for lists of 3+ items
- Keep sentences under 25 words when possible
- Include a clear call-to-action at the end

## Research Requirements

Before writing on any topic:
1. Use the `researcher` subagent for in-depth topic research
2. Gather at least 3 credible sources
3. Identify the key points readers need to understand
4. Find concrete examples or case studies to illustrate concepts

要使此代理符合您自己的语气、支柱和格式规则,请更新 AGENTS.md.

Add subagents.yaml

创建一个名为 subagents.yaml. 然后添加以下描述的 txt 文件 researcher 具有 Tavily 支持的 web_search 工具、Haiku 模型 ID,以及在从主代理委派时将结果保存到您指定的路径的说明:

# Subagent definitions
# These are loaded by content_writer.py and wired up with tools

researcher:
  description: >
    ALWAYS use this first to research any topic before writing content.
    Searches the web for current information, statistics, and sources.
    When delegating, tell it the topic AND the file path to save results
    (e.g., 'Research renewable energy and save to research/renewable-energy.md').
  model: anthropic:claude-haiku-4-5-20251001
  system_prompt: |
    You are a research assistant. You have access to web_search and write_file tools.

    ## Your Tools
    - web_search(query, max_results=5, topic="general") - Search the web
    - write_file(file_path, content) - Save your findings

    ## Your Process
    1. Use web_search to find information on the topic
    2. Make 2-3 targeted searches with specific queries
    3. Gather key statistics, quotes, and examples
    4. Save findings to the file path specified in your task

    ## Important
    - The user will tell you WHERE to save the file - use that exact path
    - Always include source URLs in your findings
    - Keep findings concise but informative
  tools:
    - web_search

该文件稍后在创建深度代理时作为参数传递。

Add skills

创建一个 skills/ 目录。每个技能是一个包含 SKILL.md 文件的文件夹,包含 YAML 前端内容 (name, description) 和技能说明。

创建 skills/blog-post/SKILL.md 并在其中复制以下文本,其中包含有关创作长篇文章、优化内容以进行 SEO 以及生成封面图片的信息。

---
name: blog-post
description: Writes and structures long-form blog posts, creates tutorial outlines, and optimizes content for SEO with cover image generation. Use when the user asks to write a blog post, article, how-to guide, tutorial, technical writeup, thought leadership piece, or long-form content.
---

# Blog Post Writing Skill

## Research First (Required)

**Before writing any blog post, you MUST delegate research:**

1. Use the `task` tool with `subagent_type: "researcher"`
2. In the description, specify BOTH the topic AND where to save:

task( subagent_type="researcher", description="Research [TOPIC]. Save findings to research/[slug].md" )

Example:

task( subagent_type="researcher", description="Research the current state of AI agents in 2025. Save findings to research/ai-agents-2025.md" )

3. After research completes, read the findings file before writing

## Output Structure (Required)

**Every blog post MUST have both a post AND a cover image:**

blogs/ └── <slug>/ ├── post.md # 博客文章内容 └── hero.png # 必需:生成的封面图片

Example: A post about "AI Agents in 2025" → `blogs/ai-agents-2025/`

**You MUST complete both steps:**
1. Write the post to `blogs/<slug>/post.md`
2. Generate a cover image using `generate_image` and save to `blogs/<slug>/hero.png`

**A blog post is NOT complete without its cover image.**

## Blog Post Structure

Every blog post should follow this structure:

### 1. Hook (Opening)
- Start with a compelling question, statistic, or statement
- Make the reader want to continue
- Keep it to 2-3 sentences

### 2. Context (The Problem)
- Explain why this topic matters
- Describe the problem or opportunity
- Connect to the reader's experience

### 3. Main Content (The Solution)
- Break into 3-5 main sections with H2 headers
- Each section covers one key point
- Include code examples, diagrams, or screenshots where helpful
- Use bullet points for lists

### 4. Practical Application
- Show how to apply the concepts
- Include step-by-step instructions if applicable
- Provide code snippets or templates

### 5. Conclusion & CTA
- Summarize key takeaways (3 bullets max)
- End with a clear call-to-action
- Link to related resources

## Cover Image Generation

After writing the post, generate a cover image using the `generate_cover` tool:

generate_cover(prompt="A detailed description of the image...", slug="your-blog-slug")

The tool saves the image to `blogs/<slug>/hero.png`.

### Writing Effective Image Prompts

Structure your prompt with these elements:

1. **Subject**: What is the main focus? Be specific and concrete.
2. **Style**: Art direction (minimalist, isometric, flat design, 3D render, watercolor, etc.)
3. **Composition**: How elements are arranged (centered, rule of thirds, symmetrical)
4. **Color palette**: Specific colors or mood (warm earth tones, cool blues and purples, high contrast)
5. **Lighting/Atmosphere**: Soft diffused light, dramatic shadows, golden hour, neon glow
6. **Technical details**: Aspect ratio considerations, negative space for text overlay

### Example Prompts

**For a technical blog post:**

相互连接的发光立方体的等距 3D 插图,代表 AI 代理,每个立方体都有微妙的电路图案。立方体由发光数据流连接。深海军蓝背景 (#0a192f),带有电蓝色 (#64ffda) 和柔和紫色 (#c792ea) 的点缀。简洁的极简风格,顶部有大量留白用于标题。专业的科技美学。

**For a tutorial/how-to:**

扁平简洁的插图,展示双手在键盘上打字,抽象的代码符号向上飘浮,变成灯泡和齿轮。温暖的渐变背景,从柔和的珊瑚色到浅桃色。友好、平易近人的风格。中央构图,有空间进行文字叠加。

**For thought leadership:**

人像轮廓与几何神经网络图案融合的抽象可视化。分割构图 - 左侧是有机水彩纹理过渡到右侧干净的矢量线条。柔和的鼠尾草绿和温暖的赤陶色配色方案。沉思的、前瞻性的氛围。

## SEO Considerations

- Include the main keyword in the title and first paragraph
- Use the keyword naturally 3-5 times throughout
- Keep the title under 60 characters
- Write a meta description (150-160 characters)

## Quality Checklist

Before finishing:
- [ ] Post saved to `blogs/<slug>/post.md`
- [ ] Hero image generated at `blogs/<slug>/hero.png`
- [ ] Hook grabs attention in first 2 sentences
- [ ] Each section has a clear purpose
- [ ] Conclusion summarizes key points
- [ ] CTA tells reader what to do next
`

接下来,创建 skills/social-media/SKILL.md 并在其中复制以下文本,其中包含有关起草社交媒体帖子和生成配图的信息:

---
name: social-media
description: Drafts engaging social media posts, writes hooks, suggests hashtags, creates thread structures, and generates companion images. Use when the user asks to write a LinkedIn post, tweet, Twitter/X thread, social media caption, social post, or repurpose content for social platforms.
---

# Social Media Content Skill

## Research First (Required)

**Before writing any social media content, you MUST delegate research:**

1. Use the `task` tool with `subagent_type: "researcher"`
2. In the description, specify BOTH the topic AND where to save:

task( subagent_type="researcher", description="Research [TOPIC]. Save findings to research/[slug].md" )

Example:

task( subagent_type="researcher", description="Research renewable energy trends in 2025. Save findings to research/renewable-energy.md" )

3. After research completes, read the findings file before writing

## Output Structure (Required)

**Every social media post MUST have both content AND an image:**

**LinkedIn posts:**

linkedin/ └── <slug>/ ├── post.md # 帖子内容 └── image.png # 必需:生成的视觉内容

**Twitter/X threads:**

tweets/ └── <slug>/ ├── thread.md # 推文串内容 └── image.png # 必需:生成的视觉内容

Example: A LinkedIn post about "prompt engineering" → `linkedin/prompt-engineering/`

**You MUST complete both steps:**
1. Write the content to the appropriate path
2. Generate an image using `generate_image` and save alongside the post

**A social media post is NOT complete without its image.**

## Platform Guidelines

### LinkedIn

**Format:**
- 1,300 character limit (show more after ~210 chars)
- First line is crucial - make it hook
- Use line breaks for readability
- 3-5 hashtags at the end

**Tone:**
- Professional but personal
- Share insights and learnings
- Ask questions to drive engagement
- Use "I" and share experiences

**Structure:**

[钩子 - 1 行引人入胜的内容]

[空行]

[背景 - 为什么这很重要]

[空行]

[核心洞察 - 2-3 段简短内容]

[空行]

[行动号召或问题]

#hashtag1 #hashtag2 #hashtag3

### Twitter/X

**Format:**
- 280 character limit per tweet
- Threads for longer content (use 1/🧵 format)
- No more than 2 hashtags per tweet

**Thread Structure:**

1/🧵 [Hook - the main insight]

2/ [Supporting point 1]

3/ [Supporting point 2]

4/ [Example or evidence]

5/ [Conclusion + CTA]

## Image Generation

Every social media post needs an eye-catching image. Use the `generate_social_image` tool:

generate_社交_image(prompt="A detailed description...", platform="linkedin", slug="your-post-slug")

The tool saves the image to `<platform>/<slug>/image.png`.

### Social Image Best Practices

Social images need to work at small sizes in crowded feeds:
- **Bold, simple compositions** - one clear focal point
- **High contrast** - stands out when scrolling
- **No text in image** - too small to read, platforms add their own
- **Square or 4:5 ratio** - works across platforms

### Writing Effective Prompts

Include these elements:

1. **Single focal point**: One clear subject, not a busy scene
2. **Bold style**: Vibrant colors, strong shapes, high contrast
3. **Simple background**: Solid color, gradient, or subtle texture
4. **Mood/energy**: Match the post tone (inspiring, urgent, thoughtful)

### Example Prompts

**For an insight/tip post:**

一只发光灯泡漂浮在深紫色渐变背景前,灯泡由互联的金色几何线条构成,柔和的光线向外散发。极简、醒目、高对比度。正方形构图。

**For announcements/news:**

由彩色几何形状构成的抽象火箭飞船向上发射,尾部带有粒子轨迹。明亮的珊瑚色和青色配色方案,白色背景。充满活力、庆祝的氛围。粗犷扁平插画风格。

**For thought-provoking content:**

两个重叠的半透明圆形,一个蓝色一个橙色,在中心形成一个发光的交集。代表协作或思想交汇。深炭灰色背景,柔和空灵的光晕。极简且沉思的风格。

## Content Types

### Announcement Posts
- Lead with the news
- Explain the impact
- Include link or next step

### Insight Posts
- Share one specific learning
- Explain the context briefly
- Make it actionable

### Question Posts
- Ask a genuine question
- Provide your take first
- Keep it focused on one topic

## Quality Checklist

Before finishing:
- [ ] Post saved to `linkedin/<slug>/post.md` or `tweets/<slug>/thread.md`
- [ ] Image generated alongside the post
- [ ] First line hooks attention
- [ ] Content fits platform limits
- [ ] Tone matches platform norms
- [ ] Has clear CTA or question
- [ ] Hashtags are relevant (not generic)
`

它们指示代理先调用 researcher 子代理,先在 blogs/, linkedin/, or tweets/下编写 Markdown,然后调用 generate_cover or generate_social_image 来生成图像。

当你之后创建代理并指定技能文件夹时,文件的 frontmatter SKILLS.md 这些技能文件夹中的文件会被加载到系统提示中,这样当任务与技能描述匹配时,代理就能使用该技能。

构建脚本

在项目根目录创建 content_writer.py 。以下部分按顺序属于一个文件。

Add tools

研究子代理使用 Tavily 搜索。 博客和社交工作流使用 Gemini 图像生成。 之后创建代理时, load_subagents 函数会读取 subagents.yaml 并将工具名称解析为这些装饰函数。

Create the agent

使用 @[create_深度_代理] 创建深度代理时,传递内存路径、技能目录、图像工具、YAML 中的子代理和一个 FilesystemBackend 以示例目录为根,这样像 ./AGENTS.md./skills/ 这样的路径就能正确解析。

Add an entry point

使用用户消息调用代理以验证代理是否正常工作:

运行代理

从项目目录你可以不传递参数或传递提示作为参数来调用代理:

python content_writer.py
python content_writer.py Write a blog post about prompt engineering

使用 LANGSMITH_API_KEY 设置,你可以在 LangSmith.

输出

成功时,生成的生成物会写入系统临时目录(在 macOS 和 Linux 上,通常在 /tmp/),而不是项目文件旁边。

blogs/
└── prompt-engineering/
    ├── post.md
    └── hero.png
research/
└── prompt-engineering.md

路径遵循 SKILL.md.

完整代码

浏览完整的 content-builder-agent 示例 在 GitHub 上,包括基于 Rich 的流式 UI。

后续步骤

  • - 编辑 AGENTS.md 以更改品牌声音和研究需求
  • - 在 skills/<name>/SKILL.md 下添加技能以支持新的内容类型
  • - 在 subagents.yaml 下添加子代理,并在 load_subagents
  • - 阅读 子代理, 技能自定义 以进行更深入的配置