model.ts 5.7 KB

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