"""An offline command-line chat project with an explicit response contract."""
from argparse import ArgumentParser
from dataclasses import dataclass
from datetime import datetime, timezone
import json
from math import isfinite
from pathlib import Path
MODEL_RATES = {"lab-small": (2, 8), "lab-large": (4, 16)}
HELP = "/help /stats /save /clear /model <id> /temp <value> /system <text> /quit"
@dataclass(frozen=True)
class Reply:
pieces: tuple[str, ...]
input_tokens: int
output_tokens: int
complete: bool = True
def fixture_provider(model, temperature, messages):
last = messages[-1]["content"]
if last == "模拟中断":
return Reply(("尚未完成",), 20, 5, complete=False)
previous = sum(row["role"] == "assistant" for row in messages)
return Reply((f"{model} · {temperature:g} · ", f"历史 {previous} 轮 · {last}"), 20, 5)
class Chat:
def __init__(self, model="lab-small", system="依据档案记录回答", max_turns=2, stream=True):
self.model = model
self.system = system
self.max_turns = max_turns
self.stream = stream
self.temperature = 0.2
self.clear()
def clear(self):
self.turns = []
self.input_tokens = self.output_tokens = self.cost_microusd = 0
def messages(self, prompt):
rows = [{"role": "system", "content": self.system}]
for question, answer in self.turns:
rows.extend([{"role": "user", "content": question}, {"role": "assistant", "content": answer}])
return [*rows, {"role": "user", "content": prompt}]
def chat(self, prompt):
reply = fixture_provider(self.model, self.temperature, self.messages(prompt))
if self.stream:
print("助手:", end="", flush=True)
for text in reply.pieces:
print(text, end="", flush=True)
print()
if not reply.complete:
print("回包中断,未记入历史或用量。")
return
answer = "".join(reply.pieces)
if not self.stream:
print("助手:" + answer)
self.turns = [*self.turns, (prompt, answer)][-self.max_turns:] if self.max_turns else []
self.input_tokens += reply.input_tokens
self.output_tokens += reply.output_tokens
input_rate, output_rate = MODEL_RATES[self.model]
self.cost_microusd += reply.input_tokens * input_rate + reply.output_tokens * output_rate
def stats(self):
print(f"保留 {len(self.turns)} 轮;输入 {self.input_tokens};输出 {self.output_tokens};"
f"模拟费用 {self.cost_microusd} 微美元。")
def save(self, destination):
payload = dict(model=self.model, temperature=self.temperature, system=self.system,
turns=self.turns, input_tokens=self.input_tokens, output_tokens=self.output_tokens,
simulated_cost_microusd=self.cost_microusd, saved_at=datetime.now(timezone.utc).isoformat())
try:
with destination.open("x", encoding="utf8") as output:
json.dump(payload, output, ensure_ascii=False, indent=2)
output.write("\n")
except FileExistsError:
print("已有记录,保留原文件。")
else:
print("已保存会话。")
def command(self, line, destination):
name, _, argument = line.partition(" ")
argument = argument.strip()
if name in {"/quit", "/exit", "/q"} and not argument:
return False
if name == "/help" and not argument:
print(HELP)
elif name == "/stats" and not argument:
self.stats()
elif name == "/save" and not argument:
self.save(destination)
elif name == "/clear" and not argument:
self.clear()
print("历史已清除。")
elif name == "/model" and argument in MODEL_RATES:
self.model = argument
print("模型已切换为 " + argument)
elif name == "/temp":
try:
value = float(argument)
except ValueError:
value = float("nan")
if isfinite(value) and 0 <= value <= 2:
self.temperature = value
print(f"采样温度 {value:g}")
else:
print("模拟温度须是 0 到 2 之间的数。")
elif name == "/system" and argument:
self.system = argument
self.clear()
print("规则已更新,历史已清除。")
else:
print("未知命令或参数,输入 /help。")
return True
def load_config(path):
if path is None:
return {}
config = json.loads(path.read_bytes())
if not isinstance(config, dict) or not set(config) <= {"model", "system", "max_turns", "stream"}:
raise ValueError("配置只允许非秘密字段。")
if ("model" in config and (type(config["model"]) is not str or config["model"] not in MODEL_RATES)
or "system" in config and (type(config["system"]) is not str or not config["system"].strip())
or "max_turns" in config and (type(config["max_turns"]) is not int or not 0 <= config["max_turns"] <= 20)
or "stream" in config and type(config["stream"]) is not bool):
raise ValueError("配置字段类型或取值错误。")
return config
def main():
parser = ArgumentParser(description="只使用内置固定回包的聊天项目")
parser.add_argument("--config", type=Path)
parser.add_argument("--save", type=Path, default=Path("session.json"))
options = parser.parse_args()
try:
chat = Chat(**load_config(options.config))
except (OSError, ValueError) as error:
parser.error(str(error))
print("档案索引聊天练习。输入 /help 查看命令。")
while True:
try:
line = input("你:").strip()
except EOFError:
break
except KeyboardInterrupt:
print("\n输入 /quit 退出。")
continue
if line.startswith("/"):
if not chat.command(line, options.save):
break
elif line:
chat.chat(line)
print("再见。")
if __name__ == "__main__":
main()
本例需在 CPython 3.12.14,OpenAI SDK 3.46.0 / 3.48.0、Anthropic SDK 2.7.0、httpx2 2.16.0、Tenacity 9.1.4,固定回包。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:CPython 3.12.14,OpenAI SDK 3.46.0 / 3.48.0、Anthropic SDK 2.7.0、httpx2 2.16.0、Tenacity 9.1.4,固定回包。
入口文件:projects/ai-api-development/chat_cli.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
chat_cli.py,或下载右侧课程工程包。 - 确认本地已准备 CPython 3.12.14,OpenAI SDK 3.46.0 / 3.48.0、Anthropic SDK 2.7.0、httpx2 2.16.0、Tenacity 9.1.4,固定回包。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a4.zip
课程关联工程包(登记关联30章) · 含当前章节或实例 · mbskycom202612a5.zip