From 3ae4c63a8cfa3db2e53a3934032045f3c666928e Mon Sep 17 00:00:00 2001 From: Robert Gruen Date: Mon, 23 Nov 2026 17:48:12 -0800 Subject: [PATCH 1/2] Separate schema and user messages in TypeScript 0.3.0 Keep the 0.2 request builder behind an explicit legacy layout. Migrate the Program translator and examples, and verify role boundaries, repair, workspace resolution, and packaged consumers with deterministic models. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- site/src/docs/typescript/basic-usage.md | 55 +++++++- typescript/README.md | 15 +++ typescript/examples/calendar/package.json | 2 +- .../examples/coffeeShop-zod/package.json | 2 +- typescript/examples/coffeeShop/package.json | 2 +- typescript/examples/crossword/package.json | 2 +- .../examples/crossword/src/translator.ts | 86 +++--------- typescript/examples/drawing/package.json | 2 +- typescript/examples/drawing/src/main.ts | 10 +- typescript/examples/healthData/package.json | 2 +- .../examples/healthData/src/translator.ts | 58 ++------ typescript/examples/math/package.json | 2 +- typescript/examples/multiSchema/package.json | 2 +- typescript/examples/multiSchema/src/router.ts | 12 +- typescript/examples/music/package.json | 2 +- typescript/examples/restaurant/package.json | 2 +- .../examples/sentiment-zod/package.json | 2 +- typescript/examples/sentiment/package.json | 2 +- typescript/package-lock.json | 28 ++-- typescript/package.json | 2 +- typescript/src/model.ts | 7 +- typescript/src/ts/program.ts | 22 ++- typescript/src/typechat.ts | 47 +++++-- typescript/test/failure.test.ts | 16 ++- typescript/test/program.test.ts | 47 ++++++- typescript/test/prompt-layout.test.ts | 125 ++++++++++++++++++ typescript/tests/examples.test.mjs | 97 +++++++++++++- typescript/tests/package.test.mjs | 16 +++ 28 files changed, 477 insertions(+), 190 deletions(-) create mode 100644 typescript/test/prompt-layout.test.ts diff --git a/site/src/docs/typescript/basic-usage.md b/site/src/docs/typescript/basic-usage.md index 5e0df32b..0e83c814 100644 --- a/site/src/docs/typescript/basic-usage.md +++ b/site/src/docs/typescript/basic-usage.md @@ -396,7 +396,60 @@ When we are ready to translate a user request, we can call the `translate` metho translator.translate("Hello world! šŸ™‚"); ``` -We'll come back to this. +### Message layout in 0.3 + +By default the translator sends: + +1. A **system** message with the application's instructions, the validator's schema and target type, and the JSON output rules. +2. Any **caller-supplied context**, in its original order and roles. A string preamble becomes one user message. +3. One **user** message containing the current request exactly as passed to `translate`, without quoting or other wrappers. + +TypeChat does not store conversation history. For a follow-up, pass prior turns as the second argument, **not** as part of the new request: + +```ts +await translator.translate("What about this one? Great!", [ + { role: "user", content: "I disliked it." }, + { role: "assistant", content: '{"sentiment":"negative"}' } +]); +``` + +For multimodal context, a user section's `content` can be an array of text and image parts. +The [crossword example](https://github.com/microsoft/TypeChat/tree/main/typescript/examples/crossword/src/translator.ts) +passes a screenshot that way, leaving the final user question untouched. + +To add application-owned instructions, extend the system builder. It receives **no request or history**: + +```ts +const schemaPrompt = translator.createSystemPrompt; +translator.createSystemPrompt = () => `${schemaPrompt()}\nClassify the sentiment of the most recent user message.`; +``` + +Keep user text, retrieved content, and model replies out of this builder; assign a caller preamble the system role **only** for your own trusted instructions. +Role separation does not establish intent or authorize an action. Continue validating data and applying application permissions. + +`createProgramTranslator(model, apiSchema)` from `typechat/ts` uses the same message order but a different output contract: +it asks for a JSON **Program** with `@steps`, provides the Program definitions **and** the allowed `API`, and checks calls against that API. + +### Migrating a 0.2 request hook or model + +If you need the previous layout, select it when constructing the translator. This preserves the combined schema/request **user** prompt +and the `createRequestPrompt(request)` hook, including hooks that return structured content: + +```ts +const legacy = createJsonTranslator(model, validator, { promptLayout: "legacy" }); +// If your app overrode this hook in 0.2, the same function can still be used. +legacy.createRequestPrompt = myExistingRequestPrompt; +``` + +`createProgramTranslator` accepts the same option. In the default layout an override of `createRequestPrompt` returns a migration error from `translate` before a model call; +TypeChat neither ignores the override nor calls it to build a system message. To migrate, move just the trusted instructions into `createSystemPrompt()` and pass the context as a preamble. + +A custom model must forward the roles and structured content it receives or report that it cannot. Do not concatenate history into a single prompt. +There is no automatic fallback to legacy. Even in legacy layout a preamble or a repair can require multiple roles. + +In either layout a parsed object that fails validation can trigger **one** repair: TypeChat appends the original model text as **assistant** +and `createRepairPrompt(validationError)` as **user**. Set `attemptRepair = false` to turn that off. +Missing or malformed JSON still fails without a repair. The model's transport retry settings are separate. ## Creating the Prompt diff --git a/typescript/README.md b/typescript/README.md index 1538f41d..2677938f 100644 --- a/typescript/README.md +++ b/typescript/README.md @@ -63,6 +63,21 @@ npm run build The build emits CommonJS JavaScript and declarations in `dist`, and native ESM JavaScript and declarations in `dist/esm`. +### Translator prompts in 0.3 + +`createJsonTranslator` sends the schema and JSON output instructions as a system message, +then caller-supplied context in its original roles and order, then the exact request as a user message. +Extend `translator.createSystemPrompt()` with application-owned instructions only; pass history or image +parts as the second argument to `translate`, not as part of the system message. `typechat/ts`'s +`createProgramTranslator` describes both the JSON Program to return and the API it may call. + +To keep the 0.2 layout or an existing `createRequestPrompt(request)` override, explicitly pass +`{ promptLayout: "legacy" }` as the factory's third argument. Without that option a request-hook +override produces a migration error before dispatch. Validation, repair, and model retry settings +are independent of layout. See the [TypeScript usage and migration examples](https://microsoft.github.io/TypeChat/docs/typescript/basic-usage/). + +### Running the tests + Run the test suite with `npm test`. Package tests verify named and default imports, both module formats, and their declaration resolution using only the files included in the npm package. diff --git a/typescript/examples/calendar/package.json b/typescript/examples/calendar/package.json index 980e18b7..b4d26a4a 100644 --- a/typescript/examples/calendar/package.json +++ b/typescript/examples/calendar/package.json @@ -13,7 +13,7 @@ "dependencies": { "dotenv": "^16.3.1", "find-config": "^1.0.0", - "typechat": "^0.2.0", + "typechat": "^0.3.0", "typescript": "^5.3.3" }, "devDependencies": { diff --git a/typescript/examples/coffeeShop-zod/package.json b/typescript/examples/coffeeShop-zod/package.json index fa17b18d..ca31069e 100644 --- a/typescript/examples/coffeeShop-zod/package.json +++ b/typescript/examples/coffeeShop-zod/package.json @@ -13,7 +13,7 @@ "dependencies": { "dotenv": "^16.3.1", "find-config": "^1.0.0", - "typechat": "^0.2.0", + "typechat": "^0.3.0", "zod": "^4.0.0" }, "devDependencies": { diff --git a/typescript/examples/coffeeShop/package.json b/typescript/examples/coffeeShop/package.json index b6893261..a86bdb2b 100644 --- a/typescript/examples/coffeeShop/package.json +++ b/typescript/examples/coffeeShop/package.json @@ -13,7 +13,7 @@ "dependencies": { "dotenv": "^16.3.1", "find-config": "^1.0.0", - "typechat": "^0.2.0", + "typechat": "^0.3.0", "typescript": "^5.3.3" }, "devDependencies": { diff --git a/typescript/examples/crossword/package.json b/typescript/examples/crossword/package.json index 57ae8fc6..bd6ae442 100644 --- a/typescript/examples/crossword/package.json +++ b/typescript/examples/crossword/package.json @@ -13,7 +13,7 @@ "dependencies": { "dotenv": "^16.3.1", "find-config": "^1.0.0", - "typechat": "^0.2.0", + "typechat": "^0.3.0", "typescript": "^5.3.3" }, "devDependencies": { diff --git a/typescript/examples/crossword/src/translator.ts b/typescript/examples/crossword/src/translator.ts index 0b804388..40f07586 100644 --- a/typescript/examples/crossword/src/translator.ts +++ b/typescript/examples/crossword/src/translator.ts @@ -2,8 +2,7 @@ import { TypeChatLanguageModel, createJsonTranslator, TypeChatJsonTranslator, - MultimodalPromptContent, - PromptContent, + PromptSection, } from "typechat"; import { TypeScriptJsonValidator } from "typechat/ts"; @@ -12,71 +11,22 @@ export function createCrosswordActionTranslator( validator: TypeScriptJsonValidator, crosswordImage: string ): TypeChatJsonTranslator { - const _imageContent = crosswordImage; - - const _translator = createJsonTranslator(model, validator); - _translator.createRequestPrompt = createRequestPrompt - - return _translator; - - function createRequestPrompt(request: string): PromptContent { - const screenshotSection = getScreenshotPromptSection(_imageContent); - const contentSections = [ - { - type: "text", - text: "You are a virtual assistant that can help users to complete requests by interacting with the UI of a webpage.", - }, - ...screenshotSection, - { - type: "text", - text: ` - Use the layout information provided to answer user queries. - The responses should be translated into JSON objects of type ${_translator.validator.getTypeName()} using the typescript schema below: - - ''' - ${_translator.validator.getSchemaText()} - ''' - `, - }, - { - type: "text", - text: ` - The following is a user request: - ''' - ${request} - ''' - The following is the assistant's response translated into a JSON object with 2 spaces of indentation and no properties with the value undefined: - `, - }, - ] as MultimodalPromptContent[]; - - return contentSections; - } - - function getScreenshotPromptSection(screenshot: string | undefined) { - let screenshotSection = []; - if (screenshot) { - screenshotSection.push({ - type: "text", - text: "Here is a screenshot of the currently visible webpage", - }); - - screenshotSection.push({ - type: "image_url", - image_url: { - url: screenshot, - detail: "high" - }, - }); - - screenshotSection.push({ - type: "text", - text: `Use the top left corner as coordinate 0,0 and draw a virtual grid of 1x1 pixels, - where x values increase for each pixel as you go from left to right, and y values increase - as you go from top to bottom. - `, - }); - } - return screenshotSection; + const translator = createJsonTranslator(model, validator); + const schemaPrompt = translator.createSystemPrompt; + translator.createSystemPrompt = () => `${schemaPrompt()}\n` + + "Help the user interact with the crossword webpage using its layout. " + + "Use the top left corner as (0,0), with x increasing to the right and y increasing down, in pixels."; + + if (crosswordImage) { + const screenshot: PromptSection = { role: "user", content: [ + { type: "text", text: "Here is a screenshot of the currently visible webpage" }, + { type: "image_url", image_url: { url: crosswordImage, detail: "high" } }, + ] }; + const translate = translator.translate; + translator.translate = (request, preamble) => { + const context: PromptSection[] = typeof preamble === "string" ? [{ role: "user", content: preamble }] : preamble ?? []; + return translate(request, [...context, screenshot]); + }; } + return translator; } diff --git a/typescript/examples/drawing/package.json b/typescript/examples/drawing/package.json index a357efaf..6ac3a3db 100644 --- a/typescript/examples/drawing/package.json +++ b/typescript/examples/drawing/package.json @@ -13,7 +13,7 @@ "dependencies": { "dotenv": "^16.3.1", "find-config": "^1.0.0", - "typechat": "^0.2.0", + "typechat": "^0.3.0", "typescript": "^5.3.3" }, "devDependencies": { diff --git a/typescript/examples/drawing/src/main.ts b/typescript/examples/drawing/src/main.ts index 8ca0cc05..13f3ed01 100644 --- a/typescript/examples/drawing/src/main.ts +++ b/typescript/examples/drawing/src/main.ts @@ -2,7 +2,7 @@ import dotenv from "dotenv"; import findConfig from "find-config"; import fs from "fs"; import path from "path"; -import { createJsonTranslator, createLanguageModel } from "typechat"; +import { createJsonTranslator, createLanguageModel, PromptSection } from "typechat"; import { processRequests } from "typechat/interactive"; import { createTypeScriptJsonValidator } from "typechat/ts"; import { Drawing } from "./drawingSchema"; @@ -22,18 +22,20 @@ const model = createLanguageModel(process.env); const schema = fs.readFileSync(path.join(__dirname, "drawingSchema.ts"), "utf8"); const validator = createTypeScriptJsonValidator(schema, "Drawing"); const translator = createJsonTranslator(model, validator); +const schemaPrompt = translator.createSystemPrompt; +translator.createSystemPrompt = () => `${schemaPrompt()}\nReturn the complete drawing, including the requested changes.`; const outputPath = path.join(__dirname, "drawing.svg"); -const history: string[] = []; +const history: PromptSection[] = []; // Process requests interactively or from the input file specified on the command line processRequests("šŸŽØ> ", process.argv[2], async (request) => { - const response = await translator.translate([...history, request].join("\n")); + const response = await translator.translate(request, history); if (!response.success) { console.log(response.message); return; } - history.push(request); + history.push({ role: "user", content: request }); const drawing = response.data; console.log(JSON.stringify(drawing, undefined, 2)); diff --git a/typescript/examples/healthData/package.json b/typescript/examples/healthData/package.json index 7336eaec..e542e372 100644 --- a/typescript/examples/healthData/package.json +++ b/typescript/examples/healthData/package.json @@ -13,7 +13,7 @@ "dependencies": { "dotenv": "^16.3.1", "find-config": "^1.0.0", - "typechat": "^0.2.0", + "typechat": "^0.3.0", "typescript": "^5.1.3" }, "devDependencies": { diff --git a/typescript/examples/healthData/src/translator.ts b/typescript/examples/healthData/src/translator.ts index c8e21658..8d052595 100644 --- a/typescript/examples/healthData/src/translator.ts +++ b/typescript/examples/healthData/src/translator.ts @@ -1,13 +1,8 @@ -import {Result, TypeChatLanguageModel, createJsonTranslator, TypeChatJsonTranslator} from "typechat"; +import { PromptSection, Result, TypeChatLanguageModel, createJsonTranslator, TypeChatJsonTranslator } from "typechat"; import { createTypeScriptJsonValidator } from "typechat/ts"; -type ChatMessage = { - source: "system" | "user" | "assistant"; - body: object; -}; - export interface TranslatorWithHistory { - _chatHistory: ChatMessage[]; + _chatHistory: PromptSection[]; _maxPromptLength: number; _additionalAgentInstructions: string; _translator: TypeChatJsonTranslator; @@ -15,13 +10,19 @@ export interface TranslatorWithHistory { } export function createHealthDataTranslator(model: TypeChatLanguageModel, schema: string, typename: string, additionalAgentInstructions: string): TranslatorWithHistory { - const _chatHistory: ChatMessage[] = []; + const _chatHistory: PromptSection[] = []; const _maxPromptLength = 2048; const _additionalAgentInstructions = additionalAgentInstructions; const validator = createTypeScriptJsonValidator(schema, typename); const _translator = createJsonTranslator(model, validator); - _translator.createRequestPrompt = createRequestPrompt; + const schemaPrompt = _translator.createSystemPrompt; + _translator.createSystemPrompt = () => { + const now = new Date(); + return `${schemaPrompt()}\n` + + `Use precise dates and times relative to the current date: ${now.toLocaleDateString()}, time: ${now.toTimeString().split(" ")[0]}.\n` + + `Turn ranges like next week and next month into precise dates.\n${_additionalAgentInstructions}`; + }; const customtranslator: TranslatorWithHistory = { _chatHistory, @@ -34,45 +35,10 @@ export function createHealthDataTranslator(model: TypeChatLang return customtranslator; async function translate(request: string): Promise> { - const response = await _translator.translate(request); + const response = await _translator.translate(request, _chatHistory); if (response.success) { - _chatHistory.push({ source: "assistant", body: response.data }); + _chatHistory.push({ role: "assistant", content: JSON.stringify(response.data, undefined, 2) }); } return response; - - } - - function createRequestPrompt(intent: string): string { - // TODO: drop history entries if we exceed the max_prompt_length - const historyStr = JSON.stringify(_chatHistory, undefined, 2); - - const now = new Date(); - - const prompt = ` -user: You are a service that translates user requests into JSON objects of type "${typename}" according to the following TypeScript definitions: -''' -${schema} -''' - -user: -Use precise date and times RELATIVE TO CURRENT DATE: ${now.toLocaleDateString()} CURRENT TIME: ${now.toTimeString().split(' ')[0]} -Also turn ranges like next week and next month into precise dates - -user: -${_additionalAgentInstructions} - -system: -IMPORTANT CONTEXT for the user request: -${historyStr} - -user: -The following is a user request: -''' -${intent} -''' -The following is the user request translated into a JSON object with 2 spaces of indentation and no properties with the value undefined: -""" -`; - return prompt; } } diff --git a/typescript/examples/math/package.json b/typescript/examples/math/package.json index a0be1ea6..4a11c8c2 100644 --- a/typescript/examples/math/package.json +++ b/typescript/examples/math/package.json @@ -13,7 +13,7 @@ "dependencies": { "dotenv": "^16.3.1", "find-config": "^1.0.0", - "typechat": "^0.2.0", + "typechat": "^0.3.0", "typescript": "^5.3.3" }, "devDependencies": { diff --git a/typescript/examples/multiSchema/package.json b/typescript/examples/multiSchema/package.json index 8ab50afe..5f5b729a 100644 --- a/typescript/examples/multiSchema/package.json +++ b/typescript/examples/multiSchema/package.json @@ -13,7 +13,7 @@ "license": "MIT", "dependencies": { "dotenv": "^16.3.1", - "typechat": "^0.2.0", + "typechat": "^0.3.0", "find-config": "^1.0.0", "music": "^0.0.1", "typescript": "^5.3.3" diff --git a/typescript/examples/multiSchema/src/router.ts b/typescript/examples/multiSchema/src/router.ts index 60debc9e..be3fc0dc 100644 --- a/typescript/examples/multiSchema/src/router.ts +++ b/typescript/examples/multiSchema/src/router.ts @@ -29,6 +29,10 @@ export function createAgentRouter(model: TypeChatLanguageModel description: "Handles all unrecognized requests" }); + const schemaPrompt = taskClassifier.createSystemPrompt; + taskClassifier.createSystemPrompt = () => `${schemaPrompt()}\n` + + `Classify the request using this table of registered agents:\n${JSON.stringify(router._taskTypes, undefined, 2)}`; + return router; async function handlerUnknownTask(request: string): Promise> { @@ -47,13 +51,7 @@ export function createAgentRouter(model: TypeChatLanguageModel } async function routeRequest(request:string): Promise { - const initClasses = JSON.stringify(router._taskTypes, undefined, 2); - const fullRequest = ` -Classify "${request}" using the following classification table:\n -${initClasses}\n`; - const response = await router._taskClassifier.translate(request, [{ - role: "assistant", content: `${fullRequest}` - }]); + const response = await router._taskClassifier.translate(request); if (response.success) { if (response.data.taskType != "No Match") { diff --git a/typescript/examples/music/package.json b/typescript/examples/music/package.json index f646a0f6..e2023e54 100644 --- a/typescript/examples/music/package.json +++ b/typescript/examples/music/package.json @@ -23,7 +23,7 @@ "find-config": "^1.0.0", "open": "^7.0.4", "sqlite3": "^6.0.1", - "typechat": "^0.2.0", + "typechat": "^0.3.0", "typescript": "^5.3.3" }, "devDependencies": { diff --git a/typescript/examples/restaurant/package.json b/typescript/examples/restaurant/package.json index afcfecc0..ad3ab504 100644 --- a/typescript/examples/restaurant/package.json +++ b/typescript/examples/restaurant/package.json @@ -13,7 +13,7 @@ "dependencies": { "dotenv": "^16.3.1", "find-config": "^1.0.0", - "typechat": "^0.2.0", + "typechat": "^0.3.0", "typescript": "^5.3.3" }, "devDependencies": { diff --git a/typescript/examples/sentiment-zod/package.json b/typescript/examples/sentiment-zod/package.json index 87188ff4..2abcc3a9 100644 --- a/typescript/examples/sentiment-zod/package.json +++ b/typescript/examples/sentiment-zod/package.json @@ -13,7 +13,7 @@ "dependencies": { "dotenv": "^16.3.1", "find-config": "^1.0.0", - "typechat": "^0.2.0" + "typechat": "^0.3.0" }, "devDependencies": { "@types/find-config": "1.0.4", diff --git a/typescript/examples/sentiment/package.json b/typescript/examples/sentiment/package.json index 40c2b1a4..8d856fb8 100644 --- a/typescript/examples/sentiment/package.json +++ b/typescript/examples/sentiment/package.json @@ -13,7 +13,7 @@ "dependencies": { "dotenv": "^16.3.1", "find-config": "^1.0.0", - "typechat": "^0.2.0", + "typechat": "^0.3.0", "typescript": "^5.3.3" }, "devDependencies": { diff --git a/typescript/package-lock.json b/typescript/package-lock.json index ab0e9bc6..0ad02b51 100644 --- a/typescript/package-lock.json +++ b/typescript/package-lock.json @@ -1,12 +1,12 @@ { "name": "typechat", - "version": "0.2.0", + "version": "0.3.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "typechat", - "version": "0.2.0", + "version": "0.3.0", "license": "MIT", "workspaces": [ "./", @@ -43,7 +43,7 @@ "dependencies": { "dotenv": "^16.3.1", "find-config": "^1.0.0", - "typechat": "^0.2.0", + "typechat": "^0.3.0", "typescript": "^5.3.3" }, "devDependencies": { @@ -82,7 +82,7 @@ "dependencies": { "dotenv": "^16.3.1", "find-config": "^1.0.0", - "typechat": "^0.2.0", + "typechat": "^0.3.0", "typescript": "^5.3.3" }, "devDependencies": { @@ -98,7 +98,7 @@ "dependencies": { "dotenv": "^16.3.1", "find-config": "^1.0.0", - "typechat": "^0.2.0", + "typechat": "^0.3.0", "zod": "^4.0.0" }, "devDependencies": { @@ -161,7 +161,7 @@ "dependencies": { "dotenv": "^16.3.1", "find-config": "^1.0.0", - "typechat": "^0.2.0", + "typechat": "^0.3.0", "typescript": "^5.3.3" }, "devDependencies": { @@ -199,7 +199,7 @@ "dependencies": { "dotenv": "^16.3.1", "find-config": "^1.0.0", - "typechat": "^0.2.0", + "typechat": "^0.3.0", "typescript": "^5.3.3" }, "devDependencies": { @@ -238,7 +238,7 @@ "dependencies": { "dotenv": "^16.3.1", "find-config": "^1.0.0", - "typechat": "^0.2.0", + "typechat": "^0.3.0", "typescript": "^5.1.3" }, "devDependencies": { @@ -276,7 +276,7 @@ "dependencies": { "dotenv": "^16.3.1", "find-config": "^1.0.0", - "typechat": "^0.2.0", + "typechat": "^0.3.0", "typescript": "^5.3.3" }, "devDependencies": { @@ -316,7 +316,7 @@ "dotenv": "^16.3.1", "find-config": "^1.0.0", "music": "^0.0.1", - "typechat": "^0.2.0", + "typechat": "^0.3.0", "typescript": "^5.3.3" }, "devDependencies": { @@ -359,7 +359,7 @@ "find-config": "^1.0.0", "open": "^7.0.4", "sqlite3": "^6.0.1", - "typechat": "^0.2.0", + "typechat": "^0.3.0", "typescript": "^5.3.3" }, "devDependencies": { @@ -399,7 +399,7 @@ "dependencies": { "dotenv": "^16.3.1", "find-config": "^1.0.0", - "typechat": "^0.2.0", + "typechat": "^0.3.0", "typescript": "^5.3.3" }, "devDependencies": { @@ -437,7 +437,7 @@ "dependencies": { "dotenv": "^16.3.1", "find-config": "^1.0.0", - "typechat": "^0.2.0", + "typechat": "^0.3.0", "typescript": "^5.3.3" }, "devDependencies": { @@ -452,7 +452,7 @@ "dependencies": { "dotenv": "^16.3.1", "find-config": "^1.0.0", - "typechat": "^0.2.0" + "typechat": "^0.3.0" }, "devDependencies": { "@types/find-config": "1.0.4", diff --git a/typescript/package.json b/typescript/package.json index 1df97ea9..e98314b4 100644 --- a/typescript/package.json +++ b/typescript/package.json @@ -1,7 +1,7 @@ { "name": "typechat", "author": "Microsoft", - "version": "0.2.0", + "version": "0.3.0", "license": "MIT", "description": "TypeChat is an experimental library that makes it easy to build natural language interfaces using types.", "keywords": [ diff --git a/typescript/src/model.ts b/typescript/src/model.ts index ef74e34e..b34d69bc 100644 --- a/typescript/src/model.ts +++ b/typescript/src/model.ts @@ -1,9 +1,9 @@ import { Result, success, error, withResponseMetadata, TypeChatResponseMetadata, TypeChatTokenUsage } from "./result.js"; /** - * Represents a section of an LLM prompt with an associated role. TypeChat uses the "user" role for - * prompts it generates and the "assistant" role for previous LLM responses (which will be part of - * the prompt in repair attempts). TypeChat currently doesn't use the "system" role. + * Represents a section of an LLM prompt with an associated role. By default translators send the + * schema and output instructions as system, the current request as user, and, when repairing, + * the rejected model response as assistant and the diagnostic as user. */ export interface PromptSection { /** @@ -88,6 +88,7 @@ export interface TypeChatLanguageModel { * Obtains a completion from the language model for the given prompt. * @param prompt A prompt string or an array of prompt sections. If a string is specified, * it is converted into a single "user" role prompt section. + * Preserve the roles and order of sections; report unsupported layouts rather than flattening them. * Optional result metadata contains service-reported usage and filtering information. */ complete(prompt: string | PromptSection[]): Promise>; diff --git a/typescript/src/ts/program.ts b/typescript/src/ts/program.ts index b771c653..8947afd3 100644 --- a/typescript/src/ts/program.ts +++ b/typescript/src/ts/program.ts @@ -1,7 +1,7 @@ import { Result, error, success } from "../result.js"; import { TypeChatLanguageModel } from "../model.js"; import { createTypeScriptJsonValidator } from "./validate.js"; -import { TypeChatJsonTranslator, createJsonTranslator } from "../typechat.js"; +import { TypeChatJsonTranslator, TypeChatTranslatorOptions, createJsonTranslator } from "../typechat.js"; const programSchemaText = `// A program consists of a sequence of function calls that are evaluated in order. export type Program = { @@ -210,24 +210,34 @@ export async function evaluateJsonProgram(program: Program, onCall: (func: strin * function. * @param model The language model to use for translating requests into programs. * @param schema The TypeScript source code for the target API. The source code must export a type named `API`. + * @param options Selects the prompt layout, as for `createJsonTranslator`. * @returns A `TypeChatJsonTranslator` instance. */ -export function createProgramTranslator(model: TypeChatLanguageModel, schema: string): TypeChatJsonTranslator { +export function createProgramTranslator(model: TypeChatLanguageModel, schema: string, options?: TypeChatTranslatorOptions): TypeChatJsonTranslator { const validator = createTypeScriptJsonValidator( schema, "Program", "API" ); validator.createModuleTextFromJson = createModuleTextFromProgram; - const translator = createJsonTranslator(model, validator); - translator.createRequestPrompt = createRequestPrompt; + const translator = createJsonTranslator(model, validator, options); + translator.createSystemPrompt = () => describeProgram() + + `\`\`\`\n${validator.getSchemaText()}\n\`\`\`\n` + + `Return only a JSON object of type Program with 2 spaces of indentation and no properties with the value undefined.`; + if (options?.promptLayout === "legacy") { + translator.createRequestPrompt = createRequestPrompt; + } translator.createRepairPrompt = createRepairPrompt; return translator; - function createRequestPrompt(request: string) { + function describeProgram() { return `You are a service that translates user requests into programs represented as JSON using the following TypeScript definitions:\n` + `\`\`\`\n${programSchemaText}\`\`\`\n` + - `The programs can call functions from the API defined in the following TypeScript definitions:\n` + + `The programs can call functions from the API defined in the following TypeScript definitions:\n`; + } + + function createRequestPrompt(request: string) { + return describeProgram() + `\`\`\`\n${validator.getSchemaText()}\`\`\`\n` + `The following is a user request:\n` + `"""\n${request}\n"""\n` + diff --git a/typescript/src/typechat.ts b/typescript/src/typechat.ts index 66b082f1..76c2b4e9 100644 --- a/typescript/src/typechat.ts +++ b/typescript/src/typechat.ts @@ -4,6 +4,11 @@ import { typeChatSchemaValidation } from "./schemaValidation.js"; export { typeChatSchemaValidation } from "./schemaValidation.js"; +export interface TypeChatTranslatorOptions { + /** Use separate system and user messages (default), or explicitly select the 0.2 request prompt. */ + promptLayout?: "schema-first" | "legacy"; +} + /** * Represents an object that can translate natural language requests in JSON objects of the given type. */ @@ -29,10 +34,13 @@ export interface TypeChatJsonTranslator { */ stripNulls: boolean; /** - * Creates an AI language model prompt from the given request. This function is called by `completeAndValidate` - * to obtain the prompt. An application can assign a new function to provide a different prompt. - * @param request The natural language request. - * @returns A prompt that combines the request with the schema and type name of the underlying validator. + * Creates the schema-first system message. Include only application-owned instructions, schema, + * and output rules, not user requests, model output, or history. + */ + createSystemPrompt(): string; + /** + * Creates the final user message in the legacy layout. To use an existing override, select + * `{ promptLayout: "legacy" }` at construction. Its content is never used as a system message. */ createRequestPrompt(request: string): PromptContent; /** @@ -62,8 +70,8 @@ export interface TypeChatJsonTranslator { * come from different attempts if a repair response couldn't be parsed. * Optional result metadata retains response records and reported usage across both attempts. * @param request The natural language request. - * @param promptPreamble An optional string or array of prompt sections to prepend to the generated - * prompt. If a string is specified, it is converted into a single "user" role prompt section. + * @param promptPreamble Optional context before the current user message (after the system message + * in the default layout). A string becomes one user message; sections retain their roles and order. * @returns A promise for the resulting object. */ translate(request: string, promptPreamble?: string | PromptSection[]): Promise>; @@ -97,19 +105,23 @@ export interface TypeChatJsonValidatorWithSchemaValidation ext /** * Creates an object that can translate natural language requests into JSON objects of the given type. - * The specified type argument `T` must be the same type as `typeName` in the given `schema`. The function - * creates a `TypeChatJsonValidator` and stores it in the `validator` property of the returned instance. * @param model The language model to use for translating requests into JSON. - * @param validator A string containing the TypeScript source code for the JSON schema. - * @param typeName The name of the JSON target type in the schema. + * @param validator Supplies the schema and validates the translated object. + * @param options Selects the prompt layout. * @returns A `TypeChatJsonTranslator` instance. */ -export function createJsonTranslator(model: TypeChatLanguageModel, validator: TypeChatJsonValidator): TypeChatJsonTranslator { +export function createJsonTranslator( + model: TypeChatLanguageModel, validator: TypeChatJsonValidator, { promptLayout = "schema-first" }: TypeChatTranslatorOptions = {} +): TypeChatJsonTranslator { + if (promptLayout !== "schema-first" && promptLayout !== "legacy") { + throw new Error(`Unknown promptLayout: ${promptLayout}. Expected "schema-first" or "legacy".`); + } const typeChat: TypeChatJsonTranslator = { model, validator, attemptRepair: true, stripNulls: false, + createSystemPrompt, createRequestPrompt, createRepairPrompt, validateInstance: success, @@ -117,6 +129,12 @@ export function createJsonTranslator(model: TypeChatLanguageMo }; return typeChat; + function createSystemPrompt() { + return `Translate user requests into JSON objects of type "${validator.getTypeName()}" using the following TypeScript definitions:\n` + + `\`\`\`\n${validator.getSchemaText()}\n\`\`\`\n` + + `Return only the JSON object with 2 spaces of indentation and no properties with the value undefined.`; + } + function createRequestPrompt(request: string) { return `You are a service that translates user requests into JSON objects of type "${validator.getTypeName()}" according to the following TypeScript definitions:\n` + `\`\`\`\n${validator.getSchemaText()}\`\`\`\n` + @@ -139,7 +157,12 @@ export function createJsonTranslator(model: TypeChatLanguageMo return error(`Schema validation failed before model request: ${preflight.message}`); } const preamble: PromptSection[] = typeof promptPreamble === "string" ? [{ role: "user", content: promptPreamble }] : promptPreamble ?? []; - let prompt: PromptSection[] = [...preamble, { role: "user", content: typeChat.createRequestPrompt(request) }]; + if (promptLayout !== "legacy" && typeChat.createRequestPrompt !== createRequestPrompt) { + return error('A custom createRequestPrompt requires { promptLayout: "legacy" }. To migrate, move application instructions to createSystemPrompt() and pass context as promptPreamble.'); + } + const prompt: PromptSection[] = promptLayout === "legacy" + ? [...preamble, { role: "user", content: typeChat.createRequestPrompt(request) }] + : [{ role: "system", content: typeChat.createSystemPrompt() }, ...preamble, { role: "user", content: request }]; let attemptRepair = typeChat.attemptRepair; let failureContext: (Pick & { responseText: string }) | undefined; const responses: TypeChatResponseMetadata[] = []; diff --git a/typescript/test/failure.test.ts b/typescript/test/failure.test.ts index 5a5666d1..3454a433 100644 --- a/typescript/test/failure.test.ts +++ b/typescript/test/failure.test.ts @@ -251,15 +251,19 @@ describe("translation failure context", () => { }); describe("repair failure context", () => { - it("preserves a successful repair and the existing repair prompt", async () => { - const first = '{"value":"invalid"}'; + it("repair: raw invalid reply as assistant, validator diagnostic as user", async () => { + const first = 'original preface\n{"value":"invalid"}\noriginal suffix'; const { translator, prompts } = translatorFor([success(first), success('{"value":42}')]); assert.deepEqual(await translator.translate("request"), success({ value: 42 })); assert.equal(prompts.length, 2); - const repairPrompt = prompts[1]; - assert.ok(Array.isArray(repairPrompt)); - assert.equal(repairPrompt[1].content, first); - assert.match(String(repairPrompt[2].content), /value must be a number/); + const [initial, repair] = prompts; + assert.ok(Array.isArray(initial)); + assert.deepEqual(initial.map(section => section.role), ["system", "user"]); + assert.equal(initial[1].content, "request"); + assert.doesNotMatch(String(initial[0].content), /original preface|value must be a number/); + assert.deepEqual(repair, [...initial, { role: "assistant", content: first }, { role: "user", content: + `The JSON object is invalid for the following reason:\n"""\nvalue must be a number\n"""\nThe following is a revised JSON object:\n` + }]); }); it("returns the latest rejected candidate after exactly one repair", async () => { diff --git a/typescript/test/program.test.ts b/typescript/test/program.test.ts index 5eaa8183..f68248d4 100644 --- a/typescript/test/program.test.ts +++ b/typescript/test/program.test.ts @@ -1,5 +1,6 @@ import { describe, it } from "node:test"; import assert from "node:assert/strict"; +import type { PromptSection } from "../dist/index.js"; import { createModuleTextFromProgram, createProgramTranslator, @@ -115,11 +116,12 @@ describe("createModuleTextFromProgram result references", () => { describe("createProgramTranslator", () => { const apiSchema = "export interface API { add(a: number, b: number): number; }"; - it("preflights an API-only schema and translates a valid program", async () => { - let modelCalls = 0; + it("program: describes the JSON Program output and allowed API, then validates a program", async () => { + const calls: PromptSection[][] = []; const translator = createProgramTranslator({ - async complete() { - modelCalls++; + async complete(prompt) { + assert.ok(Array.isArray(prompt)); + calls.push(structuredClone(prompt)); return { success: true as const, data: '{"@steps":[{"@func":"add","@args":[1,2]}]}' @@ -131,7 +133,34 @@ describe("createProgramTranslator", () => { const result = await translator.translate("add one and two"); assert.ok(result.success); assert.deepEqual(result.data, { "@steps": [{ "@func": "add", "@args": [1, 2] }] }); - assert.equal(modelCalls, 1); + assert.equal(calls.length, 1); + const [system] = calls[0]; + assert.match(String(system.content), /export type Program =/); + assert.match(String(system.content), /"@steps": FunctionCall\[\]/); + assert.ok(system.content.includes(apiSchema)); + assert.match(String(system.content), /Return only a JSON object of type Program/); + assert.doesNotMatch(String(system.content), /add one and two/); + assert.deepEqual(calls[0], [{ role: "system", content: system.content }, { role: "user", content: "add one and two" }]); + } finally { + (translator.validator as TypeScriptJsonValidator).close(); + } + }); + + it("legacy program prompt keeps both schemas and the request in the user role", async () => { + const translator = createProgramTranslator({ + async complete(prompt) { + assert.ok(Array.isArray(prompt)); + assert.deepEqual(prompt.map(section => section.role), ["user"]); + const content = String(prompt[0].content); + assert.match(content, /export type Program =/); + assert.ok(content.includes(apiSchema)); + assert.match(content, /The following is a user request:\n"""\nadd one and two\n"""/); + assert.match(content, /translated into a JSON program object/); + return { success: true, data: '{"@steps":[]}' }; + } + }, apiSchema, { promptLayout: "legacy" }); + try { + assert.ok((await translator.translate("add one and two")).success); } finally { (translator.validator as TypeScriptJsonValidator).close(); } @@ -144,7 +173,13 @@ describe("createProgramTranslator", () => { ]; let modelCalls = 0; const translator = createProgramTranslator({ - async complete() { + async complete(prompt) { + if (modelCalls === 1) { + assert.ok(Array.isArray(prompt)); + assert.deepEqual(prompt.map(section => section.role), ["system", "user", "assistant", "user"]); + assert.equal(prompt[2].content, responses[0]); + assert.match(String(prompt[3].content), /JSON program object is invalid[\s\S]+not assignable/); + } const data = responses[modelCalls++]; return { success: true as const, data }; } diff --git a/typescript/test/prompt-layout.test.ts b/typescript/test/prompt-layout.test.ts new file mode 100644 index 00000000..9bbab2fb --- /dev/null +++ b/typescript/test/prompt-layout.test.ts @@ -0,0 +1,125 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { createJsonTranslator, error, success, type PromptSection, type TypeChatJsonValidator, type TypeChatLanguageModel } from "../dist/index.js"; + +const schema = "export type Reply = { value: number };"; +const validator: TypeChatJsonValidator<{ value: number }> = { + getSchemaText: () => schema, + getTypeName: () => "Reply", + validate: obj => "value" in obj && typeof obj.value === "number" ? success({ value: obj.value }) : error("expected a number") +}; +const request = ' CURRENT_MARKER\n""" \r\nā˜• '; + +function recorder() { + const calls: PromptSection[][] = []; + const model: TypeChatLanguageModel = { + async complete(prompt) { + assert.ok(Array.isArray(prompt)); + calls.push(structuredClone(prompt)); + return success('{"value":1}'); + } + }; + return { model, calls }; +} + +test("fresh: system schema, then one verbatim user request", async () => { + const { model, calls } = recorder(); + const translator = createJsonTranslator(model, validator); + assert.deepEqual(await translator.translate(request), success({ value: 1 })); + assert.equal(calls.length, 1); + const [system] = calls[0]; + assert.equal(typeof system.content, "string"); + assert.ok(system.content.includes(schema)); + assert.match(String(system.content), /type "Reply"/); + assert.match(String(system.content), /Return only the JSON object/); + assert.doesNotMatch(String(system.content), /CURRENT_MARKER/); + assert.deepEqual(calls[0], [{ role: "system", content: system.content }, { role: "user", content: request }]); +}); + +test("history: caller sections keep their roles and stay out of the generated system message", async () => { + const { model, calls } = recorder(); + const translator = createJsonTranslator(model, validator); + const history: PromptSection[] = [ + { role: "user", content: ["PAST_USER", { type: "text", text: "CAPTION" }, + { type: "image_url", image_url: { url: "data:image/png;base64,AAAA", detail: "low" } }] }, + { role: "assistant", content: 'PAST_ANSWER\n{"value":1}' }, + { role: "system", content: "CALLER_SYSTEM" } + ]; + const original = structuredClone(history); + assert.ok((await translator.translate(request, history)).success); + assert.ok((await translator.translate("fresh again")).success); + const [system] = calls[1]; + assert.equal(system.role, "system"); + assert.doesNotMatch(String(system.content), /PAST_|CAPTION|base64|CALLER_SYSTEM|CURRENT_MARKER|fresh again/); + assert.deepEqual(calls, [ + [system, ...original, { role: "user", content: request }], + [system, { role: "user", content: "fresh again" }] + ]); + assert.deepEqual(history, original); +}); + +test("custom system builder receives no request or history; a string preamble stays user", async () => { + const { model, calls } = recorder(); + const translator = createJsonTranslator(model, validator); + const base = translator.createSystemPrompt; + const instructions = `${base()}\nUse the application vocabulary.`; + translator.createSystemPrompt = (...args) => { + assert.deepEqual(args, []); + return instructions; + }; + assert.ok((await translator.translate(request, "caller context")).success); + assert.deepEqual(calls, [[ + { role: "system", content: instructions }, { role: "user", content: "caller context" }, { role: "user", content: request } + ]]); +}); + +test("legacy: explicit 0.2 request layout", async () => { + const { model, calls } = recorder(); + const translator = createJsonTranslator(model, validator, { promptLayout: "legacy" }); + const history: PromptSection[] = [{ role: "assistant", content: "previous reply" }]; + assert.ok((await translator.translate(request, history)).success); + assert.deepEqual(calls, [[...history, { role: "user", content: + `You are a service that translates user requests into JSON objects of type "Reply" according to the following TypeScript definitions:\n` + + `\`\`\`\n${schema}\`\`\`\nThe following is a user request:\n"""\n${request}\n"""\n` + + `The following is the user request translated into a JSON object with 2 spaces of indentation and no properties with the value undefined:\n` + }]]); +}); + +test("legacy: custom request content stays in the user role", async () => { + const { model, calls } = recorder(); + const translator = createJsonTranslator(model, validator, { promptLayout: "legacy" }); + translator.createRequestPrompt = text => [ + { type: "image_url", image_url: { url: "https://example.test/puzzle.png", detail: "high" } }, `wrapped:${text}` + ]; + assert.ok((await translator.translate(request, "before")).success); + assert.deepEqual(calls, [[{ role: "user", content: "before" }, { role: "user", content: [ + { type: "image_url", image_url: { url: "https://example.test/puzzle.png", detail: "high" } }, `wrapped:${request}` + ] }]]); +}); + +test("unmigrated request hook fails before dispatch, without fallback", async () => { + const { model, calls } = recorder(); + const translator = createJsonTranslator(model, validator); + translator.createRequestPrompt = () => assert.fail("must not invoke or promote a request-bearing hook"); + const result = await translator.translate(request); + assert.ok(!result.success); + assert.match(result.message, /createRequestPrompt.*promptLayout: "legacy".*createSystemPrompt/); + assert.deepEqual(calls, []); +}); + +test("a model rejecting roles is not retried with flattened history or implicit legacy", async () => { + const calls: PromptSection[][] = []; + const unsupported = error("This model supports a single user message only."); + const model: TypeChatLanguageModel = { + async complete(prompt) { + assert.ok(Array.isArray(prompt)); + calls.push(structuredClone(prompt)); + return prompt.length === 1 && prompt[0].role === "user" ? success('{"value":1}') : unsupported; + } + }; + assert.deepEqual(await createJsonTranslator(model, validator).translate(request, "PAST"), unsupported); + assert.deepEqual(calls.map(call => call.map(section => section.role)), [["system", "user", "user"]]); + const legacy = createJsonTranslator(model, validator, { promptLayout: "legacy" }); + assert.ok((await legacy.translate(request)).success); + assert.deepEqual(await legacy.translate(request, "PAST"), unsupported); +}); diff --git a/typescript/tests/examples.test.mjs b/typescript/tests/examples.test.mjs index c581b2c7..887dcdaa 100644 --- a/typescript/tests/examples.test.mjs +++ b/typescript/tests/examples.test.mjs @@ -5,6 +5,9 @@ import { createRequire } from "node:module"; import { dirname, join } from "node:path"; import { describe, test } from "node:test"; import { fileURLToPath } from "node:url"; +import { compileFunction } from "node:vm"; +import { success } from "../dist/index.js"; +import { createTypeScriptJsonValidator } from "../dist/ts/index.js"; const examplesDir = join(dirname(fileURLToPath(import.meta.url)), "..", "examples"); const examples = [ @@ -49,12 +52,15 @@ function runStartup(source, dotEnvPath) { }); } -for (const example of examples) { - const mainPath = join(examplesDir, example, "src", "main.ts"); - const ts = createRequire(mainPath)("typescript"); - const source = ts.transpileModule(readFileSync(mainPath, "utf8"), { +function compileExample(file) { + const ts = createRequire(file)("typescript"); + return ts.transpileModule(readFileSync(file, "utf8"), { compilerOptions: { module: ts.ModuleKind.CommonJS, esModuleInterop: true }, }).outputText; +} + +for (const example of examples) { + const source = compileExample(join(examplesDir, example, "src", "main.ts")); describe(`${example} environment setup`, () => { test("reports missing .env without a stack trace and exits with status 1", () => { @@ -75,3 +81,86 @@ for (const example of examples) { }); }); } + +test("all example workspaces resolve the local TypeChat build", () => { + for (const example of [...examples, "music"]) { + const require = createRequire(join(examplesDir, example, "package.json")); + assert.equal(require.resolve("typechat"), fileURLToPath(new URL("../dist/index.js", import.meta.url)), example); + } +}); + +// Exercise the checked-in example, not a stale example dist/ or a copy of its prompt. +function loadTranslator(example) { + const file = join(examplesDir, example, "src", "translator.ts"); + const exports = {}; + compileFunction(compileExample(file), ["require", "exports"], { filename: file })(createRequire(file), exports); + return exports; +} + +function recordingModel(...answers) { + const calls = []; + const model = { + async complete(prompt) { + assert.ok(answers.length, "unexpected model call"); + calls.push(structuredClone(prompt)); + return success(JSON.stringify(answers.shift())); + } + }; + return { model, calls }; +} + +test("crossword example: screenshot parts stay user context before the raw question", async () => { + const { createCrosswordActionTranslator } = loadTranslator("crossword"); + const schema = readFileSync(join(examplesDir, "crossword", "src", "crosswordSchema.ts"), "utf8"); + const validator = createTypeScriptJsonValidator(schema, "CrosswordActions"); + const answer = { actionName: "getClueText", parameters: { clueNumber: 61, clueDirection: "across", value: "Monogram" } }; + const { model, calls } = recordingModel(answer); + const image = "data:image/jpeg;base64,AAAA"; + const request = " What is 61 across? "; + try { + const translator = createCrosswordActionTranslator(model, validator, image); + assert.deepEqual(await translator.translate(request, "earlier context"), success(answer)); + assert.equal(calls.length, 1); + const [system] = calls[0]; + assert.ok(system.content.includes(schema)); + assert.match(system.content, /crossword webpage/); + assert.doesNotMatch(system.content, /base64|earlier context|61 across/); + assert.deepEqual(calls[0], [ + { role: "system", content: system.content }, + { role: "user", content: "earlier context" }, + { role: "user", content: [ + { type: "text", text: "Here is a screenshot of the currently visible webpage" }, + { type: "image_url", image_url: { url: image, detail: "high" } } + ] }, + { role: "user", content: request } + ]); + } finally { + validator.close(); + } +}); + +test("healthData example: validated prior answer stays assistant context", async () => { + const { createHealthDataTranslator } = loadTranslator("healthData"); + const schema = readFileSync(join(examplesDir, "healthData", "src", "healthDataSchema.ts"), "utf8"); + const firstAnswer = { message: "PAST_ANSWER" }; + const { model, calls } = recordingModel(firstAnswer, { message: "OK" }); + const translator = createHealthDataTranslator(model, schema, "HealthDataResponse", "APP_INSTRUCTIONS"); + try { + assert.ok((await translator.translate("FIRST_REQUEST")).success); + assert.ok((await translator.translate("NEXT_REQUEST")).success); + assert.equal(calls.length, 2); + for (const [system] of calls) { + assert.equal(system.role, "system"); + assert.ok(system.content.includes(schema)); + assert.match(system.content, /APP_INSTRUCTIONS/); + assert.doesNotMatch(system.content, /PAST_ANSWER|FIRST_REQUEST|NEXT_REQUEST/); + } + assert.deepEqual(calls[0].slice(1), [{ role: "user", content: "FIRST_REQUEST" }]); + assert.deepEqual(calls[1].slice(1), [ + { role: "assistant", content: JSON.stringify(firstAnswer, null, 2) }, + { role: "user", content: "NEXT_REQUEST" } + ]); + } finally { + translator._translator.validator.close(); + } +}); diff --git a/typescript/tests/package.test.mjs b/typescript/tests/package.test.mjs index 84b770e9..2fe239c4 100644 --- a/typescript/tests/package.test.mjs +++ b/typescript/tests/package.test.mjs @@ -292,6 +292,11 @@ describe("published package", () => { "export interface Value { value: string; }", "Value" ); const translator: TypeChatJsonTranslator = createJsonTranslator(model, validator); + const system: string = translator.createSystemPrompt(); + // @ts-expect-error A system prompt builder never receives the user request. + translator.createSystemPrompt = (request: string) => request; + const legacy = createJsonTranslator(model, validator, { promptLayout: "legacy" }); + legacy.createRequestPrompt = request => [{ type: "text", text: request }]; const result: Result = createZodJsonValidator( { Value: z.object({ value: z.string() }) }, "Value" ).validate({ value: "ok" }); @@ -487,6 +492,7 @@ test("published package works for a clean TypeScript 7 consumer", () => { writeFileSync( verification, `import assert from "node:assert/strict"; +import { createJsonTranslator, success } from "typechat"; import { createTypeScriptJsonValidator } from "typechat/ts"; const validator = createTypeScriptJsonValidator( @@ -499,6 +505,16 @@ try { data: { value: "ok" }, }); assert.equal(validator.validate({ value: 42 }).success, false); + const translator = createJsonTranslator({ + async complete(prompt) { + assert.deepEqual(prompt.map(section => section.role), ["system", "user"]); + assert.ok(prompt[0].content.includes(validator.getSchemaText())); + assert.ok(!prompt[0].content.includes("PACKED_REQUEST")); + assert.equal(prompt[1].content, " PACKED_REQUEST "); + return success('{"value":"ok"}'); + } + }, validator); + assert.deepEqual(await translator.translate(" PACKED_REQUEST "), success({ value: "ok" })); } finally { validator.close?.(); } From 83053fddebd121738fc0e694f7637da1e32249c2 Mon Sep 17 00:00:00 2001 From: Robert Gruen Date: Tue, 24 Nov 2026 17:26:40 -0800 Subject: [PATCH 2/2] Repair missing and malformed JSON once TypeScript now makes the same one repair attempt as Python and TypeChat.NET when a reply has no JSON object or cannot be parsed. Validation failures still repair once, and attemptRepair = false still returns immediately. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- site/src/docs/typescript/basic-usage.md | 8 +-- typescript/README.md | 2 +- typescript/src/typechat.ts | 87 ++++++++++++++----------- typescript/test/failure.test.ts | 20 +++++- 4 files changed, 74 insertions(+), 43 deletions(-) diff --git a/site/src/docs/typescript/basic-usage.md b/site/src/docs/typescript/basic-usage.md index 0e83c814..db193d59 100644 --- a/site/src/docs/typescript/basic-usage.md +++ b/site/src/docs/typescript/basic-usage.md @@ -384,7 +384,7 @@ import { createJsonTranslator } from "typechat"; A translator takes both a model and a validator, and provides a way to translate some user input into objects following our schema. To do so, it crafts a prompt based on the schema, reaches out to the model, parses out JSON data, and attempts validation. -Optionally, it will craft repair prompts and retry if validation fails. +Optionally, it will craft one repair prompt and retry if the response has no JSON object, the JSON cannot be parsed, or validation fails. ```ts const translator = createJsonTranslator(model, validator); @@ -447,9 +447,9 @@ TypeChat neither ignores the override nor calls it to build a system message. To A custom model must forward the roles and structured content it receives or report that it cannot. Do not concatenate history into a single prompt. There is no automatic fallback to legacy. Even in legacy layout a preamble or a repair can require multiple roles. -In either layout a parsed object that fails validation can trigger **one** repair: TypeChat appends the original model text as **assistant** -and `createRepairPrompt(validationError)` as **user**. Set `attemptRepair = false` to turn that off. -Missing or malformed JSON still fails without a repair. The model's transport retry settings are separate. +In either layout, missing JSON, JSON that cannot be parsed, or a parsed object that fails validation can trigger **one** repair: TypeChat appends the original model text as **assistant** +and `createRepairPrompt(diagnostic)` as **user**. Set `attemptRepair = false` to turn that off. +The model's transport retry settings are separate. ## Creating the Prompt diff --git a/typescript/README.md b/typescript/README.md index 2677938f..2f5c8985 100644 --- a/typescript/README.md +++ b/typescript/README.md @@ -11,7 +11,7 @@ Simply define types that represent the intents supported in your natural languag After defining your types, TypeChat takes care of the rest by: 1. Constructing a prompt to the LLM using types. -2. Validating the LLM response conforms to the schema. If the validation fails, repair the non-conforming output through further language model interaction. +2. Validating the LLM response conforms to the schema. If the response is not usable JSON or validation fails, repair the output through one further language model interaction. 3. Summarizing succinctly (without use of a LLM) the instance and confirm that it aligns with user intent. Types are all you need! diff --git a/typescript/src/typechat.ts b/typescript/src/typechat.ts index 76c2b4e9..1fa9ddaf 100644 --- a/typescript/src/typechat.ts +++ b/typescript/src/typechat.ts @@ -22,8 +22,9 @@ export interface TypeChatJsonTranslator { */ validator: TypeChatJsonValidator; /** - * A boolean indicating whether to attempt repairing JSON objects that fail to validate. The default is `true`, - * but an application can set the property to `false` to disable repair attempts. + * A boolean indicating whether to attempt one repair when the response has no JSON object, the JSON cannot + * be parsed, or the object fails to validate. The default is `true`, but an application can set the property + * to `false` to disable repair attempts. */ attemptRepair: boolean; /** @@ -44,11 +45,10 @@ export interface TypeChatJsonTranslator { */ createRequestPrompt(request: string): PromptContent; /** - * Creates a repair prompt to append to an original prompt/response in order to repair a JSON object that - * failed to validate. This function is called by `completeAndValidate` when `attemptRepair` is true and the - * JSON object produced by the original prompt failed to validate. An application can assign a new function - * to provide a different repair prompt. - * @param validationError The error message returned by the validator. + * Creates a repair prompt to append to an original prompt/response. This function is called when + * `attemptRepair` is true and the response has no usable JSON object or the object failed to validate. + * An application can assign a new function to provide a different repair prompt. + * @param validationError The diagnostic for the failed response. * @returns A repair prompt constructed from the error message. */ createRepairPrompt(validationError: string): string; @@ -62,10 +62,10 @@ export interface TypeChatJsonTranslator { */ validateInstance(instance: T): Result; /** - * Translates a natural language request into an object of type `T`. If the JSON object returned by - * the language model fails to validate and the `attemptRepair` property is `true`, a second - * attempt to translate the request will be made. The prompt for the second attempt will include the - * diagnostics produced for the first attempt. This often helps produce a valid instance. + * Translates a natural language request into an object of type `T`. If the response has no JSON object, + * the JSON cannot be parsed, or the object fails to validate, and `attemptRepair` is `true`, one further + * attempt is made. The repair prompt includes the diagnostic from the first attempt. This often helps + * produce a valid instance. * A failure retains the latest rejected candidate and available model response text. These may * come from different attempts if a repair response couldn't be parsed. * Optional result metadata retains response records and reported usage across both attempts. @@ -184,38 +184,51 @@ export function createJsonTranslator( failureContext = { ...failureContext, responseText }; const startIndex = responseText.indexOf("{"); const endIndex = responseText.lastIndexOf("}"); - if (!(startIndex >= 0 && endIndex > startIndex)) { - return finish(error(`Response is not JSON:\n${responseText}`, failureContext)); + const jsonText = startIndex >= 0 && endIndex > startIndex ? responseText.slice(startIndex, endIndex + 1) : undefined; + let parsed = false; + let jsonObject: object = {}; + let failure: (TypeChatError & { responseText: string }) | undefined; + if (!jsonText) { + failure = { ...error(`Response is not JSON:\n${responseText}`, failureContext), responseText }; } - const jsonText = responseText.slice(startIndex, endIndex + 1); - let jsonObject; - try { - jsonObject = JSON.parse(jsonText) as object; - } - catch (e) { - return finish(error(e instanceof SyntaxError ? e.message : "JSON parse error", failureContext)); + else { + try { + jsonObject = JSON.parse(jsonText) as object; + parsed = true; + } + catch (e) { + failure = { ...error(e instanceof SyntaxError ? e.message : "JSON parse error", failureContext), responseText }; + } } - if (typeChat.stripNulls) { - stripNulls(jsonObject); + if (parsed) { + if (typeChat.stripNulls) { + stripNulls(jsonObject); + } + const schemaValidation = validator.validate(jsonObject); + const validation = schemaValidation.success ? typeChat.validateInstance(schemaValidation.data) : schemaValidation; + if (validation.success) { + return finish(validation); + } + failure = { + ...validation, + success: false, + message: validation.message, + data: "data" in validation ? validation.data : schemaValidation.success ? schemaValidation.data : jsonObject, + responseText: validation.responseText ?? responseText + }; + if (!attemptRepair) { + return finish({ ...failure, message: `JSON validation failed: ${failure.message}\n${jsonText}` }); + } } - const schemaValidation = validator.validate(jsonObject); - const validation = schemaValidation.success ? typeChat.validateInstance(schemaValidation.data) : schemaValidation; - if (validation.success) { - return finish(validation); + else if (!attemptRepair) { + return finish(failure!); } - const failure: TypeChatError & { responseText: string } = { - ...validation, - success: false, - message: validation.message, - data: "data" in validation ? validation.data : schemaValidation.success ? schemaValidation.data : jsonObject, - responseText: validation.responseText ?? responseText + failureContext = { + ...("data" in failure! ? { data: failure!.data } : {}), + responseText: failure!.responseText }; - failureContext = { data: failure.data, responseText: failure.responseText }; - if (!attemptRepair) { - return finish({ ...failure, message: `JSON validation failed: ${failure.message}\n${jsonText}` }); - } prompt.push({ role: "assistant", content: responseText }); - prompt.push({ role: "user", content: typeChat.createRepairPrompt(failure.message) }); + prompt.push({ role: "user", content: typeChat.createRepairPrompt(failure!.message) }); attemptRepair = false; } } diff --git a/typescript/test/failure.test.ts b/typescript/test/failure.test.ts index 3454a433..ba768561 100644 --- a/typescript/test/failure.test.ts +++ b/typescript/test/failure.test.ts @@ -224,14 +224,32 @@ describe("translation failure context", () => { }); for (const responseText of ["not JSON", 'before {"value":} after', ""]) { - it("retains unparseable output without inventing data or changing repair behavior", async () => { + it("retains unparseable output without inventing data when repair is disabled", async () => { const { translator, prompts } = translatorFor([success(responseText)]); + translator.attemptRepair = false; const result = await translator.translate("request"); assert.ok(!result.success); assert.ok(!("data" in result)); assert.equal(result.responseText, responseText); assert.equal(prompts.length, 1); }); + + it("repairs unparseable output once without changing the schema-first request", async () => { + const { translator, prompts } = translatorFor([success(responseText), success('{"value":7}')]); + const result = await translator.translate("request"); + assert.deepEqual(result, success({ value: 7 })); + assert.equal(prompts.length, 2); + const [initial, repair] = prompts; + assert.ok(Array.isArray(initial)); + assert.ok(Array.isArray(repair)); + assert.deepEqual(initial.map(section => section.role), ["system", "user"]); + assert.equal(initial[1].content, "request"); + assert.deepEqual(repair.slice(0, initial.length), initial); + assert.equal(repair[repair.length - 2].role, "assistant"); + assert.equal(repair[repair.length - 2].content, responseText); + assert.equal(repair[repair.length - 1].role, "user"); + assert.match(String(repair[repair.length - 1].content), /Response is not JSON|JSON parse error|Unexpected|Expected/); + }); } it("propagates an initial model failure unchanged", async () => {