匠人学院 JR Academy
  • Position

    Where am I now, and where should I go?

    How your job is changing, where your experience can take you and what you still need for a target role, worked out from what you have actually done. Free, and the full result needs no sign-up.

    Analyse my career and skills

    Look up a career

    Will AI replace my job?AI impact and transition paths for common careersNew jobs in the AI eraWhat they do, what they need, how to move in

    Focused tools

    AI Engineer interview readiness30 timed questions on what you still need before interviewsCareer personality testDirections that suit how you workReturning to China checkJob prospects in China by school, major and graduation date

    AI coach

    Talk to your AI coachStill unsure after your result? Talk through what is holding you back
  • Core courses

    AI Engineer BootcampEngineering bootcamp from LLM apps to agentsAI Engineer Full-Stack Project Class16 weeks · RAG and full-stack AI projectsVibe Coding Masterclass8 weeks · direct agents to build and ship a productAI Essentials10 hours · use AI for email, reports, data and copyAI Office Automation Course8 weeks · help a whole company adopt AIOne-Person Company (OPC) Bootcamp15 weeks in person · build a one-person company with AIAll courses →

    AI engineering

    Machine Learning & Data Engineering Full-Stack ClassAI Agent & MCP Project BootcampAI Engineer Core TechniquesAI Engineer FoundationsAI Engineer Advanced: RAG to Agents and TuningClaude Code TasterAll AI engineering courses →

    AI at work

    AI Coding for everyoneClaude Code One-Day Masterclass (Non-Technical)Enterprise AI Automation BootcampAI Marketing BootcampAI Risk, Governance and Audit CourseOpenClaw 4-Week Personal AI Assistant BootcampAll AI-at-work courses →

    Career development

    AI Product Manager (BA) Bootcamp + InternshipAustralia IT Interview BootcampAustralia IT Technical Interview BootcampAustralia IT Resume BootcampAustralia Big Tech Job Search BootcampAustralia IT Career Planning BootcampAll career courses →

    Learn free first

    Vibe CodingAI for office workPrompt MasterAI EngineerAI data analysisResource centerInstructorsAll learning paths →
  • Evidence

    What will convince an employer?

    Certifications, projects, team work and competition entries, collected into one portfolio.

    See the portfolio

    Certifications

    Cert Master · all certificationsPrep and mock exams for AWS, Azure, GCP, Claude and moreAWS CLF-C02Entry-level AWS cloud certificationAWS SAA-C03Entry certification for cloud architectsClaude certificationsAnthropic Claude certification seriesAll certifications →

    Projects and team work

    P3 team projectsBuild a project with real teammates in a simulated team workflowP3 project experienceThe parts of a P3 project that go on your resumeDemo DayProject showcaseP3 certificatesProof once a project is completeAll of P3 →

    Competitions and work

    HackathonsBuild something against the clockSubmit your workAdd your project to the showcaseCareerOS portfolioDo tasks in the desktop app; your results become portfolio pieces
    Cert MasterBrowser extension, app and mini programScreenshot a question for analysis and practise anywhereAbout Cert Master
  • Connect

    How do I get myself in front of employers?

    Resume, interviews, referrals and mentors. See how far you are from the target role first, then decide what to fix.

    Start with Jobpin

    Resume and openings

    Graduate careersGraduate preparation across Australia, China, Malaysia, Singapore, the US and UKJobpinAI job search workspace: resume, roles, applicationsAI resumeRewrite your resume against a job descriptionReferralsRoles shared by students and mentorsOpportunitiesInternships, projects and collaborationsOffer boardOffers students have received

    Interviews

    AI Engineer interview guideSeven areas, with worked examplesFDE interview guideFive rounds, from scoping to the customer roundAI mock interviewPractise by text or voice and see the gapsInterview storiesReal interview experiencesSystem Design handbookPrepare for system design interviewsAll interview prep →

    Mentors

    1:1 mentorsBook AI, career and technical mentors by the hourGroup tutoringShare a tutor with a few others and pay less eachCareer coachingResume, interview and direction packages
    Jobpin desktopOne workspace for the whole job searchOrganise real experience and refine resume versions for target roles on macOS or Windows.About Jobpin
BusinessMembershipDownload CareerOS
0
匠人学院 JR Academy

Follow Us

linkedinfacebooktwitterinstagramyoutube

