callback-array-from-length.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Callback invocation family (docs/analysis.md), the motivating
  2. // script: a fan-out written as `Array.from({ length: TOTAL }, (_, i) => agent(...).ask(...))`.
  3. // The mapper is a per-element callback per the registry, so its body is a `fanout` region
  4. // INSIDE phase#1 (not a detached body swept to the end under `unphased`), the worker lane
  5. // carries `within=fan-out#1`, and the summarizer's ask follows the join. Cardinality is
  6. // absent: `{ length: TOTAL }` is not an array literal (the card renders as `many`).
  7. interface Item {
  8. /** 该 worker 的编号。 */
  9. id: number;
  10. /** 一句话:关于数字 id 的一个有趣数学事实。 */
  11. fact: string;
  12. /** worker 自评的趣味程度 1-5。 */
  13. funScore: number;
  14. }
  15. interface WorkflowReport {
  16. /** 两三句话回答用户问了什么。 */
  17. conclusion: string;
  18. /** 全部 50 个 worker 的产物。 */
  19. items: Item[];
  20. /** 本次运行检查了什么、怎么检查的。 */
  21. verified: string[];
  22. /** 没有覆盖什么、为什么。 */
  23. notCovered: string[];
  24. }
  25. phase("并发发起 50 个独立 worker");
  26. const TOTAL = 50;
  27. log(`fan-out: ${TOTAL} 个独立 worker,一次性全部发出`);
  28. const items = await Promise.all(
  29. Array.from({ length: TOTAL }, (_, i) =>
  30. agent(`worker-${i}`, {
  31. system: "你是并行压测中的一个微型 worker。只回答分配给你的那一个数字,不要展开多余的上下文。",
  32. }).ask<Item>(
  33. `给出关于数字 ${i} 的一个有趣数学事实(一句话),并给它 1-5 的趣味评分。数字本身也要放进返回的 id 字段。`,
  34. ),
  35. ),
  36. );
  37. phase("汇总 50 个 worker 的产物");
  38. const summary = await agent("summarizer", {
  39. system: "你汇总并行 worker 的结果,只输出简洁的中文摘要。",
  40. }).ask<string>(
  41. `以下是 ${TOTAL} 个并行 worker 各自返回的数字事实(JSON 数组)。写 2-3 句总结:覆盖了哪些数字、平均趣味评分大约多少、最有意思的几条是什么。\n${JSON.stringify(items)}`,
  42. );
  43. const avg = items.reduce((s, it) => s + (it.funScore || 0), 0) / Math.max(items.length, 1);
  44. const result: WorkflowReport = {
  45. conclusion: `50 个 worker 全部并发完成,平均趣味评分 ${avg.toFixed(1)}。汇总者点评:${summary}`,
  46. items,
  47. verified: [`全部 ${items.length}/${TOTAL} 个 worker 都返回了带 id、fact、funScore 的产物`],
  48. notCovered: ["这是纯并行度演示,worker 结果未做独立复核"],
  49. };
  50. return result;