Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 55 additions & 2 deletions site/src/docs/typescript/basic-usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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, 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

Expand Down
17 changes: 16 additions & 1 deletion typescript/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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!
Expand Down Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion typescript/examples/calendar/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
2 changes: 1 addition & 1 deletion typescript/examples/coffeeShop-zod/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
2 changes: 1 addition & 1 deletion typescript/examples/coffeeShop/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
2 changes: 1 addition & 1 deletion typescript/examples/crossword/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
86 changes: 18 additions & 68 deletions typescript/examples/crossword/src/translator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ import {
TypeChatLanguageModel,
createJsonTranslator,
TypeChatJsonTranslator,
MultimodalPromptContent,
PromptContent,
PromptSection,
} from "typechat";
import { TypeScriptJsonValidator } from "typechat/ts";

Expand All @@ -12,71 +11,22 @@ export function createCrosswordActionTranslator<T extends object>(
validator: TypeScriptJsonValidator<T>,
crosswordImage: string
): TypeChatJsonTranslator<T> {
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;
}
2 changes: 1 addition & 1 deletion typescript/examples/drawing/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
10 changes: 6 additions & 4 deletions typescript/examples/drawing/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -22,18 +22,20 @@ const model = createLanguageModel(process.env);
const schema = fs.readFileSync(path.join(__dirname, "drawingSchema.ts"), "utf8");
const validator = createTypeScriptJsonValidator<Drawing>(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));
Expand Down
2 changes: 1 addition & 1 deletion typescript/examples/healthData/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
58 changes: 12 additions & 46 deletions typescript/examples/healthData/src/translator.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,28 @@
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<T extends object> {
_chatHistory: ChatMessage[];
_chatHistory: PromptSection[];
_maxPromptLength: number;
_additionalAgentInstructions: string;
_translator: TypeChatJsonTranslator<T>;
translate(request: string): Promise<Result<T>>;
}

export function createHealthDataTranslator<T extends object>(model: TypeChatLanguageModel, schema: string, typename: string, additionalAgentInstructions: string): TranslatorWithHistory<T> {
const _chatHistory: ChatMessage[] = [];
const _chatHistory: PromptSection[] = [];
const _maxPromptLength = 2048;
const _additionalAgentInstructions = additionalAgentInstructions;

const validator = createTypeScriptJsonValidator<T>(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<T> = {
_chatHistory,
Expand All @@ -34,45 +35,10 @@ export function createHealthDataTranslator<T extends object>(model: TypeChatLang
return customtranslator;

async function translate(request: string): Promise<Result<T>> {
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;
}
}
2 changes: 1 addition & 1 deletion typescript/examples/math/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
2 changes: 1 addition & 1 deletion typescript/examples/multiSchema/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
Loading
Loading