We Accept

/image/layout/pay-paypal.png/image/layout/pay-visa.png/image/layout/pay-master-card.png/image/layout/pay-airwallex.png/image/layout/pay-alipay.png
Airbotix · AI learning & creation for kids Another Life · AI story game
Products46

CareerOS and tools

  • CareerOS
  • Cert Master
  • Jobpin
  • Jobpin web
  • Jobpin report
  • Jobpin desktop download
  • My job search reports
  • Buy report credits
  • Jobpin billing
  • AI Toolbox
  • AI Skill Marketplace

Membership

  • Membership
  • AI membership

Courses

  • Bootcamps
  • Training Camp
  • Kanban learning
  • AI Builder course
  • MCP course
  • NotebookLM workshop
  • Business Analyst course
  • Web Full-Stack Bootcamp
  • DevOps Bootcamp
  • Data Engineering Bootcamp
  • Data Analysis Bootcamp
  • Coding for Beginners
  • Algorithm Bootcamp

Career services

  • Graduate careers
  • Graduate careers in Australia
  • Graduate careers in China
  • Graduate careers in Malaysia
  • Graduate careers in Singapore
  • Graduate careers in the US
  • Graduate careers in the UK
  • 1:1 coaching
  • Career coaching
  • AI Engineer VIP
  • BA & PM Internship
  • Data Science Internship
  • Data Analysis Internship
  • Marketing Internship
  • Resume Review
  • Interview Coaching
  • Job Application Service
  • Job Monitoring
  • LinkedIn Management
  • LinkedIn Networking
Library57

Learning paths

  • All Learning Paths
  • AI Engineer
  • Context Engineering
  • Vibe Coding
  • Prompt Master
  • AI Builder
  • AI Product Manager
  • Python Basics
  • AI Productivity
  • AI Data Analysis
  • AI Finance
  • AI Content Creation
  • AI Image Creation
  • Frontend Development
  • Hermes Agent
  • OpenClaw Local Agent

Interactive labs

  • Prompt Lab
  • Frontend Lab
  • JavaScript Lab
  • Python Lab
  • AWS Lab
  • Azure Lab
  • LLM Lab
  • Git Lab

Reference and guides

  • Resources
  • Wiki
  • Cheat sheets
  • Roadmaps
  • AI roadmaps
  • Videos
  • Ebooks
  • Blog
  • Interview handbook
  • Mock exams
  • Free resources

Cities

  • Sydney
  • Melbourne
  • Brisbane
  • Adelaide
  • Singapore
  • Kuala Lumpur
  • London
  • New York
  • San Francisco
  • Los Angeles
  • Seattle
  • Toronto
  • Vancouver

Immigration

  • Australia Immigration
  • Skilled Visa 189/190/491
  • Employer Sponsored 482/186/494
  • Business Visa 188/888
  • UK Immigration
  • US Immigration
  • Canada Immigration
  • Singapore immigration
  • Malaysia immigration
Business20

For business

  • AI for Business
  • Business portal sign-in
  • Corporate Training
  • Internship Partnership
  • Recruitment Partnership
  • Enterprise (EN)

Metatree AI Lab

  • Metatree AI Lab (Chinese)
  • AI solutions (Chinese)
  • Digital employees (Chinese)
  • Case studies (Chinese)
  • Metatree AI Lab
  • AI services
  • Digital employees
  • Case studies

AI education for kids

  • Airbotix — AI Learning & Creation for Kids
  • AU Family Resource Hub
  • NAPLAN Report Guide
  • My School Data Guide
  • Sydney Private School Fees 2026
  • Kids Coding Programs
About15

Company

  • About Us
  • Our Mentors
  • Become a Mentor
  • Metaverse Classroom
  • JR Careers
  • Another Life — AI Story Game
  • Contact Us

Help and policies

  • FAQs
  • Terms & Conditions
  • Privacy Policy
  • Cancellation & Refund Policy
  • Site map

Friend links

  • CS Browser

Contact

  • hello@jiangren.com.au
  • 0421-672-555

Offices

Level 10b, 144 Edward Street, Brisbane CBD (Headquarter)
Level 2, 171 La Trobe St, Melbourne VIC 3000
45A13, Block B, Oriental Hope Tianxiang Plaza, 500 Tianfu Avenue Middle Section, Wuhou District, Chengdu, Sichuan, China
Business Hub, 155 Waymouth St, Adelaide SA 5000
Disclaimer
footer-disclaimerfooter-disclaimer

