model.ts 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. import { createServer } from "node:http";
  2. import { copyFile, writeFile } from "node:fs/promises";
  3. import { join, resolve } from "node:path";
  4. import { Events } from "./agent.js";
  5. // 确定性本地模型只返回预置工具调用;授权、认领、执行、取消仍走真实 Agent。
  6. export async function startModel(root: string, cli: string) {
  7. const requests = new Events<any>();
  8. const plans: { key: string; delayed: boolean; status?: number; finishReason?: string }[] = [];
  9. const aborted = new Events<string>();
  10. const releases = new Map<string, () => void>();
  11. const server = createServer(async (req, res) => {
  12. const chunks: Buffer[] = [];
  13. for await (const chunk of req) chunks.push(chunk);
  14. const body = JSON.parse(Buffer.concat(chunks).toString());
  15. const plan = plans.shift();
  16. const tool = body.tools?.find((t: any) => t.function?.name.endsWith("__page_edit"));
  17. if (!body.stream) {
  18. const reply = () => {
  19. releases.delete(plan?.key ?? "");
  20. if (res.destroyed) return;
  21. if (plan?.status) {
  22. res.writeHead(plan.status, { "Content-Type": "application/json" });
  23. res.end(
  24. JSON.stringify({
  25. error: {
  26. message: "fixture provider denied",
  27. type: "authentication_error",
  28. code: "invalid_api_key",
  29. },
  30. }),
  31. );
  32. return;
  33. }
  34. res.writeHead(200, { "Content-Type": "application/json" });
  35. res.end(
  36. JSON.stringify({
  37. id: "sampling-fixture",
  38. object: "chat.completion",
  39. created: 1,
  40. model: "gpt-4o",
  41. choices: [
  42. {
  43. index: 0,
  44. message: { role: "assistant", content: `answer:${plan?.key ?? "sample"}` },
  45. finish_reason: plan?.finishReason ?? "stop",
  46. },
  47. ],
  48. usage: { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 },
  49. }),
  50. );
  51. };
  52. res.on("close", () => {
  53. if (!res.writableEnded) aborted.emit(plan?.key ?? "sample");
  54. releases.delete(plan?.key ?? "");
  55. });
  56. if (plan?.delayed) releases.set(plan.key, reply);
  57. requests.emit({ body, plan, tool, url: req.url });
  58. if (!plan?.delayed) reply();
  59. return;
  60. }
  61. requests.emit({ body, plan, tool, url: req.url });
  62. const delta =
  63. plan && tool
  64. ? {
  65. role: "assistant",
  66. tool_calls: [
  67. {
  68. index: 0,
  69. id: `call_${plan.key}`,
  70. type: "function",
  71. function: { name: tool.function.name, arguments: JSON.stringify(plan) },
  72. },
  73. ],
  74. }
  75. : { role: "assistant", content: "fixture complete" };
  76. const base = {
  77. id: "fixture-completion",
  78. object: "chat.completion.chunk",
  79. created: 1,
  80. model: "gpt-4o",
  81. };
  82. res.writeHead(200, { "Content-Type": "text/event-stream" });
  83. res.write(
  84. `data: ${JSON.stringify({ ...base, choices: [{ index: 0, delta, finish_reason: null }] })}\n\n`,
  85. );
  86. res.write(
  87. `data: ${JSON.stringify({ ...base, choices: [{ index: 0, delta: {}, finish_reason: plan && tool ? "tool_calls" : "stop" }], usage: { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 } })}\n\n`,
  88. );
  89. res.end("data: [DONE]\n\n");
  90. });
  91. await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
  92. const port = (server.address() as { port: number }).port;
  93. const builtin = join(root, "fixture-builtin.json"),
  94. personal = join(root, "fixture-personal.json");
  95. await copyFile(resolve(cli, "../../../../../../config/provider/zcode-builtin.json"), builtin);
  96. await writeFile(
  97. personal,
  98. JSON.stringify({
  99. schemaVersion: 1,
  100. config: {
  101. providerConfigRules: {
  102. providerRules: [
  103. {
  104. providerId: "fixture-local",
  105. config: {
  106. group: "standard-personal",
  107. access: { type: "api-key", apiKey: "fixture-only" },
  108. api: { type: "openai-chat-completions", baseUrl: `http://127.0.0.1:${port}/v1` },
  109. personalModelIds: ["gpt-4o", "gpt-4o-mini"],
  110. },
  111. },
  112. ],
  113. },
  114. modelConfigRules: {
  115. providerModelRules: ["gpt-4o", "gpt-4o-mini"].map((modelId) => ({
  116. providerId: "fixture-local",
  117. modelId,
  118. config: { properties: { inputFormat: { supportsImage: true } } },
  119. })),
  120. manualProviderModelRules: [],
  121. },
  122. defaultModelSelection: {
  123. providerId: "fixture-local",
  124. modelId: "gpt-4o",
  125. options: { reasoningLevel: "disabled" },
  126. },
  127. },
  128. }),
  129. );
  130. return {
  131. requests,
  132. plans,
  133. aborted,
  134. release: (key: string) => releases.get(key)?.(),
  135. env: {
  136. ZCODE_BUILTIN_PROVIDER_CONFIG_FILE: builtin,
  137. ZCODE_PERSONAL_PROVIDER_CONFIG_FILE: personal,
  138. },
  139. selection: {
  140. providerId: "fixture-local",
  141. modelId: "gpt-4o",
  142. options: { reasoningLevel: "disabled" },
  143. },
  144. close: () =>
  145. new Promise<void>((resolve) => {
  146. server.closeAllConnections();
  147. server.close(() => resolve());
  148. }),
  149. };
  150. }