diff --git a/README.md b/README.md index e390eed..565bf86 100644 --- a/README.md +++ b/README.md @@ -38,11 +38,13 @@ instance when you are done. ## Global Options When creating a `GTPScript` instance, you can pass the following global options. These options are also available as -run `Options`. Anything specified as a run option will take precedence over the global option. +run `Options`. Except `Env`, anything specified as a run option will take precedence over the global +option. Any `env` provided in the run options are appended. - `APIKey`: Specify an OpenAI API key for authenticating requests - `BaseURL`: A base URL for an OpenAI compatible API (the default is `https://api.openai.com/v1`) - `DefaultModel`: The default model to use for OpenAI requests +- `Env`: Replace the system's environment variables with these in the for `KEY=VAL` ## Run Options diff --git a/src/gptscript.ts b/src/gptscript.ts index acd92d4..a83b64b 100644 --- a/src/gptscript.ts +++ b/src/gptscript.ts @@ -8,25 +8,23 @@ export interface GlobalOpts { APIKey?: string BaseURL?: string DefaultModel?: string + Env?: string[] } -function globalOptsToArgs(opts?: GlobalOpts): string[] { - const args: string[] = [] +function globalOptsToEnv(env: NodeJS.ProcessEnv, opts?: GlobalOpts) { if (!opts) { - return args + return } if (opts.APIKey) { - args.push("--openai-api-key", opts.APIKey) + env["OPENAI_API_KEY"] = opts.APIKey } if (opts.BaseURL) { - args.push("--openai-base-url", opts.BaseURL) + env["OPENAI_BASE_URL"] = opts.BaseURL } if (opts.DefaultModel) { - args.push("--default-model", opts.DefaultModel) + env["GPTSCRIPT_DEFAULT_MODEL"] = opts.DefaultModel } - - return args } export interface RunOpts { @@ -83,10 +81,23 @@ export class GPTScript { GPTScript.serverURL = "http://" + u.hostname + ":" + String((s.address() as net.AddressInfo).port) srv.close() - const args = globalOptsToArgs(opts) - args.push("--listen-address", GPTScript.serverURL.replace("http://", ""), "sdkserver") - GPTScript.serverProcess = child_process.spawn(getCmdPath(), args, { - env: process.env, + let env = process.env + if (opts && opts.Env) { + env = {} + for (const v of opts.Env) { + const equalIndex = v.indexOf("=") + if (equalIndex === -1) { + env[v] = "" + } else { + env[v.substring(0, equalIndex)] = v.substring(equalIndex + 1) + } + } + } + + globalOptsToEnv(env, opts) + + GPTScript.serverProcess = child_process.spawn(getCmdPath(), ["--listen-address", GPTScript.serverURL.replace("http://", ""), "sdkserver"], { + env: env, stdio: ["pipe"] }) diff --git a/tests/gptscript.test.ts b/tests/gptscript.test.ts index 702e32c..e061a82 100644 --- a/tests/gptscript.test.ts +++ b/tests/gptscript.test.ts @@ -12,7 +12,7 @@ describe("gptscript module", () => { throw new Error("neither OPENAI_API_KEY nor GPTSCRIPT_URL is set") } - g = new gptscript.GPTScript({APIKey: process.env.GPTSCRIPT_API_KEY!}) + g = new gptscript.GPTScript({APIKey: process.env.OPENAI_API_KEY}) }) afterAll(() => { g.close()