qna.ts 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. /**
  2. * Q&A extraction extension - extracts questions from assistant responses
  3. *
  4. * Demonstrates the "prompt generator" pattern:
  5. * 1. /qna command gets the last assistant message
  6. * 2. Shows a spinner while extracting (hides editor)
  7. * 3. Loads the result into the editor for user to fill in answers
  8. */
  9. import { complete, type UserMessage } from "@earendil-works/pi-ai";
  10. import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
  11. import { BorderedLoader } from "@earendil-works/pi-coding-agent";
  12. const SYSTEM_PROMPT = `You are a question extractor. Given text from a conversation, extract any questions that need answering and format them for the user to fill in.
  13. Output format:
  14. - List each question on its own line, prefixed with "Q: "
  15. - After each question, add a blank line for the answer prefixed with "A: "
  16. - If no questions are found, output "No questions found in the last message."
  17. Example output:
  18. Q: What is your preferred database?
  19. A:
  20. Q: Should we use TypeScript or JavaScript?
  21. A:
  22. Keep questions in the order they appeared. Be concise.`;
  23. export default function (pi: ExtensionAPI) {
  24. pi.registerCommand("qna", {
  25. description: "Extract questions from last assistant message into editor",
  26. handler: async (_args, ctx) => {
  27. if (ctx.mode !== "tui") {
  28. ctx.ui.notify("qna requires interactive mode", "error");
  29. return;
  30. }
  31. if (!ctx.model) {
  32. ctx.ui.notify("No model selected", "error");
  33. return;
  34. }
  35. // Find the last assistant message on the current branch
  36. const branch = ctx.sessionManager.getBranch();
  37. let lastAssistantText: string | undefined;
  38. for (let i = branch.length - 1; i >= 0; i--) {
  39. const entry = branch[i];
  40. if (entry.type === "message") {
  41. const msg = entry.message;
  42. if ("role" in msg && msg.role === "assistant") {
  43. if (msg.stopReason !== "stop") {
  44. ctx.ui.notify(`Last assistant message incomplete (${msg.stopReason})`, "error");
  45. return;
  46. }
  47. const textParts = msg.content
  48. .filter((c): c is { type: "text"; text: string } => c.type === "text")
  49. .map((c) => c.text);
  50. if (textParts.length > 0) {
  51. lastAssistantText = textParts.join("\n");
  52. break;
  53. }
  54. }
  55. }
  56. }
  57. if (!lastAssistantText) {
  58. ctx.ui.notify("No assistant messages found", "error");
  59. return;
  60. }
  61. // Run extraction with loader UI
  62. const result = await ctx.ui.custom<string | null>((tui, theme, _kb, done) => {
  63. const loader = new BorderedLoader(tui, theme, `Extracting questions using ${ctx.model!.id}...`);
  64. loader.onAbort = () => done(null);
  65. // Do the work
  66. const doExtract = async () => {
  67. const auth = await ctx.modelRegistry.getApiKeyAndHeaders(ctx.model!);
  68. if (!auth.ok || !auth.apiKey) {
  69. throw new Error(auth.ok ? `No API key for ${ctx.model!.provider}` : auth.error);
  70. }
  71. const userMessage: UserMessage = {
  72. role: "user",
  73. content: [{ type: "text", text: lastAssistantText! }],
  74. timestamp: Date.now(),
  75. };
  76. const response = await complete(
  77. ctx.model!,
  78. { systemPrompt: SYSTEM_PROMPT, messages: [userMessage] },
  79. { apiKey: auth.apiKey, headers: auth.headers, signal: loader.signal },
  80. );
  81. if (response.stopReason === "aborted") {
  82. return null;
  83. }
  84. return response.content
  85. .filter((c): c is { type: "text"; text: string } => c.type === "text")
  86. .map((c) => c.text)
  87. .join("\n");
  88. };
  89. doExtract()
  90. .then(done)
  91. .catch(() => done(null));
  92. return loader;
  93. });
  94. if (result === null) {
  95. ctx.ui.notify("Cancelled", "info");
  96. return;
  97. }
  98. ctx.ui.setEditorText(result);
  99. ctx.ui.notify("Questions loaded. Edit and submit when ready.", "info");
  100. },
  101. });
  102. }