Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(internal): add internal helpers & improve build scripts #643

Merged
merged 1 commit into from
Jan 22, 2024
Merged
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
Binary file modified ecosystem-tests/bun/bun.lockb
Binary file not shown.
Binary file modified ecosystem-tests/bun/sample1.mp3
Binary file not shown.
Binary file modified ecosystem-tests/node-ts-cjs-auto/sample1.mp3
Binary file not shown.
Binary file modified ecosystem-tests/node-ts-cjs-web/sample1.mp3
Binary file not shown.
Binary file modified ecosystem-tests/node-ts-cjs/sample1.mp3
Binary file not shown.
Binary file modified ecosystem-tests/node-ts-esm-auto/sample1.mp3
Binary file not shown.
Binary file modified ecosystem-tests/node-ts-esm-web/sample1.mp3
Binary file not shown.
Binary file modified ecosystem-tests/node-ts-esm/sample1.mp3
Binary file not shown.
Binary file modified ecosystem-tests/node-ts4.5-jest27/sample1.mp3
Binary file not shown.
32 changes: 16 additions & 16 deletions helpers.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,20 +38,22 @@ as a string.
client.chat.completions.runTools({
model: 'gpt-3.5-turbo',
messages: [{ role: 'user', content: 'How is the weather this week?' }],
tools: [{
type: 'function',
function: {
function: getWeather as (args: { location: string, time: Date}) => any,
parse: parseFunction as (args: strings) => { location: string, time: Date },
parameters: {
type: 'object',
properties: {
location: { type: 'string' },
time: { type: 'string', format: 'date-time' },
tools: [
{
type: 'function',
function: {
function: getWeather as (args: { location: string; time: Date }) => any,
parse: parseFunction as (args: strings) => { location: string; time: Date },
parameters: {
type: 'object',
properties: {
location: { type: 'string' },
time: { type: 'string', format: 'date-time' },
},
},
},
}
}],
},
],
});
```

Expand Down Expand Up @@ -236,7 +238,6 @@ async function main() {
main();
```


### Integrate with `zod`

[`zod`](https://www.npmjs.com/package/zod) is a schema validation library which can help with validating the
Expand All @@ -261,8 +262,8 @@ async function main() {
function: getWeather,
parse: GetWeatherParameters.parse,
parameters: zodToJsonSchema(GetWeatherParameters),
}
}
},
},
],
})
.on('message', (message) => console.log(message));
Expand Down Expand Up @@ -293,4 +294,3 @@ See an example of a Next.JS integration here [`examples/stream-to-client-next.ts
### Proxy Streaming to a Browser

See an example of using express to stream to a browser here [`examples/stream-to-client-express.ts`](examples/stream-to-client-express.ts).

6 changes: 5 additions & 1 deletion scripts/fix-index-exports.cjs
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
const fs = require('fs');
const path = require('path');

const indexJs = path.resolve(__dirname, '..', 'dist', 'index.js');
const indexJs =
process.env['DIST_PATH'] ?
path.resolve(process.env['DIST_PATH'], 'index.js')
: path.resolve(__dirname, '..', 'dist', 'index.js');

let before = fs.readFileSync(indexJs, 'utf8');
let after = before.replace(
/^\s*exports\.default\s*=\s*(\w+)/m,
Expand Down
2 changes: 1 addition & 1 deletion scripts/make-dist-package-json.cjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const pkgJson = require('../package.json');
const pkgJson = require(process.env['PKG_JSON_PATH'] || '../package.json');

function processExportMap(m) {
for (const key in m) {
Expand Down
11 changes: 8 additions & 3 deletions scripts/postprocess-files.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@ const fs = require('fs');
const path = require('path');
const { parse } = require('@typescript-eslint/parser');

const distDir = path.resolve(__dirname, '..', 'dist');
const pkgImportPath = process.env['PKG_IMPORT_PATH'] ?? 'openai/'

const distDir =
process.env['DIST_PATH'] ?
path.resolve(process.env['DIST_PATH'])
: path.resolve(__dirname, '..', 'dist');
const distSrcDir = path.join(distDir, 'src');

/**
Expand Down Expand Up @@ -105,11 +110,11 @@ async function postprocess() {

let transformed = mapModulePaths(code, (importPath) => {
if (file.startsWith(distSrcDir)) {
if (importPath.startsWith('openai/')) {
if (importPath.startsWith(pkgImportPath)) {
// convert self-references in dist/src to relative paths
let relativePath = path.relative(
path.dirname(file),
path.join(distSrcDir, importPath.substring('openai/'.length)),
path.join(distSrcDir, importPath.substring(pkgImportPath.length)),
);
if (!relativePath.startsWith('.')) relativePath = `./${relativePath}`;
return relativePath;
Expand Down
11 changes: 11 additions & 0 deletions src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,11 @@ export abstract class APIClient {
return reqHeaders;
}

/**
* Used as a callback for mutating the given `FinalRequestOptions` object.
*/
protected async prepareOptions(options: FinalRequestOptions): Promise<void> {}

/**
* Used as a callback for mutating the given `RequestInit` object.
*
Expand Down Expand Up @@ -387,6 +392,8 @@ export abstract class APIClient {
retriesRemaining = options.maxRetries ?? this.maxRetries;
}

await this.prepareOptions(options);

const { req, url, timeout } = this.buildRequest(options);

await this.prepareRequest(req, { url, options });
Expand Down Expand Up @@ -1139,3 +1146,7 @@ export const toBase64 = (str: string | null | undefined): string => {

throw new OpenAIError('Cannot generate b64 string; Expected `Buffer` or `btoa` to be defined');
};

export function isObj(obj: unknown): obj is Record<string, unknown> {
return obj != null && typeof obj === 'object' && !Array.isArray(obj);
}