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

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

PYTHONCPython 3.12,本机隔离数据;术语工作树练习使用 Gitwork_loop.py
work_loop.py151 行
"""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]")
本例需在 CPython 3.12,本机隔离数据;术语工作树练习使用 Git 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:CPython 3.12,本机隔离数据;术语工作树练习使用 Git

入口文件:projects/ai-agent-architecture/work_loop.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 work_loop.py,或下载右侧课程工程包。
  2. 确认本地已准备 CPython 3.12,本机隔离数据;术语工作树练习使用 Git。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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