JR Academy acknowledges Traditional Owners of Country throughout Australia and recognises the continuing connection to lands, waters and communities. We pay our respect to Aboriginal and Torres Strait Islander cultures; and to Elders past and present. Aboriginal and Torres Strait Islander peoples should be aware that this website may contain images or names of people who have since passed away.

All content on the JR Academy website, including course materials, logos, and information provided, is protected under Australian intellectual property laws. Unauthorized use, sale, distribution, reproduction, or modification is strictly prohibited. Violations may result in legal action. By accessing our website, you agree to respect our intellectual property. JR Academy Pty Ltd reserves all rights, including patents, trademarks, and copyrights. Any infringement will be subject to legal prosecution. View Terms of Service

© 2017-2026 JR Academy Pty Ltd. All rights reserved.

ABN 26621887572

HomeLearnCoursesCerts
  1. Home
  2. Learn
  3. Blog
  4. CrewAI 实战手册:用 Python 编排多 Agent 协作 — 生产上线:FastAPI 封装 + Docker 容器化 + 断点续跑
JR Academy · BlogCareer insights

CrewAI 实战手册:用 Python 编排多 Agent 协作 — 生产上线:FastAPI 封装 + Docker 容器化 + 断点续跑

把 CrewAI Crew 包进 FastAPI、用 Docker Compose 一键部署、用 restore_from_state_id 实现断点续跑——从本地脚本到生产级服务的完整路径

Published2026-12-01
Reading time3 min
Author

Contents

  • 从脚本到服务
  • 用 FastAPI 封装 Crew
  • 同时跑多个 Crew:kickoff_for_each_async
  • 断点续跑:restore_from_state_id(CrewAI 1.14.5+)
  • Docker 容器化
  • 成本控制:生产环境不能放任烧钱
  • 部署后必做:开监控

从脚本到服务

本地 crew.kickoff() 是同步阻塞的,跑完才返回。真实业务里你需要:

  1. HTTP 触发:让后端系统、定时任务、前端按钮能调用 Crew
  2. 异步执行:Crew 跑 2 分钟,API 不能阻塞 2 分钟
  3. 任务状态追踪:用户需要知道"还在跑"还是"已完成"
  4. 失败恢复:网络抖动或 LLM 超时不应该让整个流程重来

这一章把这四件事都解决掉。

用 FastAPI 封装 Crew

项目结构:

my_crew/
├── crew.py           # Crew 定义
├── api.py            # FastAPI 应用
├── Dockerfile
└── docker-compose.yml

crew.py(复用第三章的竞品分析 Crew):

from crewai import Agent, Task, Crew, Process
from crewai_tools import SerperDevTool

def build_crew() -> Crew:
    search = SerperDevTool()

    scout = Agent(
        role="Market Scout",
        goal="找到 {product} 的所有竞品及最新动态",
        backstory="你专门追踪 SaaS 市场动态",
        tools=[search],
        max_iter=5
    )
    analyst = Agent(
        role="Competitive Analyst",
        goal="对比 {product} 和竞品的功能、定价",
        backstory="你擅长结构化分析",
        tools=[search],
        max_iter=5
    )

    scan_task = Task(
        description="搜索 {product} 主要竞品,每个收集官网、功能、定价",
        expected_output="竞品清单表格,至少 5 个竞品",
        agent=scout
    )
    compare_task = Task(
        description="对比 {product} 和每个竞品的优劣势",
        expected_output="详细对比矩阵",
        agent=analyst,
        context=[scan_task]
    )

    return Crew(
        agents=[scout, analyst],
        tasks=[scan_task, compare_task],
        process=Process.sequential
    )

api.py:

import asyncio
import uuid
from fastapi import FastAPI, BackgroundTasks
from pydantic import BaseModel

app = FastAPI()

# 内存 job 状态(生产换 Redis)
jobs: dict[str, dict] = {}

class KickoffRequest(BaseModel):
    product: str

