structured-output.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /**
  2. * Structured Output Tool
  3. *
  4. * Demonstrates `terminate: true` so the agent can end on a tool call
  5. * without paying for an extra follow-up LLM turn.
  6. */
  7. import { defineTool, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
  8. import { Text } from "@earendil-works/pi-tui";
  9. import { Type } from "typebox";
  10. interface StructuredOutputDetails {
  11. headline: string;
  12. summary: string;
  13. actionItems: string[];
  14. }
  15. const structuredOutputTool = defineTool({
  16. name: "structured_output",
  17. label: "Structured Output",
  18. description:
  19. "Return a final structured answer. Use this as your last action when the user asks for structured output or a machine-readable summary.",
  20. promptSnippet: "Emit a final structured answer as a terminating tool result",
  21. promptGuidelines: [
  22. "Use structured_output as your final action when the user asks for structured output, JSON-like output, or a machine-readable summary.",
  23. "After calling structured_output, do not emit another assistant response in the same turn.",
  24. ],
  25. parameters: Type.Object({
  26. headline: Type.String({ description: "Short title for the result" }),
  27. summary: Type.String({ description: "One-paragraph summary" }),
  28. actionItems: Type.Array(Type.String(), { description: "Concrete next steps or key bullets" }),
  29. }),
  30. async execute(_toolCallId, params) {
  31. return {
  32. content: [{ type: "text", text: `Saved structured output: ${params.headline}` }],
  33. details: {
  34. headline: params.headline,
  35. summary: params.summary,
  36. actionItems: params.actionItems,
  37. } satisfies StructuredOutputDetails,
  38. terminate: true,
  39. };
  40. },
  41. renderResult(result, _options, theme) {
  42. const details = result.details as StructuredOutputDetails | undefined;
  43. if (!details) {
  44. const text = result.content[0];
  45. return new Text(text?.type === "text" ? text.text : "", 0, 0);
  46. }
  47. const lines = [
  48. theme.fg("toolTitle", theme.bold(details.headline)),
  49. theme.fg("text", details.summary),
  50. "",
  51. ...details.actionItems.map((item, index) => theme.fg("muted", `${index + 1}. ${item}`)),
  52. ];
  53. return new Text(lines.join("\n"), 0, 0);
  54. },
  55. });
  56. export default function (pi: ExtensionAPI) {
  57. pi.registerTool(structuredOutputTool);
  58. }