蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

实跑 CrewAI 记录员、写作者与本地工具

PYTHONCPython 3.12,CrewAI 1.15.39;两期计数和 BaseLLM 返回由本站固定,工具与任务真实执行。crewai_handoff.py
crewai_handoff.py190 行
"""Run an offline research and writing crew using actual tasks, tools and Markdown."""
from contextlib import redirect_stdout
from decimal import Decimal, ROUND_HALF_UP
from importlib.metadata import version
from io import StringIO
import ipaddress
import json
import os
import socket
from threading import Barrier, get_ident
from unittest.mock import patch

from lab_tools import run_exercise


def exercise(checks,root):
    os.environ.update(CREWAI_STORAGE_DIR=str(root/"crew-data"),CREWAI_TRACING_ENABLED="false",
        CREWAI_DISABLE_TELEMETRY="true",OTEL_SDK_DISABLED="true",PYTHON_DOTENV_DISABLED="1")

    from crewai import Agent, Crew, Process, Task
    from crewai.llms.base_llm import BaseLLM
    from crewai.tools import tool
    from dotenv import dotenv_values, load_dotenv
    from pydantic import ValidationError

    events=[]
    catalogue={"dock":(80,100),"shed":(0,8)}
    @tool("read_counts")
    def read_counts(site: str) -> str:
        """Return the two training counts for one site."""
        before,after=catalogue[site]
        events.append(["read",site,before,after])
        return json.dumps({"before":before,"after":after},separators=(",",":"))

    @tool("calculate_growth")
    def calculate_growth(before: int, after: int) -> str:
        """Calculate percent growth from a positive baseline or report no baseline."""
        events.append(["calculate",before,after])
        if before==0:
            return "GROWTH=no_baseline"
        rate=(Decimal(after-before)*100/before).quantize(Decimal("0.1"),rounding=ROUND_HALF_UP)
        return f"GROWTH={rate}%"

    barrier=Barrier(2,timeout=10)
    worker_threads={}

    class FixtureModel(BaseLLM):
        def call(self,messages,tools=None,callbacks=None,available_functions=None,
                 from_task=None,from_agent=None,response_model=None):
            content=[messages] if isinstance(messages,str) else [str(m.get("content","")) for m in messages]
            text="\n".join(content)
            if from_task and from_task.description.startswith("Research "):
                site=from_task.description.split()[1].rstrip(".")
                observations=[line.removeprefix("Observation: ").strip()
                              for message in content for line in message.splitlines() if line.startswith("Observation: ")]
                if any(observed.startswith("GROWTH=") for observed in observations):
                    growth=next(observed for observed in reversed(observations) if observed.startswith("GROWTH="))
                    return "Final Answer: "+site+" "+growth
                if any(observed.startswith('{"before":') for observed in observations):
                    counts=next(observed for observed in reversed(observations) if observed.startswith('{"before":'))
                    return "Thought: Calculate from the measured values.\nAction: calculate_growth\nAction Input: "+counts
                return "Thought: Look up the sample first.\nAction: read_counts\nAction Input: "+json.dumps({"site":site})
            if from_task and from_task.description=="Write a brief from the supplied finding.":
                site,rate=next((site,rate) for site,rate in (("dock","25.0%"),("shed","no_baseline"))
                               if f"{site} GROWTH={rate}" in text)
                events.append(["handoff",site,rate])
                value=rate if rate!="no_baseline" else "无正数基期,增长率未定义"
                return f"Final Answer: # 站点 {site}\n\n增长率:{value}"
            if from_task and from_task.description in ("Count west bins.","Count east bins."):
                side=from_task.description.split()[1]
                worker_threads[side]=get_ident()
                barrier.wait()
                return "Final Answer: "+{"west":"west=12","east":"east=9"}[side]
            if from_task and from_task.description=="Merge the two counts.":
                assert "west=12" in text and "east=9" in text
                return "Final Answer: total=21"
            if from_task and from_task.description=="Confirm team initialization.":
                return "Final Answer: manager handled the fixture"
            raise AssertionError("unexpected task input")

    model=FixtureModel(model="mbsky-fixture")
    def make_agent(role,goal,tools=()):
        return Agent(role=role,goal=goal,backstory="Use only the local evidence supplied to this task.",
                     llm=model,tools=list(tools),allow_delegation=False,max_iter=5,verbose=False)
    researcher=make_agent("Recorder","Calculate growth from a two-period series",(read_counts,calculate_growth))
    writer=make_agent("Writer","Explain the confirmed growth or missing baseline")

    def sequential(site):
        facts=Task(description=f"Research {site}. Find the count and growth.",
                   expected_output="One site and checked growth result.",agent=researcher)
        brief=Task(description="Write a brief from the supplied finding.",
                   expected_output="One Markdown heading and the growth line.",agent=writer,context=[facts])
        crew=Crew(agents=[researcher,writer],tasks=[facts,brief],process=Process.sequential,
                  memory=False,cache=False,verbose=False,tracing=False)
        start=len(events)
        with redirect_stdout(StringIO()):
            result=crew.kickoff()
        finding,report=result.tasks_output
        assert not result.has_tool_failures and report.raw==result.raw
        path=root/(site+".md")
        with path.open("x",encoding="utf8",newline="\n") as target:
            target.write(result.raw+"\n")
        return [events[start:],finding.raw,path.read_text(encoding="utf8")],result

    socket_connect=socket.socket.connect
    def loopback_only(connection,address):
        if not (isinstance(address,tuple) and ipaddress.ip_address(address[0]).is_loopback):
            raise AssertionError("external network forbidden")
        return socket_connect(connection,address)
    with patch.object(socket.socket,"connect",new=loopback_only):
        normal,result=sequential("dock")
        empty,_=sequential("shed")
    checks.expect("crewai_two_tools",["dock",80,100],"Run two actual tools, pass the finding to the writer and reread Markdown",
        [[["read","dock",80,100],["calculate",80,100],["handoff","dock","25.0%"]],
         "dock GROWTH=25.0%","# 站点 dock\n\n增长率:25.0%\n"],normal)
    checks.expect("crewai_zero_baseline",["shed",0,8],"Pass a zero-baseline finding to the writer without dividing",
        [[["read","shed",0,8],["calculate",0,8],["handoff","shed","no_baseline"]],
         "shed GROWTH=no_baseline","# 站点 shed\n\n增长率:无正数基期,增长率未定义\n"],empty)
    checks.expect("crewai_result_contract","CrewOutput","Inspect the actual public result fields",
        ["CrewOutput","str","list","TaskOutput","UsageMetrics",True],
        [type(result).__name__,type(result.raw).__name__,type(result.tasks_output).__name__,
         type(result.tasks_output[0]).__name__,type(result.token_usage).__name__,
         result.usage_metrics==result.token_usage.model_dump()])

    def error_kind(process,agent,**options):
        job=Task(description="Confirm team initialization.",expected_output="A short line.",agent=agent)
        try:
            Crew(agents=[researcher],tasks=[job],process=process,cache=False,tracing=False,**options)
        except ValidationError as error:
            return error.errors()[0]["type"]
        raise AssertionError("missing condition accepted")

    checks.expect("crewai_validation",["sequential without task agent","hierarchical without manager",
        "manager repeated in worker list"],"Check real validation error identifiers",
        ["missing_agent_in_task","missing_manager_llm_or_manager_agent","manager_agent_in_agents"],
        [error_kind(Process.sequential,None),error_kind(Process.hierarchical,researcher),
         error_kind(Process.hierarchical,researcher,manager_agent=researcher)])

    try:
        Crew(agents=[researcher],tasks=[Task(description="Confirm team initialization.",
             expected_output="A short line.",agent=researcher)],verbose=2,tracing=False)
    except ValidationError as error:
        verbose_error=error.errors()[0]
        verbose_status=[list(verbose_error["loc"]),verbose_error["type"]]
    else:
        raise AssertionError("numeric log level accepted")
    checks.expect("crewai_verbose_contract",2,"Validate verbose as a boolean instead of a numeric log level",
        [["verbose"],"bool_parsing"],verbose_status)

    manager=make_agent("Manager","Handle the single fixture task")
    job=Task(description="Confirm team initialization.",expected_output="A short line.")
    group=Crew(agents=[researcher],tasks=[job],process=Process.hierarchical,manager_agent=manager,
               cache=False,memory=False,verbose=False,tracing=False)
    with patch.object(socket.socket,"connect",new=loopback_only),redirect_stdout(StringIO()):
        manager_result=group.kickoff()
    checks.expect("crewai_manager","explicit manager and unassigned task","Run the hierarchical executor with a fixed answer",
        ["hierarchical","manager handled the fixture"],[group.process.value,manager_result.raw])

    west_agent=make_agent("West recorder","Read the fixed west count")
    east_agent=make_agent("East recorder","Read the fixed east count")
    west=Task(description="Count west bins.",expected_output="One west count.",agent=west_agent,async_execution=True)
    east=Task(description="Count east bins.",expected_output="One east count.",agent=east_agent,async_execution=True)
    merge=Task(description="Merge the two counts.",expected_output="One total.",agent=writer,context=[west,east])
    parallel=Crew(agents=[west_agent,east_agent,writer],tasks=[west,east,merge],process=Process.sequential,
                  cache=False,memory=False,verbose=False,tracing=False)
    with patch.object(socket.socket,"connect",new=loopback_only),redirect_stdout(StringIO()):
        merged=parallel.kickoff()
    checks.expect("crewai_async_context",["west=12","east=9"],"Wait for two real asynchronous tasks at a barrier, then merge",
        [2,["west=12","east=9","total=21"]],
        [len(set(worker_threads.values())),[task.raw for task in merged.tasks_output]])

    env_file=root/"example.env"
    key="MBSKY_CREW_EXAMPLE_OPTION"
    env_file.write_text(key+"=sample-only\n",encoding="utf8")
    with patch.dict(os.environ,{"PYTHON_DOTENV_DISABLED":"0"}):
        os.environ.pop(key,None)
        assert load_dotenv(env_file,override=False)
        from_file=os.environ[key]
        os.environ[key]="explicit"
        load_dotenv(env_file,override=False)
        kept=os.environ[key]
    checks.expect("crewai_env_fixture",env_file.name,"Parse and load a non-secret fixture, then retain an explicit variable",
        ["sample-only","sample-only","explicit"],
        [dotenv_values(env_file)[key],from_file,kept])
    checks.expect("crewai_package","installed metadata","Read the real package version","1.15.39",version("crewai"))


if __name__=="__main__":
    run_exercise(exercise)
本例需在 CPython 3.12,CrewAI 1.15.39;两期计数和 BaseLLM 返回由本站固定,工具与任务真实执行。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:CPython 3.12,CrewAI 1.15.39;两期计数和 BaseLLM 返回由本站固定,工具与任务真实执行。

入口文件:projects/ai-agent-crewai/crewai_handoff.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 crewai_handoff.py,或下载右侧课程工程包。
  2. 确认本地已准备 CPython 3.12,CrewAI 1.15.39;两期计数和 BaseLLM 返回由本站固定,工具与任务真实执行。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:AI Agent(智能体)

课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a3073.zip

下载课程关联工程包:AI Agent(智能体)

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3076.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习