@app.post("/kickoff")
async def kickoff(req: KickoffRequest, background_tasks: BackgroundTasks):
    job_id = str(uuid.uuid4())
    jobs[job_id] = {"status": "running", "result": None}

    async def run():
        try:
            crew = build_crew()
            # kickoff_async() 不阻塞事件循环
            result = await crew.kickoff_async(inputs={"product": req.product})
            jobs[job_id] = {"status": "done", "result": result.raw}
        except Exception as e:
            jobs[job_id] = {"status": "error", "error": str(e)}

    background_tasks.add_task(run)
    return {"job_id": job_id}

@app.get("/status/{job_id}")
def status(job_id: str):
    return jobs.get(job_id, {"status": "not_found"})

@app.get("/health")
def health():
    return {"status": "ok"}

前端轮询 /status/{job_id} 直到 status == "done",再拿 result。

同时跑多个 Crew:kickoff_for_each_async

如果你的场景是"给 10 个产品各跑一次竞品分析",用 kickoff_for_each_async:

from crewai import Crew

products = ["CrewAI", "LangGraph", "AutoGen", "Dify", "Coze"]
inputs_list = [{"product": p} for p in products]

crew = build_crew()
# 并发跑,自动管理事件循环
results = await crew.kickoff_for_each_async(inputs=inputs_list)

for product, result in zip(products, results):
    print(f"{product}: {result.raw[:200]}")

串行跑 5 个可能需要 10 分钟,并发只需要 2-3 分钟(取决于 LLM 限速)。

断点续跑:restore_from_state_id(CrewAI 1.14.5+)

Flow 跑到一半因为网络超时崩了?不用从头来。Flow 支持持久化 State,用 restore_from_state_id 从某个快照分叉:

from crewai.flow.flow import Flow, listen, start, persist
from pydantic import BaseModel

class PipelineState(BaseModel):
    topic: str = ""
    research: str = ""
    article: str = ""

class ContentPipeline(Flow[PipelineState]):
    @start()
    @persist   # 每步执行后自动保存 state
    def pick_topic(self):
        self.state.topic = "CrewAI 2026 生产部署"

    @listen(pick_topic)
    @persist
    def do_research(self, topic):
        result = research_crew.kickoff(inputs={"topic": topic})
        self.state.research = result.raw

    @listen(do_research)
    @persist
    def write_article(self):
        result = writing_crew.kickoff(inputs={
            "topic": self.state.topic,
            "research": self.state.research
        })
        self.state.article = result.raw

pipeline = ContentPipeline()

# 正常跑,拿到 state_id
result = await pipeline.kickoff_async()
state_id = pipeline.state_id   # 保存下来

# 崩了?从某个已保存的快照恢复,分配新 state_id
recovery_pipeline = ContentPipeline()
result = await recovery_pipeline.kickoff_async(
    restore_from_state_id=state_id  # 从该快照加载 state 继续跑
)

@persist 装饰每个步骤,保证每步完成后 state 都写入 SQLite(默认)。restore_from_state_id 加载快照后用新 state_id 写后续结果,原始历史不丢。

注意:restore_from_state_id 和 from_checkpoint 不能同时用,二选一。

Docker 容器化

Dockerfile:

FROM python:3.11-slim

WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .
EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=10s \
  CMD curl -f http://localhost:8000/health || exit 1

CMD ["uvicorn", "api:app", "--host", "0.0.0.0", "--port", "8000"]

docker-compose.yml(含 Redis 用于生产级 job 状态存储):

services:
  crew-api:
    build: .
    ports:
      - "8000:8000"
    environment:
      - OPENAI_API_KEY=${OPENAI_API_KEY}
      - SERPER_API_KEY=${SERPER_API_KEY}
      - REDIS_URL=redis://redis:6379
    depends_on:
      redis:
        condition: service_healthy
    restart: unless-stopped

  redis:
    image: redis:7-alpine
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 10s
      timeout: 5s
      retries: 3
    restart: unless-stopped
# 启动
docker compose up -d

# 测试
curl -X POST http://localhost:8000/kickoff \
  -H "Content-Type: application/json" \
  -d '{"product": "CrewAI"}'

# 查状态
curl http://localhost:8000/status/{job_id}

成本控制:生产环境不能放任烧钱

一个 3-Agent Crew 单次约 $0.10–0.30,定时任务每天跑 100 次就是 $10–30/天。几个硬性规则:

