蓝色天空.知识 · 实践 · 创造
我的收藏
AI Agent(智能体) 教程目录 48章
课程介绍
AI Agent(智能体) / LEARN BY DOING

AI Agent 工作原理与命令行练习

在真实 Python 子进程中输入指令,核对路由、工具计算、结果回传和退出。

学完这一章,你能够

  • 在真实 Python 子进程中输入指令,核对路由、工具计算、结果回传和退出。

让工具返回可以核对的结果

任务执行一般经历接收输入、形成下一步、执行工具、读取结果、判断完成五个阶段。模型可以提出调用,控制程序负责检查并实际执行。读取表格、按字段汇总和保存图表需要相应工具,不能从模型生成文字推断文件已经写出。

例如,先从软件包信息源取得版本,再形成带版本的安装命令。拿到错误时可以在策略允许下重试,或报告没有可用结果。本站从自有离线快照读取一个固定版本,不查询最新版本也不执行安装。实际对接应校验包名、索引来源和结果时效。

把参数检查与运算分开

报价工具接收 JSON 对象,先核对字段和类型,再按单价乘数量减优惠。本站以分为单位计算,1200 分乘 4 再减 350 分,得到 4450 分。比较 89 元乘 6 减 30 元时,同一工具得到 504 元。金额的显示由调用方处理。布尔值和超过小计的优惠都会被拒绝。

命令行算术接受两个十进制数和一个加减乘除运算符,用全串匹配限定输入,拒绝多步表达式、尾随文本、函数调用和零除。小数以 Decimal 计算,除法在有限精度下求值。需要扩展到更复杂的算式时,可以先用 AST 解析,再显式检查每类节点和资源上限,避免把任意用户字符串交给 eval。

读真实输入,记录本轮状态

命令行从标准输入读取一行、去除首尾空白并识别任务。weather 查询固定数据,calc 调用计算器,也可直接输入符合语法的算式。未知指令返回用法,未知城市返回明确结果。空行跳过,输入 quit、exit 或退出命令结束,输入关闭时也可结束。

程序执行后按顺序保存用户输入和工具结果,并在退出时显示本轮记录。保存历史本身不会让规则理解“再乘二”这样的指代。若要续接,需要保存带类型的任务状态或授权对话,并定义恢复、过期和删除规则。本站使用新子进程验证状态不跨会话串用。

从固定规则过渡到模型工具调用

本章用显式规则教学。改为模型驱动时,将任务和工具说明发给支持调用的模型,由它提出工具名与参数;控制器验证权限、类型与业务条件,执行允许的工具并回传结果,再由下一轮判断是否继续。对循环设步数和时间上限,写入类操作要能核对副作用。

反应式、目标导向、效用型、学习型和多 Agent 描述的是不同决策或组织方式,可能重叠。初次开发可以从原生函数与数据结构开始,系统变复杂时再选状态编排、检索或多角色框架。ReAct 只是一种利用观察来推进操作的模式。

执行系统的组成

组成部分用途
模型(LLM)根据任务与上下文提出候选回答或调用。在本章用可重复规则示范决策接口。
工具(Tools)查询数据或执行操作,把结果交回控制器。
状态与记忆(State / Memory)保存本次输入、工具输出及需要的中间状态。跨会话需要持久存储。
执行控制(Agent Runtime)调度已允许的工具,记录结果、处理错误并结束循环。

决策方式与组织结构

类型特点
反应式 Agent(Reactive Agent)依据当前信号和规则选择操作。
目标导向 Agent(Goal-based Agent)从完成条件反推所需步骤,依据工具反馈推进。
效用型 Agent(Utility-based Agent)用目标函数比较行动,例如估算成本和耗时再选。
学习型 Agent(Learning Agent)根据经验更新决策策略;持续保存日志不能单独证明策略已经学习。
多智能体系统(Multi-Agent)由多个执行者分工和交换结果,各自仍可采用不同的决策机制。

开发入口

方式重点
原生 Python + LLM API直接实现调用校验、反馈、执行预算和任务状态,便于隔离排查。
LangChain / LangGraph前者提供模型、工具和 Agent 组件,后者侧重图式工作流、状态与控制。
LlamaIndex可组织文档、索引、检索及 Agent 相关组件,常见于知识型应用。
Microsoft Agent Framework可组织 Agent 和工作流,并对接持久状态、工具及人工审批。

在终端执行天气、算术和退出命令

含完整源码 · 151 行
展开查看收起
python
"""A bounded command-line loop using tools, structured requests, and actual stdin."""
from decimal import Decimal, localcontext
import ast
import json
import operator
import re
import sys

from lab_tools import run_exercise

NUMBER = r"-?[0-9]{1,9}(?:\.[0-9]{1,4})?"
EXPRESSION = re.compile(rf"({NUMBER})\s*([+*/-])\s*({NUMBER})")
OPERATORS = {"+":operator.add, "-":operator.sub, "*":operator.mul, "/":operator.truediv}
WEATHER = {"Harbor":"rain", "Hill":"clear", "Grove":"cloudy"}
PINNED_PACKAGE = {"seaframe":"2.7.1"}


def compute(expression):
    match = EXPRESSION.fullmatch(expression.strip())
    if not match:
        raise ValueError("expected two decimal numbers and one operator")
    left, symbol, right = match.groups()
    if symbol == "/" and not Decimal(right):
        raise ValueError("division by zero")
    with localcontext() as ctx:
        ctx.prec = 28
        return format(OPERATORS[symbol](Decimal(left),Decimal(right)).normalize(),"f")


