diff --git a/.gitignore b/.gitignore index 00f84bc5..a8e435df 100644 --- a/.gitignore +++ b/.gitignore @@ -14,4 +14,3 @@ node_modules/ **/tsconfig.debug.json !**/.vscode/launch.json **/build.bat - diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 00000000..4a933dc4 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,113 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "name": "sentiment", + "type": "node", + "request": "launch", + "program": "${workspaceFolder}/typescript/examples/sentiment/src/main.ts", + "stopOnEntry": false, + "args": [], + "cwd": "${workspaceFolder}/typescript/examples/sentiment", + "skipFiles": [ + "/**" + ], + "preLaunchTask": "build-sentiment", + "sourceMaps": true, + "outFiles": [ + "${workspaceFolder}/typescript/examples/sentiment/dist/**/*.js" + ], + "console": "integratedTerminal" + }, + { + "name": "calendar", + "type": "node", + "request": "launch", + "program": "${workspaceFolder}/typescript/examples/calendar/src/main.ts", + "stopOnEntry": false, + "args": [], + "cwd": "${workspaceFolder}/typescript/examples/calendar", + "skipFiles": [ + "/**" + ], + "preLaunchTask": "build-calendar", + "sourceMaps": true, + "outFiles": [ + "${workspaceFolder}/typescript/examples/calendar/dist/**/*.js" + ], + "console": "integratedTerminal" + }, + { + "name": "math", + "type": "node", + "request": "launch", + "program": "${workspaceFolder}/typescript/examples/math/src/main.ts", + "stopOnEntry": false, + "args": [], + "cwd": "${workspaceFolder}/typescript/examples/math", + "skipFiles": [ + "/**" + ], + "preLaunchTask": "build-math", + "sourceMaps": true, + "outFiles": [ + "${workspaceFolder}/typescript/examples/math/dist/**/*.js" + ], + "console": "integratedTerminal" + }, + { + "name": "music", + "type": "node", + "request": "launch", + "program": "${workspaceFolder}/typescript/examples/music/src/main.ts", + "stopOnEntry": false, + "args": [], + "cwd": "${workspaceFolder}/typescript/examples/music", + "skipFiles": [ + "/**" + ], + "preLaunchTask": "build-music", + "sourceMaps": true, + "outFiles": [ + "${workspaceFolder}/typescript/examples/music/dist/**/*.js" + ], + "console": "integratedTerminal" + }, + { + "name": "restaurant", + "type": "node", + "request": "launch", + "program": "${workspaceFolder}/typescript/examples/restaurant/src/main.ts", + "stopOnEntry": false, + "args": [], + "cwd": "${workspaceFolder}/typescript/examples/restaurant", + "skipFiles": [ + "/**" + ], + "preLaunchTask": "build-restaurant", + "sourceMaps": true, + "outFiles": [ + "${workspaceFolder}/typescript/examples/restaurant/dist/**/*.js" + ], + "console": "integratedTerminal" + }, + { + "name": "coffeeShop", + "type": "node", + "request": "launch", + "program": "${workspaceFolder}/typescript/examples/coffeeShop/src/main.ts", + "stopOnEntry": false, + "args": [], + "cwd": "${workspaceFolder}/typescript/examples/coffeeShop", + "skipFiles": [ + "/**" + ], + "preLaunchTask": "build-coffeeShop", + "sourceMaps": true, + "outFiles": [ + "${workspaceFolder}/typescript/examples/coffeeShop/dist/**/*.js" + ], + "console": "integratedTerminal" + } + ] +} \ No newline at end of file diff --git a/.vscode/tasks.json b/.vscode/tasks.json new file mode 100644 index 00000000..e87f8b93 --- /dev/null +++ b/.vscode/tasks.json @@ -0,0 +1,59 @@ +{ + "version": "2.0.0", + "tasks": [ + { + "label": "build-sentiment", + "type": "npm", + "script": "build", + "path": "typescript/examples/sentiment", + "group": "build", + "problemMatcher": [], + "detail": "tsc -p src" + }, + { + "label": "build-calendar", + "type": "npm", + "script": "build", + "path": "typescript/examples/calendar", + "group": "build", + "problemMatcher": [], + "detail": "tsc -p src" + }, + { + "label": "build-math", + "type": "npm", + "script": "build", + "path": "typescript/examples/math", + "group": "build", + "problemMatcher": [], + "detail": "tsc -p src" + }, + { + "label": "build-music", + "type": "npm", + "script": "build", + "path": "typescript/examples/music", + "group": "build", + "problemMatcher": [], + "detail": "tsc -p src" + }, + { + "label": "build-restaurant", + "type": "npm", + "script": "build", + "path": "typescript/examples/restaurant", + "group": "build", + "problemMatcher": [], + "detail": "tsc -p src" + }, + { + "label": "build-coffeeShop", + "type": "npm", + "script": "build", + "path": "typescript/examples/coffeeShop", + "group": "build", + "problemMatcher": [], + "detail": "tsc -p src" + } + ] +} \ No newline at end of file diff --git a/typescript/examples/README.md b/typescript/examples/README.md index 62237a5a..9ae1922f 100644 --- a/typescript/examples/README.md +++ b/typescript/examples/README.md @@ -80,7 +80,7 @@ To use an Azure OpenAI endpoint, include the following environment variables: | `AZURE_OPENAI_ENDPOINT` | The full URL of the Azure OpenAI REST API (e.g. `https://YOUR_RESOURCE_NAME.openai.azure.com/openai/deployments/YOUR_DEPLOYMENT_NAME/chat/completions?api-version=2023-05-15`) | | `AZURE_OPENAI_API_KEY` | Your Azure OpenAI API key | -We recommend setting environment variables by creating a `.env` file in the root directory of the project that looks like the following: +Copy [`.env.example`](../../.env.example) to `.env` in the repository root, then fill in the values for the endpoint you want to use: ```ini # For OpenAI @@ -92,6 +92,8 @@ AZURE_OPENAI_ENDPOINT=... AZURE_OPENAI_API_KEY=... ``` +Examples that search for `.env` look in the current working directory and its parent directories. If no file is found, they print a setup message and exit with status `1`, without an assertion stack trace. + ### Using a proxy (optional) If the model endpoint can only be reached through a proxy (for example in restricted regions), @@ -117,6 +119,8 @@ Examples can be found in the `examples` directory. To run an example interactively, type `node ./dist/main.js` from the example's directory and enter requests when prompted. Type `quit` or `exit` to end the session. You can also open in VS Code the selected example's directory and press F5 to launch it in debug mode. +To debug from the repository root in VS Code, choose an example configuration in Run and Debug and press F5. Configure `.env` as described above before starting the debugger. + Note that there are various sample "prose" files (e.g. `input.txt`) provided in each `src` directory that can give a sense of what you can run. To run an example with one of these input files, run `node ./dist/main.js `. diff --git a/typescript/examples/calendar/src/main.ts b/typescript/examples/calendar/src/main.ts index 03d71244..c4f1df93 100644 --- a/typescript/examples/calendar/src/main.ts +++ b/typescript/examples/calendar/src/main.ts @@ -1,4 +1,3 @@ -import assert from "assert"; import dotenv from "dotenv"; import findConfig from "find-config"; import fs from "fs"; @@ -9,7 +8,13 @@ import { processRequests } from "typechat/interactive"; import { CalendarActions } from './calendarActionsSchema'; const dotEnvPath = findConfig(".env"); -assert(dotEnvPath, ".env file not found!"); +if (!dotEnvPath) { + console.error( + "Error: .env file not found.\n" + + "Copy .env.example to .env in the repository root and configure your OpenAI or Azure OpenAI credentials." + ); + process.exit(1); +} dotenv.config({ path: dotEnvPath }); const model = createLanguageModel(process.env); diff --git a/typescript/examples/coffeeShop-zod/src/main.ts b/typescript/examples/coffeeShop-zod/src/main.ts index a97fe71b..3614ae84 100644 --- a/typescript/examples/coffeeShop-zod/src/main.ts +++ b/typescript/examples/coffeeShop-zod/src/main.ts @@ -1,4 +1,3 @@ -import assert from "assert"; import dotenv from "dotenv"; import findConfig from "find-config"; import { createJsonTranslator, createLanguageModel } from "typechat"; @@ -8,7 +7,13 @@ import { z } from "zod"; import { CoffeeShopSchema } from "./coffeeShopSchema"; const dotEnvPath = findConfig(".env"); -assert(dotEnvPath, ".env file not found!"); +if (!dotEnvPath) { + console.error( + "Error: .env file not found.\n" + + "Copy .env.example to .env in the repository root and configure your OpenAI or Azure OpenAI credentials." + ); + process.exit(1); +} dotenv.config({ path: dotEnvPath }); const model = createLanguageModel(process.env); diff --git a/typescript/examples/coffeeShop/src/main.ts b/typescript/examples/coffeeShop/src/main.ts index fd6326f4..d58cbefe 100644 --- a/typescript/examples/coffeeShop/src/main.ts +++ b/typescript/examples/coffeeShop/src/main.ts @@ -1,4 +1,3 @@ -import assert from "assert"; import dotenv from "dotenv"; import findConfig from "find-config"; import fs from "fs"; @@ -9,7 +8,13 @@ import { processRequests } from "typechat/interactive"; import { Cart } from "./coffeeShopSchema"; const dotEnvPath = findConfig(".env"); -assert(dotEnvPath, ".env file not found!"); +if (!dotEnvPath) { + console.error( + "Error: .env file not found.\n" + + "Copy .env.example to .env in the repository root and configure your OpenAI or Azure OpenAI credentials." + ); + process.exit(1); +} dotenv.config({ path: dotEnvPath }); const model = createLanguageModel(process.env); diff --git a/typescript/examples/crossword/src/main.ts b/typescript/examples/crossword/src/main.ts index 77213a24..79d6a053 100644 --- a/typescript/examples/crossword/src/main.ts +++ b/typescript/examples/crossword/src/main.ts @@ -1,4 +1,3 @@ -import assert from "assert"; import dotenv from "dotenv"; import findConfig from "find-config"; import fs from "fs"; @@ -10,7 +9,13 @@ import { CrosswordActions } from "./crosswordSchema"; import { createCrosswordActionTranslator } from "./translator"; const dotEnvPath = findConfig(".env"); -assert(dotEnvPath, ".env file not found!"); +if (!dotEnvPath) { + console.error( + "Error: .env file not found.\n" + + "Copy .env.example to .env in the repository root and configure your OpenAI or Azure OpenAI credentials." + ); + process.exit(1); +} dotenv.config({ path: dotEnvPath }); const model = createLanguageModel(process.env); diff --git a/typescript/examples/drawing/src/main.ts b/typescript/examples/drawing/src/main.ts index bab1a0bd..8ca0cc05 100644 --- a/typescript/examples/drawing/src/main.ts +++ b/typescript/examples/drawing/src/main.ts @@ -1,4 +1,3 @@ -import assert from "assert"; import dotenv from "dotenv"; import findConfig from "find-config"; import fs from "fs"; @@ -10,7 +9,13 @@ import { Drawing } from "./drawingSchema"; import { renderDrawingToSvg } from "./render"; const dotEnvPath = findConfig(".env"); -assert(dotEnvPath, ".env file not found!"); +if (!dotEnvPath) { + console.error( + "Error: .env file not found.\n" + + "Copy .env.example to .env in the repository root and configure your OpenAI or Azure OpenAI credentials." + ); + process.exit(1); +} dotenv.config({ path: dotEnvPath }); const model = createLanguageModel(process.env); diff --git a/typescript/examples/healthData/src/main.ts b/typescript/examples/healthData/src/main.ts index fe3e134e..46032398 100644 --- a/typescript/examples/healthData/src/main.ts +++ b/typescript/examples/healthData/src/main.ts @@ -1,4 +1,3 @@ -import assert from "assert"; import dotenv from "dotenv"; import findConfig from "find-config"; import fs from "fs"; @@ -9,7 +8,13 @@ import { HealthDataResponse } from "./healthDataSchema"; import { createHealthDataTranslator } from "./translator"; const dotEnvPath = findConfig(".env"); -assert(dotEnvPath, ".env file not found!"); +if (!dotEnvPath) { + console.error( + "Error: .env file not found.\n" + + "Copy .env.example to .env in the repository root and configure your OpenAI or Azure OpenAI credentials." + ); + process.exit(1); +} dotenv.config({ path: dotEnvPath }); const healthInstructions = ` diff --git a/typescript/examples/math/src/main.ts b/typescript/examples/math/src/main.ts index cda811c3..f79895ba 100644 --- a/typescript/examples/math/src/main.ts +++ b/typescript/examples/math/src/main.ts @@ -1,4 +1,3 @@ -import assert from "assert"; import dotenv from "dotenv"; import findConfig from "find-config"; import fs from "fs"; @@ -8,7 +7,13 @@ import { processRequests } from "typechat/interactive"; import { createModuleTextFromProgram, createProgramTranslator, evaluateJsonProgram } from "typechat/ts"; const dotEnvPath = findConfig(".env"); -assert(dotEnvPath, ".env file not found!"); +if (!dotEnvPath) { + console.error( + "Error: .env file not found.\n" + + "Copy .env.example to .env in the repository root and configure your OpenAI or Azure OpenAI credentials." + ); + process.exit(1); +} dotenv.config({ path: dotEnvPath }); const model = createLanguageModel(process.env); diff --git a/typescript/examples/multiSchema/src/main.ts b/typescript/examples/multiSchema/src/main.ts index 8820a616..a265d733 100644 --- a/typescript/examples/multiSchema/src/main.ts +++ b/typescript/examples/multiSchema/src/main.ts @@ -1,4 +1,3 @@ -import assert from "assert"; import dotenv from "dotenv"; import findConfig from "find-config"; import fs from "fs"; @@ -9,7 +8,13 @@ import { createJsonMathAgent, createJsonPrintAgent } from "./agent"; import { createAgentRouter } from "./router"; const dotEnvPath = findConfig(".env"); -assert(dotEnvPath, ".env file not found!"); +if (!dotEnvPath) { + console.error( + "Error: .env file not found.\n" + + "Copy .env.example to .env in the repository root and configure your OpenAI or Azure OpenAI credentials." + ); + process.exit(1); +} dotenv.config({ path: dotEnvPath }); const model = createLanguageModel(process.env); diff --git a/typescript/examples/restaurant/src/main.ts b/typescript/examples/restaurant/src/main.ts index fd95e89b..c355bb5d 100644 --- a/typescript/examples/restaurant/src/main.ts +++ b/typescript/examples/restaurant/src/main.ts @@ -1,4 +1,3 @@ -import assert from "assert"; import dotenv from "dotenv"; import findConfig from "find-config"; import fs from "fs"; @@ -16,7 +15,13 @@ import { import { Order } from "./foodOrderViewSchema"; const dotEnvPath = findConfig(".env"); -assert(dotEnvPath, ".env file not found!"); +if (!dotEnvPath) { + console.error( + "Error: .env file not found.\n" + + "Copy .env.example to .env in the repository root and configure your OpenAI or Azure OpenAI credentials." + ); + process.exit(1); +} dotenv.config({ path: dotEnvPath }); const model = createLanguageModel(process.env); diff --git a/typescript/examples/sentiment-zod/src/main.ts b/typescript/examples/sentiment-zod/src/main.ts index d52a3795..51b61ad5 100644 --- a/typescript/examples/sentiment-zod/src/main.ts +++ b/typescript/examples/sentiment-zod/src/main.ts @@ -1,4 +1,3 @@ -import assert from "assert"; import dotenv from "dotenv"; import findConfig from "find-config"; import { createJsonTranslator, createLanguageModel } from "typechat"; @@ -7,7 +6,13 @@ import { createZodJsonValidator } from "typechat/zod"; import { SentimentSchema } from "./sentimentSchema"; const dotEnvPath = findConfig(".env"); -assert(dotEnvPath, ".env file not found!"); +if (!dotEnvPath) { + console.error( + "Error: .env file not found.\n" + + "Copy .env.example to .env in the repository root and configure your OpenAI or Azure OpenAI credentials." + ); + process.exit(1); +} dotenv.config({ path: dotEnvPath }); const model = createLanguageModel(process.env); diff --git a/typescript/examples/sentiment/src/main.ts b/typescript/examples/sentiment/src/main.ts index 4a7590e4..d80e71c0 100644 --- a/typescript/examples/sentiment/src/main.ts +++ b/typescript/examples/sentiment/src/main.ts @@ -1,4 +1,3 @@ -import assert from "assert"; import dotenv from "dotenv"; import findConfig from "find-config"; import fs from "fs"; @@ -9,7 +8,13 @@ import { createTypeScriptJsonValidator } from "typechat/ts"; import { SentimentResponse } from "./sentimentSchema"; const dotEnvPath = findConfig(".env"); -assert(dotEnvPath, ".env file not found!"); +if (!dotEnvPath) { + console.error( + "Error: .env file not found.\n" + + "Copy .env.example to .env in the repository root and configure your OpenAI or Azure OpenAI credentials." + ); + process.exit(1); +} dotenv.config({ path: dotEnvPath }); const model = createLanguageModel(process.env); diff --git a/typescript/package.json b/typescript/package.json index dd10ea6b..1654f47e 100644 --- a/typescript/package.json +++ b/typescript/package.json @@ -21,7 +21,7 @@ }, "scripts": { "build": "tsc -p src", - "test": "npm run build && tsc -p test && node --test out/validate.test.js out/zod.test.js out/program.test.js tests/model.test.mjs", + "test": "npm run build && tsc -p test && node --test out/validate.test.js out/zod.test.js out/program.test.js tests/model.test.mjs tests/examples.test.mjs", "build-all": "npm run build --workspaces", "prepare": "npm run build-all", "prepublishOnly": "node -e \"require('fs').copyFileSync('../SECURITY.md','SECURITY.md')\"", diff --git a/typescript/tests/examples.test.mjs b/typescript/tests/examples.test.mjs new file mode 100644 index 00000000..c581b2c7 --- /dev/null +++ b/typescript/tests/examples.test.mjs @@ -0,0 +1,77 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { readFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import { dirname, join } from "node:path"; +import { describe, test } from "node:test"; +import { fileURLToPath } from "node:url"; + +const examplesDir = join(dirname(fileURLToPath(import.meta.url)), "..", "examples"); +const examples = [ + "calendar", + "coffeeShop", + "coffeeShop-zod", + "crossword", + "drawing", + "healthData", + "math", + "multiSchema", + "restaurant", + "sentiment", + "sentiment-zod", +]; +const missingEnvMessage = "Error: .env file not found.\n" + + "Copy .env.example to .env in the repository root and configure your OpenAI or Azure OpenAI credentials.\n"; + +function runStartup(source, dotEnvPath) { + return spawnSync(process.execPath, ["-"], { + input: ` + const { isBuiltin } = require("node:module"); + const { runInNewContext } = require("node:vm"); + runInNewContext(${JSON.stringify(source)}, { + exports: {}, + require(name) { + if (isBuiltin(name)) return require(name); + if (name === "find-config") return () => ${JSON.stringify(dotEnvPath)}; + if (name === "dotenv") { + // Stop after loading configuration, before any model setup. + return { config({ path }) { console.log(path); process.exit(0); } }; + } + return {}; + }, + console, + process, + }); + `, + encoding: "utf8", + env: { ...process.env, NODE_OPTIONS: "", VSCODE_INSPECTOR_OPTIONS: "" }, + timeout: 10000, + }); +} + +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"), { + compilerOptions: { module: ts.ModuleKind.CommonJS, esModuleInterop: true }, + }).outputText; + + describe(`${example} environment setup`, () => { + test("reports missing .env without a stack trace and exits with status 1", () => { + const result = runStartup(source, null); + assert.ifError(result.error); + assert.equal(result.status, 1); + assert.equal(result.stdout, ""); + assert.equal(result.stderr, missingEnvMessage); + }); + + test("passes the discovered .env path to dotenv", () => { + const dotEnvPath = join(examplesDir, example, ".env"); + const result = runStartup(source, dotEnvPath); + assert.ifError(result.error); + assert.equal(result.status, 0); + assert.equal(result.stdout, `${dotEnvPath}\n`); + assert.equal(result.stderr, ""); + }); + }); +}