agent = Agent(
    role="...",
    goal="...",
    backstory="...",
    max_iter=5,          # 禁止无限循环
    max_rpm=10,          # 每分钟最多 10 次 LLM 调用(防突发)
)

crew = Crew(
    agents=[...],
    tasks=[...],
    max_rpm=30,          # Crew 级别限速
)

模型路由策略(成本降 60% 的实操):

任务类型 推荐模型 原因
网页搜索 + 信息提取 gpt-4o-mini / claude-haiku-4-5-20251001 够用,比 GPT-4o 便宜 10x
复杂推理 / 决策 claude-sonnet-4-6 / gpt-4o 准确性更重要
最终输出生成 claude-sonnet-4-6 文字质量有要求
本地隐私数据 ollama/llama3.1 零 API 费用

部署后必做:开监控

生产 Crew 挂了你不知道,等于白部署。最省力的方式是接 Langfuse(开源,可自托管):

pip install langfuse
import os
os.environ["LANGFUSE_SECRET_KEY"] = "sk-..."
os.environ["LANGFUSE_PUBLIC_KEY"] = "pk-..."
os.environ["LANGFUSE_HOST"] = "https://cloud.langfuse.com"  # 或自托管地址

# Langfuse 自动 patch CrewAI,无需改任何代码
import langfuse
langfuse.configure()

# 正常 kickoff,所有 LLM 调用自动上报
result = crew.kickoff(inputs={"product": "CrewAI"})

Langfuse Dashboard 可以看到每次 Crew 运行的:token 消耗、延迟分布、每个 Agent 的调用链、失败率。发现某天成本突增,直接 drill down 到具体的 Agent 调用。

Author
Share or copy the link

Related learning resources

  • AI learning hub
  • Prompt engineering
← Previous articleCrewAI 实战手册:用 Python 编排多 Agent 协作 — 测试与调试:用 crewai test 量化 Crew 表现Next article →CrewAI 实战手册:用 Python 编排多 Agent 协作 — Knowledge 知识库:让 Agent 读懂你的私有文档

Related articles

USYD 医疗初创盘点、网络平台注意义务法案、全身 MRI 广告研究

2026-12-02

UQ 皮肤癌在线硕士开办 20 周年、中澳绿色钢铁对话、HIV 预防提醒

2026-12-02

UNSW iFire 2.3 火场模拟系统、AI 卵巢癌预后研究、艺术家与 AI 版权调查

2026-12-02

ANS-C01 退役倒计时 29 天 · AIB-C01 Beta $50 新认证上线 · MLA-C02 Beta 报名开放

2026-12-02

Amazon开放首个自研大模型Ergo,代理作弊率实测差距悬殊,Anthropic格密码结果暂无现实威胁

2026-12-02

GitHub Copilot 实战指南 — Copilot AI Code Review:30 秒让 AI 帮你审 PR,三档深度随需切换

2026-12-01
View all articles →

Done reading? Next steps

Not sure what to learn next? Tell us where you are

Tell us what you do now and where you want to go. See your gaps in skills, evidence, experience, expression and positioning, and what to work on first. No sign-in needed.

Compare with my situation
  • SkillAI Engineer Bootcamp13 weeks, 12 Theory + 13 Practice live classes. You build one Agent system across Context, RAG, Tools, Memory and production Evals. Built for Applied AI and Agent Engineer roles.See the program →
  • PositioningLearning roadmaps by roleFrontend, backend, data, AI and more, laid out stage by stage in the order to learn them.All roadmaps →
  • ExpressionTry an AI mock interviewPick a role and run a mock interview to practise explaining your experience and projects.Practise now →

Not sure what to do next?

Take this page's topic with you and see where your gaps are.

Compare with my situation
JR Academy
AI learning for the global Chinese community
BootcampsFree resourcesLearn AICareer coaching
精选推荐
AI Career Impact Map
Assess career exposure and explore transition paths and learning options
Popular tool
AI & Data Bootcamps
Build your skills through structured courses and hands-on projects
Popular courses
1:1 Career Coaching
Work with an experienced mentor on your resume and interview preparation
Career coaching
Custom Corporate Training
AI training tailored to your team
Business services
Popular tags
Vibe CodingAI codingCursorClaudeJob searchPromptFrontend developmentBackend development
Subscribe to updates

Receive AI learning resources, technical tutorials and career advice by email.

We respect your privacy and do not send spam.