def total(price_cents,quantity,coupon_cents):
    values = (price_cents,quantity,coupon_cents)
    if any(type(value) is not int or value < 0 for value in values):
        raise ValueError("expected nonnegative integer fields")
    if coupon_cents > price_cents * quantity:
        raise ValueError("coupon exceeds subtotal")
    return price_cents * quantity - coupon_cents


def quote(raw):
    args = json.loads(raw)
    if not isinstance(args,dict) or set(args) != {"price_cents","quantity","coupon_cents"}:
        raise ValueError("unexpected fields")
    return total(**args)


def select(message):
    if message.casefold() in {"exit","quit","退出"}:
        return "quit",""
    action, _, argument = message.partition(" ")
    if action.casefold() in {"weather","calc","package"}:
        return action.casefold(),argument.strip()
    if EXPRESSION.fullmatch(message):
        return "calc",message
    return "chat",message


def use_tool(action, argument):
    if action == "weather":
        result = WEATHER.get(argument)
        return f"fixture weather: {result}" if result else "unknown fixture city"
    if action == "calc":
        try:
            return compute(argument)
        except ValueError as error:
            return f"error: {error}"
    if action == "package":
        release = PINNED_PACKAGE.get(argument)
        return f"snapshot only: python -m pip install {argument}=={release}" if release else "no release in snapshot"
    return "supported commands: weather, calc, package, quit"


def cli():
    history = []
    reason = "eof"
    while True:
        try:
            message = input("Task> ").strip()
        except EOFError:
            print()
            break
        except KeyboardInterrupt:
            reason = "interrupt"
            print()
            break
        if not message:
            continue
        action, argument = select(message)
        if action == "quit":
            reason = "quit"
            print()
            break
        output = use_tool(action,argument)
        print(output)
        history.extend(({"role":"user","text":message},{"role":"assistant","text":output}))
    print("SESSION " + json.dumps({"reason":reason,"history":history},ensure_ascii=True))


def exercise(checks, _):
    expect = checks.expect
    request = '{"price_cents":1200,"quantity":4,"coupon_cents":350}'
    original_values = '{"price_cents":8900,"quantity":6,"coupon_cents":3000}'
    expect("work_quote",[request,original_values],"Decode, validate and compute both quotes in integer cents",
           [4450,50400],[quote(request),quote(original_values)])
    bad_quotes = ('{"price_cents":true,"quantity":4,"coupon_cents":0}',
                  '{"price_cents":1200,"quantity":1,"coupon_cents":1300}',
                  '{"price_cents":1200,"quantity":4,"coupon_cents":10,"send":true}')
    rejected = []
    for raw in bad_quotes:
        try:
            quote(raw)
        except ValueError:
            rejected.append(raw)
    expect("work_quote_validation",list(bad_quotes),"Reject booleans, excess discounts and unknown arguments",
           list(bad_quotes),rejected)
    inputs = ["-1.5 + 3.25","13 - 8","7 * -2","21 / 4"]
    expect("work_operators",inputs,"Use only the four allowed operations",["1.75","5","-14","5.25"],
           [compute(value) for value in inputs])
    rejects = ["2 / 0","1+2+3","3 + 4 trailing","print(9)","1e6+2"]
    errors = []
    for expression in rejects:
        try:
            compute(expression)
        except ValueError as error:
            errors.append(str(error))
    expect("work_calculator_rejects",rejects,"Reject zero division and input outside the entire grammar",
           ["division by zero"]+["expected two decimal numbers and one operator"]*4,errors)
    samples = ["weather Hill","calc 8*2","3/2","package seaframe","hello","EXIT"]
    expect("work_routing",samples,"Route only explicit commands and valid arithmetic expressions",
           ["weather","calc","calc","package","chat","quit"],[select(item)[0] for item in samples])
    expect("work_fixture_weather",["Harbor","Outside"],"Read local weather and check unknown-city behavior",
           ["fixture weather: rain","unknown fixture city"],
           [use_tool("weather",city) for city in ("Harbor","Outside")])
    expect("work_release_snapshot",["seaframe","unknown"],"Read a local package pin and format the installation instruction",
           ["snapshot only: python -m pip install seaframe==2.7.1","no release in snapshot"],
           [use_tool("package",name) for name in ("seaframe","unknown")])
    trees = [ast.parse(code,mode="eval").body for code in ("2+3","print(9)")]
    expect("work_ast_boundary",["2+3","print(9)"],"Parse only and distinguish BinaryOp and a function call",
           ["BinOp","Call"],[type(tree).__name__ for tree in trees])
    candidates = [{"price":25,"minutes":12},{"price":21,"minutes":25}]
    chosen = min(candidates,key=lambda item:item["price"]+item["minutes"])
    expect("work_utility",candidates,"Choose the lower cost plus latency score",candidates[0],chosen)


if __name__ == "__main__":
    if sys.argv[1:]==["--checks"]:
        run_exercise(exercise)
    elif not sys.argv[1:]:
        cli()
    else:
        raise SystemExit("usage: work_loop.py [--checks]")
输入 weather Hill 返回本地晴天数据;calc 9 / 2 返回 4.5。输入 quit 后显示有序会话,独立进程遇到 EOF 或 Windows 伪终端 Ctrl+C 也正常结束。超额优惠和不合规算式被拒绝。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

解压后运行

README 列出三个命令及可观察结果。

下载本章实验包 (mbskycom202612a3072.zip) ↓ 查看运行说明 ↗

本章附件与实例包

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

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

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

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

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

为可重试工具设尝试次数,达到上限时返回明确的失败状态并保留调用记录。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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