from __future__ import annotations import argparse import json import os import re import time from concurrent.futures import ThreadPoolExecutor, as_completed from dataclasses import asdict, dataclass from pathlib import Path from threading import Lock from typing import Any, Callable from jsonschema import Draft202012Validator from openai import OpenAI MODEL = os.getenv("DEEPSEEK_MODEL", "deepseek-chat") BASE_URL = os.getenv("DEEPSEEK_BASE_URL", "https://api.deepseek.com") DEFAULT_MAX_WORKERS = 3 MAX_SUBTASKS = 4 PLAN_SCHEMA: dict[str, Any] = { "type": "object", "properties": { "analysis": {"type": "string", "minLength": 20, "maxLength": 1200}, "tasks": { "type": "array", "minItems": 2, "maxItems": MAX_SUBTASKS, "items": { "type": "object", "properties": { "id": {"type": "string", "pattern": "^W[1-4]$"}, "type": {"type": "string", "minLength": 2, "maxLength": 40}, "description": {"type": "string", "minLength": 20, "maxLength": 500}, "deliverable": {"type": "string", "minLength": 10, "maxLength": 300}, }, "required": ["id", "type", "description", "deliverable"], "additionalProperties": False, }, }, }, "required": ["analysis", "tasks"], "additionalProperties": False, } WORKER_SCHEMA: dict[str, Any] = { "type": "object", "properties": { "worker_id": {"type": "string", "pattern": "^W[1-4]$"}, "title": {"type": "string", "minLength": 4, "maxLength": 100}, "findings": { "type": "array", "minItems": 2, "maxItems": 6, "items": {"type": "string", "minLength": 12, "maxLength": 500}, }, "recommendations": { "type": "array", "minItems": 2, "maxItems": 6, "items": {"type": "string", "minLength": 12, "maxLength": 500}, }, "risks": { "type": "array", "minItems": 1, "maxItems": 6, "items": {"type": "string", "minLength": 8, "maxLength": 400}, }, }, "required": ["worker_id", "title", "findings", "recommendations", "risks"], "additionalProperties": False, } SYNTHESIS_SCHEMA: dict[str, Any] = { "type": "object", "properties": { "title": {"type": "string", "minLength": 4, "maxLength": 120}, "executive_summary": {"type": "string", "minLength": 40, "maxLength": 1200}, "integrated_recommendations": { "type": "array", "minItems": 3, "maxItems": 10, "items": {"type": "string", "minLength": 12, "maxLength": 500}, }, "risk_controls": { "type": "array", "minItems": 2, "maxItems": 10, "items": {"type": "string", "minLength": 12, "maxLength": 500}, }, "source_workers": { "type": "array", "minItems": 2, "maxItems": MAX_SUBTASKS, "uniqueItems": True, "items": {"type": "string", "pattern": "^W[1-4]$"}, }, }, "required": [ "title", "executive_summary", "integrated_recommendations", "risk_controls", "source_workers", ], "additionalProperties": False, } @dataclass class Usage: prompt_tokens: int = 0 completion_tokens: int = 0 total_tokens: int = 0 def add(self, response_usage: Any) -> None: if response_usage is None: return self.prompt_tokens += int(response_usage.prompt_tokens or 0) self.completion_tokens += int(response_usage.completion_tokens or 0) self.total_tokens += int(response_usage.total_tokens or 0) def merge(self, other: "Usage") -> None: self.prompt_tokens += other.prompt_tokens self.completion_tokens += other.completion_tokens self.total_tokens += other.total_tokens def _schema_error(schema: dict[str, Any], value: Any, label: str) -> None: errors = sorted( Draft202012Validator(schema).iter_errors(value), key=lambda item: list(item.absolute_path), ) if not errors: return error = errors[0] location = ".".join(str(part) for part in error.absolute_path) or label raise ValueError(f"{label}结构不合法:{location}: {error.message}") def validate_plan(plan: dict[str, Any]) -> dict[str, Any]: """校验编排计划,并拒绝重复编号或重复职责。""" _schema_error(PLAN_SCHEMA, plan, "plan") task_ids = [task["id"] for task in plan["tasks"]] task_types = [task["type"].strip().casefold() for task in plan["tasks"]] if len(task_ids) != len(set(task_ids)): raise ValueError("plan结构不合法:工作器编号重复") if len(task_types) != len(set(task_types)): raise ValueError("plan结构不合法:工作器职责重复") return plan def validate_worker_result(result: dict[str, Any], expected_id: str) -> dict[str, Any]: """校验工作器结果,并确保模型没有冒用其他工作器编号。""" _schema_error(WORKER_SCHEMA, result, "worker_result") if result["worker_id"] != expected_id: raise ValueError( f"worker_result结构不合法:期待{expected_id},实际为{result['worker_id']}" ) return result def validate_synthesis( synthesis: dict[str, Any], expected_worker_ids: list[str] ) -> dict[str, Any]: """确保聚合结果明确覆盖每个成功工作器。""" _schema_error(SYNTHESIS_SCHEMA, synthesis, "synthesis") expected = set(expected_worker_ids) actual = set(synthesis["source_workers"]) if actual != expected: missing = sorted(expected - actual) extra = sorted(actual - expected) raise ValueError(f"synthesis覆盖不完整:缺少{missing},多出{extra}") return synthesis def create_client() -> OpenAI: """每个并发线程创建独立客户端,密钥只从环境变量读取。""" api_key = os.getenv("DEEPSEEK_API_KEY") if not api_key: raise RuntimeError("未设置 DEEPSEEK_API_KEY 环境变量") return OpenAI( api_key=api_key, base_url=BASE_URL, timeout=60.0, max_retries=1, ) def call_json( system_prompt: str, user_payload: dict[str, Any], schema: dict[str, Any], label: str, max_tokens: int = 1600, ) -> tuple[dict[str, Any], Usage]: """调用DeepSeek JSON模式,并在返回后执行本地Schema校验。""" client = create_client() response = client.chat.completions.create( model=MODEL, messages=[ {"role": "system", "content": system_prompt}, { "role": "user", "content": json.dumps(user_payload, ensure_ascii=False), }, ], response_format={"type": "json_object"}, temperature=0, max_tokens=max_tokens, ) content = response.choices[0].message.content or "" try: value = json.loads(content) except json.JSONDecodeError as exc: raise ValueError(f"{label}没有返回合法JSON:{exc}") from exc _schema_error(schema, value, label) usage = Usage() usage.add(response.usage) return value, usage def build_plan(task: str, context: dict[str, Any]) -> tuple[dict[str, Any], Usage]: """由编排器按任务内容动态决定需要哪些专业工作器。""" system_prompt = """ 你是企业任务编排器。请把用户目标拆成2至4个互补、可并行、没有先后依赖的专业子任务。 每个子任务必须有不同职责,合起来应覆盖用户目标;不要直接完成最终答案。 只输出JSON对象,字段必须严格符合以下约定: analysis为拆解理由;tasks为数组;每项包含id、type、description、deliverable。 id按W1、W2、W3、W4连续编号,不得重复。禁止输出Markdown。 """.strip() plan, usage = call_json( system_prompt, {"task": task, "context": context}, PLAN_SCHEMA, "plan", max_tokens=1200, ) return validate_plan(plan), usage def execute_worker( original_task: str, context: dict[str, Any], subtask: dict[str, Any], ) -> tuple[dict[str, Any], Usage]: """执行一个专业子任务,返回可聚合的结构化结果。""" expected_id = subtask["id"] system_prompt = f""" 你是一个受控的专业工作器,只处理分配给你的子任务,不扩展职责边界。 结论必须结合总目标、业务上下文和交付要求,给出具体可执行内容。 只输出JSON对象,形状必须是: {{"worker_id":"{expected_id}","title":"标题","findings":["发现1","发现2"],"recommendations":["建议1","建议2"],"risks":["风险1"]}} findings和recommendations各2至6个字符串,risks为1至6个字符串;数组中不能放对象。 worker_id必须是{expected_id};禁止输出Markdown、嵌套对象和额外字段。 """.strip() result, usage = call_json( system_prompt, { "original_task": original_task, "context": context, "assigned_subtask": subtask, }, WORKER_SCHEMA, f"worker_{subtask['id']}", max_tokens=1800, ) return validate_worker_result(result, subtask["id"]), usage WorkerCallable = Callable[ [str, dict[str, Any], dict[str, Any]], tuple[dict[str, Any], Usage], ] def run_workers( original_task: str, context: dict[str, Any], subtasks: list[dict[str, Any]], max_workers: int = DEFAULT_MAX_WORKERS, worker_callable: WorkerCallable = execute_worker, ) -> tuple[list[dict[str, Any]], list[dict[str, Any]], Usage, dict[str, Any]]: """并行执行子任务;单个失败会被记录,不会丢失其他成功结果。""" if not subtasks: raise ValueError("没有可执行的子任务") pool_size = max(1, min(max_workers, len(subtasks), MAX_SUBTASKS)) successes: list[dict[str, Any]] = [] failures: list[dict[str, Any]] = [] timings: list[dict[str, Any]] = [] total_usage = Usage() usage_lock = Lock() batch_started = time.perf_counter() def invoke(subtask: dict[str, Any]) -> tuple[dict[str, Any], Usage, dict[str, Any]]: started = time.perf_counter() result, usage = worker_callable(original_task, context, subtask) ended = time.perf_counter() timing = { "worker_id": subtask["id"], "started_offset_seconds": round(started - batch_started, 3), "ended_offset_seconds": round(ended - batch_started, 3), "duration_seconds": round(ended - started, 3), } return result, usage, timing with ThreadPoolExecutor(max_workers=pool_size) as executor: future_map = {executor.submit(invoke, subtask): subtask for subtask in subtasks} for future in as_completed(future_map): subtask = future_map[future] try: result, usage, timing = future.result() successes.append(result) timings.append(timing) with usage_lock: total_usage.merge(usage) except Exception as exc: # 单个工作器失败不取消其他工作器 failures.append( { "worker_id": subtask["id"], "error_type": type(exc).__name__, "message": str(exc), } ) successes.sort(key=lambda item: item["worker_id"]) failures.sort(key=lambda item: item["worker_id"]) timings.sort(key=lambda item: item["worker_id"]) timing_summary = { "pool_size": pool_size, "wall_seconds": round(time.perf_counter() - batch_started, 3), "workers": timings, } return successes, failures, total_usage, timing_summary def synthesize( task: str, context: dict[str, Any], worker_results: list[dict[str, Any]], ) -> tuple[dict[str, Any], Usage]: """聚合成功工作器结果,并强制保留来源编号。""" if len(worker_results) < 2: raise RuntimeError("成功工作器少于2个,拒绝生成缺乏交叉视角的最终方案") expected_ids = [item["worker_id"] for item in worker_results] system_prompt = """ 你是结果聚合器。请合并所有专业工作器的发现,去除重复和冲突,形成面向决策者的统一方案。 不得遗漏任何输入工作器;source_workers必须逐项列出全部worker_id,不能增加不存在的编号。 只输出JSON对象,包含title、executive_summary、integrated_recommendations、risk_controls、source_workers。 integrated_recommendations必须是3至10个字符串,risk_controls必须是2至10个字符串,source_workers必须是字符串数组。 禁止输出Markdown和额外字段。 """.strip() synthesis, usage = call_json( system_prompt, {"task": task, "context": context, "worker_results": worker_results}, SYNTHESIS_SCHEMA, "synthesis", max_tokens=2000, ) return validate_synthesis(synthesis, expected_ids), usage def process_task( task: str, context: dict[str, Any] | None = None, max_workers: int = DEFAULT_MAX_WORKERS, ) -> dict[str, Any]: """执行编排、并行工作和结果聚合的完整闭环。""" task = task.strip() if len(task) < 10: raise ValueError("任务描述至少需要10个字符") context = context or {} started = time.perf_counter() plan, plan_usage = build_plan(task, context) worker_results, worker_failures, worker_usage, parallel_timing = run_workers( task, context, plan["tasks"], max_workers=max_workers, ) final, synthesis_usage = synthesize(task, context, worker_results) total_usage = Usage() for usage in (plan_usage, worker_usage, synthesis_usage): total_usage.merge(usage) return { "task": task, "model": MODEL, "plan": plan, "worker_results": worker_results, "worker_failures": worker_failures, "final": final, "timing": { "total_seconds": round(time.perf_counter() - started, 3), "parallel_stage": parallel_timing, }, "usage": asdict(total_usage), } def load_context(path: str | None) -> dict[str, Any]: if not path: return {} value = json.loads(Path(path).read_text(encoding="utf-8")) if not isinstance(value, dict): raise ValueError("上下文文件必须包含JSON对象") return value def main() -> None: parser = argparse.ArgumentParser(description="DeepSeek编排器-工作器示例") parser.add_argument("task", help="需要动态拆解的复杂任务") parser.add_argument("--context", help="JSON上下文文件") parser.add_argument("--output", default="orchestration-result.json", help="结果文件") parser.add_argument("--max-workers", type=int, default=DEFAULT_MAX_WORKERS) args = parser.parse_args() result = process_task( args.task, context=load_context(args.context), max_workers=args.max_workers, ) output_path = Path(args.output) output_path.write_text( json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8", ) print(json.dumps(result["final"], ensure_ascii=False, indent=2)) print(f"\n完整审计结果:{output_path.resolve()}") if __name__ == "__main__": main()