From 3733b78475e0f1f1b408e4ae320c9fb7b1e99e2e Mon Sep 17 00:00:00 2001 From: csgulati09 Date: Mon, 23 Sep 2024 15:54:18 +0530 Subject: [PATCH 1/5] feat: linting and prettier added and changes make --- .eslintrc.js | 19 +- .prettierrc.json | 11 + package.json | 6 +- src/_types/generalTypes.ts | 62 +- src/_types/portkeyConstructs.ts | 76 +- src/apiResource.ts | 20 +- src/apis/assistants.ts | 262 +++---- src/apis/audio.ts | 124 ++-- src/apis/batches.ts | 150 ++-- src/apis/betaChat.ts | 64 +- src/apis/chatCompletions.ts | 173 ++--- src/apis/completions.ts | 134 ++-- src/apis/createHeaders.ts | 61 +- src/apis/embeddings.ts | 54 +- src/apis/feedback.ts | 92 +-- src/apis/files.ts | 51 +- src/apis/fineTuning.ts | 279 ++++---- src/apis/generations.ts | 247 +++---- src/apis/images.ts | 50 +- src/apis/index.ts | 38 +- src/apis/models.ts | 21 +- src/apis/moderations.ts | 52 +- src/apis/postMethod.ts | 85 +-- src/apis/threads.ts | 1150 ++++++++++++++++--------------- src/apis/uploads.ts | 69 +- src/apis/vectorStores.ts | 700 ++++++++++--------- src/baseClient.ts | 419 ++++++----- src/client.ts | 313 +++++---- src/constants.ts | 39 +- src/error.ts | 200 +++--- src/index.ts | 10 +- src/streaming.ts | 528 +++++++------- src/utils.ts | 222 +++--- src/version.ts | 2 +- 34 files changed, 3031 insertions(+), 2752 deletions(-) create mode 100644 .prettierrc.json diff --git a/.eslintrc.js b/.eslintrc.js index 21f9477..64785bc 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -7,7 +7,24 @@ module.exports = { "plugin:@typescript-eslint/recommended", "prettier", ], + ignorePatterns: [ + '**/node_modules/', + '**/dist/', + '**/*.test.js', + '**/examples/*', + '**/src/index.ts', + '**/src/error.ts', + '**/src/streaming.ts', + ], rules: { - 'no-unused-vars': 'off', + "no-case-declarations": "warn", + "no-console": "warn", + "no-duplicate-imports": "error", + "@typescript-eslint/no-unused-vars": "error", + "prefer-const": "error", + "@typescript-eslint/no-explicit-any": "off", + 'no-undef': 'off', + '@typescript-eslint/no-var-requires': 'off', + '@typescript-eslint/ban-ts-comment': 'off', } }; diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 0000000..febf915 --- /dev/null +++ b/.prettierrc.json @@ -0,0 +1,11 @@ +{ + "semi": true, + "tabWidth": 2, + "printWidth": 80, + "endOfLine": "lf", + "singleQuote": true, + "arrowParens": "always", + "bracketSpacing": true, + "trailingComma": "es5" +} + \ No newline at end of file diff --git a/package.json b/package.json index 3fc4be9..998e451 100644 --- a/package.json +++ b/package.json @@ -9,8 +9,10 @@ "scripts": { "test": "jest", "build": "bash ./build", - "lint": "eslint --ext ts,js .", - "fix": "eslint --fix --ext ts,js ." + "format:check": "prettier --check \"src/**/*.ts\"", + "format": "prettier --write \"src/**/*.ts\"", + "lint:check": "eslint --ext ts,js .", + "lint:fix": "eslint --fix --ext ts,js ." }, "imports": { "portkey-ai": ".", diff --git a/src/_types/generalTypes.ts b/src/_types/generalTypes.ts index afad375..49b9ac8 100644 --- a/src/_types/generalTypes.ts +++ b/src/_types/generalTypes.ts @@ -1,36 +1,36 @@ -export type Headers = Record +export type Headers = Record; export interface ApiClientInterface { - apiKey?: string | null; - baseURL?: string | null; - virtualKey?: string | null | undefined; - config?: Record | string | null | undefined; - provider?: string | null | undefined; - traceID?: string | null | undefined; - metadata?: Record | null | undefined; - Authorization?: string | null | undefined; - cacheForceRefresh?: boolean | null | undefined; - debug?: boolean | null | undefined; - customHost?: string | null | undefined; - openaiProject?: string | null | undefined; - openaiOrganization?: string | null | undefined; - awsSecretAccessKey?: string | null | undefined; - awsAccessKeyId?: string | null | undefined; - awsSessionToken?: string | null | undefined; - awsRegion?: string | null | undefined; - vertexProjectId?: string | null | undefined; - vertexRegion?: string | null | undefined; - workersAiAccountId?: string | null | undefined; - azureResourceName?: string | null | undefined; - azureDeploymentId?: string | null | undefined; - azureApiVersion?: string | null | undefined; - huggingfaceBaseUrl?: string | null | undefined; - forwardHeaders?: Array | null | undefined; - cacheNamespace?: string | null | undefined; - requestTimeout?: number | null | undefined; - strictOpenAiCompliance?: boolean | null | undefined; + apiKey?: string | null; + baseURL?: string | null; + virtualKey?: string | null | undefined; + config?: Record | string | null | undefined; + provider?: string | null | undefined; + traceID?: string | null | undefined; + metadata?: Record | null | undefined; + Authorization?: string | null | undefined; + cacheForceRefresh?: boolean | null | undefined; + debug?: boolean | null | undefined; + customHost?: string | null | undefined; + openaiProject?: string | null | undefined; + openaiOrganization?: string | null | undefined; + awsSecretAccessKey?: string | null | undefined; + awsAccessKeyId?: string | null | undefined; + awsSessionToken?: string | null | undefined; + awsRegion?: string | null | undefined; + vertexProjectId?: string | null | undefined; + vertexRegion?: string | null | undefined; + workersAiAccountId?: string | null | undefined; + azureResourceName?: string | null | undefined; + azureDeploymentId?: string | null | undefined; + azureApiVersion?: string | null | undefined; + huggingfaceBaseUrl?: string | null | undefined; + forwardHeaders?: Array | null | undefined; + cacheNamespace?: string | null | undefined; + requestTimeout?: number | null | undefined; + strictOpenAiCompliance?: boolean | null | undefined; } export interface APIResponseType { - getHeaders: () => Record | null | undefined -} \ No newline at end of file + getHeaders: () => Record | null | undefined; +} diff --git a/src/_types/portkeyConstructs.ts b/src/_types/portkeyConstructs.ts index 12080e5..a3bcda1 100644 --- a/src/_types/portkeyConstructs.ts +++ b/src/_types/portkeyConstructs.ts @@ -1,50 +1,50 @@ export interface RetrySettings { - attempts: number; - on_status_codes: Array + attempts: number; + on_status_codes: Array; } -export interface Function { - name: string; - description: string; - parameters: string; +export interface FunctionInterface { + name: string; + description: string; + parameters: string; } export interface ModelParams { - model?: string; - suffix?: string; - max_tokens?: number; - temperature?: number; - top_k?: number; - top_p?: number; - n?: number; - stop_sequences?: Array; - timeout?: number; - functions?: Array; - function_call?: string | Function; - logprobs?: number; - echo?: boolean; - stop?: Array; - presence_penalty?: number; - frequency_penalty?: number; - best_of?: number; - logit_bias?: Record; - user?: string; - organization?: string; - seed?: number; - response_format?: any; - service_tier?: string; - top_logprobs?: number | null; - parallel_tool_calls?: boolean; - tools?: Array; - tool_choice?: any; + model?: string; + suffix?: string; + max_tokens?: number; + temperature?: number; + top_k?: number; + top_p?: number; + n?: number; + stop_sequences?: Array; + timeout?: number; + functions?: Array; + function_call?: string | FunctionInterface; + logprobs?: number; + echo?: boolean; + stop?: Array; + presence_penalty?: number; + frequency_penalty?: number; + best_of?: number; + logit_bias?: Record; + user?: string; + organization?: string; + seed?: number; + response_format?: any; + service_tier?: string; + top_logprobs?: number | null; + parallel_tool_calls?: boolean; + tools?: Array; + tool_choice?: any; } export interface Message { - role: string - content: string + role: string; + content: string; } export interface Tool { - type?: string; - function?: Record -} \ No newline at end of file + type?: string; + function?: Record; +} diff --git a/src/apiResource.ts b/src/apiResource.ts index 35b1db3..e788b90 100644 --- a/src/apiResource.ts +++ b/src/apiResource.ts @@ -1,13 +1,13 @@ -import type { Portkey } from "./index"; +import type { Portkey } from './index'; export class ApiResource { - protected client: Portkey; - protected post: Portkey["_post"] - protected put: Portkey["_put"] + protected client: Portkey; + protected post: Portkey['_post']; + protected put: Portkey['_put']; - constructor(client: Portkey) { - this.client = client - this.post = client._post.bind(client) - this.put = client._put.bind(client) - } -} \ No newline at end of file + constructor(client: Portkey) { + this.client = client; + this.post = client._post.bind(client); + this.put = client._put.bind(client); + } +} diff --git a/src/apis/assistants.ts b/src/apis/assistants.ts index 9dd01ec..c987065 100644 --- a/src/apis/assistants.ts +++ b/src/apis/assistants.ts @@ -1,158 +1,164 @@ -import { ApiClientInterface } from "../_types/generalTypes"; -import { ApiResource } from "../apiResource"; -import { RequestOptions } from "../baseClient"; -import { finalResponse, initOpenAIClient, overrideConfig } from "../utils"; -import { createHeaders } from "./createHeaders"; +import { ApiClientInterface } from '../_types/generalTypes'; +import { ApiResource } from '../apiResource'; +import { RequestOptions } from '../baseClient'; +import { finalResponse, initOpenAIClient, overrideConfig } from '../utils'; +import { createHeaders } from './createHeaders'; export interface AssistantCreateParams { - model: string; - description?: string | null; - instructions?: string | null; - metadata?: unknown | null; - name?: string | null; - tools?: Array; - response_format?: any | null; - temperature?: number | null; - tool_resources?: any | null; - top_p?: number | null; - + model: string; + description?: string | null; + instructions?: string | null; + metadata?: unknown | null; + name?: string | null; + tools?: Array; + response_format?: any | null; + temperature?: number | null; + tool_resources?: any | null; + top_p?: number | null; } export interface FileCreateParams { - file_id: string; + file_id: string; } export interface FileListParams extends CursorPageParams { - before?: string; - order?: string; + before?: string; + order?: string; } export interface CursorPageParams { - after?: string; - limit?: number; + after?: string; + limit?: number; } export interface AssistantListParams extends CursorPageParams { - before?: string; - order?: string; + before?: string; + order?: string; } export interface AssistantUpdateParams { - description?: string | null; - file_ids?: Array; - instructions?: string | null; - metadata?: unknown | null; - model?: string; - name?: string | null; - tools?: Array; + description?: string | null; + file_ids?: Array; + instructions?: string | null; + metadata?: unknown | null; + model?: string; + name?: string | null; + tools?: Array; } - export class Assistants extends ApiResource { - - async create( - _body: AssistantCreateParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - const body: AssistantCreateParams = _body; - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.beta.assistants.create(body, opts).withResponse(); - - return finalResponse(result); + async create( + _body: AssistantCreateParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + const body: AssistantCreateParams = _body; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async list( - _query?: AssistantListParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - const query: AssistantListParams | undefined = _query; - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore - const result = await OAIclient.beta.assistants.list(query, opts).withResponse(); - - return finalResponse(result); + const OAIclient = initOpenAIClient(this.client); + + const result = await OAIclient.beta.assistants + .create(body, opts) + .withResponse(); + + return finalResponse(result); + } + + async list( + _query?: AssistantListParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + const query: AssistantListParams | undefined = _query; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async retrieve( - assistantId: string, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.beta.assistants.retrieve(assistantId, opts).withResponse(); - - return finalResponse(result); + const OAIclient = initOpenAIClient(this.client); + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + const result = await OAIclient.beta.assistants + .list(query, opts) + .withResponse(); + + return finalResponse(result); + } + + async retrieve( + assistantId: string, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async update( - assistantId: string, - _body: AssistantUpdateParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - const body: AssistantUpdateParams = _body; - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.beta.assistants.update(assistantId, body, opts).withResponse(); - - return finalResponse(result); + const OAIclient = initOpenAIClient(this.client); + + const result = await OAIclient.beta.assistants + .retrieve(assistantId, opts) + .withResponse(); + + return finalResponse(result); + } + + async update( + assistantId: string, + _body: AssistantUpdateParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + const body: AssistantUpdateParams = _body; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async del( - assistantId: string, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.beta.assistants.del(assistantId, opts).withResponse(); - - return finalResponse(result); + const OAIclient = initOpenAIClient(this.client); + + const result = await OAIclient.beta.assistants + .update(assistantId, body, opts) + .withResponse(); + + return finalResponse(result); + } + + async del( + assistantId: string, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - + + const OAIclient = initOpenAIClient(this.client); + + const result = await OAIclient.beta.assistants + .del(assistantId, opts) + .withResponse(); + + return finalResponse(result); + } } diff --git a/src/apis/audio.ts b/src/apis/audio.ts index 77b4560..fcab948 100644 --- a/src/apis/audio.ts +++ b/src/apis/audio.ts @@ -1,11 +1,11 @@ -import { TranscriptionCreateParams } from "openai/resources/audio/transcriptions"; -import { ApiClientInterface } from "../_types/generalTypes"; -import { ApiResource } from "../apiResource"; -import { RequestOptions } from "../baseClient"; -import { finalResponse, initOpenAIClient, overrideConfig } from "../utils"; -import { createHeaders } from "./createHeaders"; -import { TranslationCreateParams } from "openai/resources/audio/translations"; -import { SpeechCreateParams } from "openai/resources/audio/speech"; +import { TranscriptionCreateParams } from 'openai/resources/audio/transcriptions'; +import { ApiClientInterface } from '../_types/generalTypes'; +import { ApiResource } from '../apiResource'; +import { RequestOptions } from '../baseClient'; +import { finalResponse, initOpenAIClient, overrideConfig } from '../utils'; +import { createHeaders } from './createHeaders'; +import { TranslationCreateParams } from 'openai/resources/audio/translations'; +import { SpeechCreateParams } from 'openai/resources/audio/speech'; export class Audio extends ApiResource { transcriptions: transcriptions; @@ -20,64 +20,66 @@ export class Audio extends ApiResource { } } -export class transcriptions extends ApiResource{ - async create( - _body: TranscriptionCreateParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - const body: TranscriptionCreateParams = _body; - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - const OAIclient = initOpenAIClient(this.client); - const response = await OAIclient.audio.transcriptions.create(body, opts).withResponse(); - return finalResponse(response); +export class transcriptions extends ApiResource { + async create( + _body: TranscriptionCreateParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + const body: TranscriptionCreateParams = _body; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } + const OAIclient = initOpenAIClient(this.client); + const response = await OAIclient.audio.transcriptions + .create(body, opts) + .withResponse(); + return finalResponse(response); + } } - -export class translations extends ApiResource{ - async create( - _body: TranslationCreateParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - const body: TranslationCreateParams = _body; - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - const OAIclient = initOpenAIClient(this.client); - const response = await OAIclient.audio.translations.create(body, opts).withResponse(); - return finalResponse(response); +export class translations extends ApiResource { + async create( + _body: TranslationCreateParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + const body: TranslationCreateParams = _body; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } + const OAIclient = initOpenAIClient(this.client); + const response = await OAIclient.audio.translations + .create(body, opts) + .withResponse(); + return finalResponse(response); + } } - -export class speech extends ApiResource{ - async create( - _body: SpeechCreateParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - const body: SpeechCreateParams = _body; - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - const OAIclient = initOpenAIClient(this.client); - const response = await OAIclient.audio.speech.create(body, opts); - return response; +export class speech extends ApiResource { + async create( + _body: SpeechCreateParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + const body: SpeechCreateParams = _body; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } + const OAIclient = initOpenAIClient(this.client); + const response = await OAIclient.audio.speech.create(body, opts); + return response; + } } diff --git a/src/apis/batches.ts b/src/apis/batches.ts index 9bc4245..8464bc1 100644 --- a/src/apis/batches.ts +++ b/src/apis/batches.ts @@ -1,90 +1,92 @@ -import { BatchCreateParams, BatchListParams } from "openai/resources/batches"; -import { ApiClientInterface } from "../_types/generalTypes"; -import { ApiResource } from "../apiResource"; -import { RequestOptions } from "../baseClient"; -import { finalResponse, initOpenAIClient, overrideConfig } from "../utils"; -import { createHeaders } from "./createHeaders"; +import { BatchCreateParams, BatchListParams } from 'openai/resources/batches'; +import { ApiClientInterface } from '../_types/generalTypes'; +import { ApiResource } from '../apiResource'; +import { RequestOptions } from '../baseClient'; +import { finalResponse, initOpenAIClient, overrideConfig } from '../utils'; +import { createHeaders } from './createHeaders'; -export class Batches extends ApiResource{ +export class Batches extends ApiResource { + async create( + _body: BatchCreateParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + const body: BatchCreateParams = _body; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; + } - async create( - _body: BatchCreateParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - const body: BatchCreateParams = _body; - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } + const OAIclient = initOpenAIClient(this.client); - const OAIclient = initOpenAIClient(this.client); + const result = await OAIclient.batches.create(body, opts).withResponse(); + return finalResponse(result); + } - const result = await OAIclient.batches.create(body, opts).withResponse(); - return finalResponse(result); + async retrieve( + batchId: string, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async retrieve( - batchId: string, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } + const OAIclient = initOpenAIClient(this.client); - const OAIclient = initOpenAIClient(this.client); + const result = await OAIclient.batches + .retrieve(batchId, opts) + .withResponse(); + return finalResponse(result); + } - const result = await OAIclient.batches.retrieve(batchId, opts).withResponse(); - return finalResponse(result); + async list( + _query?: BatchListParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + const query: BatchListParams | undefined = _query; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async list( - _query?: BatchListParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - const query: BatchListParams | undefined = _query; - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } + const OAIclient = initOpenAIClient(this.client); - const OAIclient = initOpenAIClient(this.client); + const result = await OAIclient.batches.list(query, opts).withResponse(); + return finalResponse(result); + } - const result = await OAIclient.batches.list(query, opts).withResponse(); - return finalResponse(result); + async cancel( + batchId: string, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async cancel( - batchId: string, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - const body = {} - const options = { body, ...opts } + const OAIclient = initOpenAIClient(this.client); + const body = {}; + const options = { body, ...opts }; - const result = await OAIclient.batches.cancel(batchId, options).withResponse(); - return finalResponse(result); - } + const result = await OAIclient.batches + .cancel(batchId, options) + .withResponse(); + return finalResponse(result); + } } - diff --git a/src/apis/betaChat.ts b/src/apis/betaChat.ts index 998474f..ac58edf 100644 --- a/src/apis/betaChat.ts +++ b/src/apis/betaChat.ts @@ -1,19 +1,18 @@ -import { ChatCompletionStreamParams } from "openai/lib/ChatCompletionStream"; -import { ApiClientInterface } from "../_types/generalTypes"; -import { ApiResource } from "../apiResource"; -import { RequestOptions } from "../baseClient"; -import { initOpenAIClient, overrideConfig } from "../utils"; -import { createHeaders } from "./createHeaders"; +import { ChatCompletionStreamParams } from 'openai/lib/ChatCompletionStream'; +import { ApiClientInterface } from '../_types/generalTypes'; +import { ApiResource } from '../apiResource'; +import { RequestOptions } from '../baseClient'; +import { initOpenAIClient, overrideConfig } from '../utils'; +import { createHeaders } from './createHeaders'; import { ChatCompletionFunctionRunnerParams, ChatCompletionToolRunnerParams, -} from "openai/lib/ChatCompletionRunner"; +} from 'openai/lib/ChatCompletionRunner'; import { ChatCompletionStreamingFunctionRunnerParams, ChatCompletionStreamingToolRunnerParams, -} from "openai/lib/ChatCompletionStreamingRunner"; -import { ChatCompletionParseParams } from "openai/resources/beta/chat/completions"; -import { ExtractParsedContentFromParams } from "openai/lib/parser"; +} from 'openai/lib/ChatCompletionStreamingRunner'; +import { ChatCompletionParseParams } from 'openai/resources/beta/chat/completions'; export class BetaChat extends ApiResource { completions: Completions; @@ -25,15 +24,13 @@ export class BetaChat extends ApiResource { } export class Completions extends ApiResource { - - async parse> - ( + async parse( _body: Params, params?: ApiClientInterface, opts?: RequestOptions ): Promise { const body: Params = _body; - + if (params) { const config = overrideConfig(this.client.config, params.config); this.client.customHeaders = { @@ -47,7 +44,7 @@ export class Completions extends ApiResource { const result = await OAIclient.beta.chat.completions.parse(body, opts); return result; } - + async runFunctions( body: ChatCompletionFunctionRunnerParams, params?: ApiClientInterface, @@ -60,7 +57,7 @@ export class Completions extends ApiResource { ): Promise; async runFunctions( _body: - ChatCompletionFunctionRunnerParams + | ChatCompletionFunctionRunnerParams | ChatCompletionStreamingFunctionRunnerParams, params?: ApiClientInterface, opts?: RequestOptions @@ -86,12 +83,12 @@ export class Completions extends ApiResource { async runTools( body: ChatCompletionToolRunnerParams, params?: ApiClientInterface, - opts?: RequestOptions, + opts?: RequestOptions ): Promise; async runTools( body: ChatCompletionStreamingToolRunnerParams, params?: ApiClientInterface, - opts?: RequestOptions, + opts?: RequestOptions ): Promise; async runTools( _body: @@ -116,23 +113,24 @@ export class Completions extends ApiResource { } async stream( - _body:ChatCompletionStreamParams, + _body: ChatCompletionStreamParams, params?: ApiClientInterface, - opts?: RequestOptions): Promise { - const body: ChatCompletionStreamParams = _body; - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.beta.chat.completions.stream(body, opts); - return result; + opts?: RequestOptions + ): Promise { + const body: ChatCompletionStreamParams = _body; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } + + const OAIclient = initOpenAIClient(this.client); + + const result = await OAIclient.beta.chat.completions.stream(body, opts); + return result; + } } export type BaseFunctionsArgs = readonly (object | string)[]; diff --git a/src/apis/chatCompletions.ts b/src/apis/chatCompletions.ts index 1f6cf95..e50a888 100644 --- a/src/apis/chatCompletions.ts +++ b/src/apis/chatCompletions.ts @@ -1,114 +1,119 @@ -import { ChatCompletionMessageToolCall, ChatCompletionStreamOptions, ChatCompletionTokenLogprob } from "openai/resources/chat/completions"; -import { APIResponseType, ApiClientInterface } from "../_types/generalTypes"; -import { ModelParams } from "../_types/portkeyConstructs"; -import { ApiResource } from "../apiResource"; -import { APIPromise, RequestOptions } from "../baseClient"; -import { CHAT_COMPLETE_API } from "../constants"; -import { Stream } from "../streaming"; -import { overrideConfig } from "../utils"; -import { createHeaders } from "./createHeaders"; +import { + ChatCompletionMessageToolCall, + ChatCompletionStreamOptions, + ChatCompletionTokenLogprob, +} from 'openai/resources/chat/completions'; +import { APIResponseType, ApiClientInterface } from '../_types/generalTypes'; +import { ModelParams } from '../_types/portkeyConstructs'; +import { ApiResource } from '../apiResource'; +import { APIPromise, RequestOptions } from '../baseClient'; +import { CHAT_COMPLETE_API } from '../constants'; +import { Stream } from '../streaming'; +import { overrideConfig } from '../utils'; +import { createHeaders } from './createHeaders'; export class Chat extends ApiResource { - completions: ChatCompletions = new ChatCompletions(this.client); + completions: ChatCompletions = new ChatCompletions(this.client); } class ChatCompletions extends ApiResource { - create( - _body: ChatCompletionsBodyNonStreaming, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise; - create( - _body: ChatCompletionsBodyStreaming, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise>; - create( - _body: ChatCompletionsBodyBase, - params?: ApiClientInterface, - opts?: RequestOptions, - ): APIPromise | ChatCompletion>; - create( - _body: ChatCompletionCreateParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise | APIPromise> { - const body = _body - // If config is present then override it. - if (params) { - const config = overrideConfig(this.client.config, params.config) - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params, config }) } - } - - - const stream = _body.stream ?? false - return this.post(CHAT_COMPLETE_API, { body, ...opts, stream }) as - | APIPromise - | APIPromise> + create( + _body: ChatCompletionsBodyNonStreaming, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise; + create( + _body: ChatCompletionsBodyStreaming, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise>; + create( + _body: ChatCompletionsBodyBase, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise | ChatCompletion>; + create( + _body: ChatCompletionCreateParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise | APIPromise> { + const body = _body; + // If config is present then override it. + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } + + const stream = _body.stream ?? false; + return this.post(CHAT_COMPLETE_API, { + body, + ...opts, + stream, + }) as APIPromise | APIPromise>; + } } export interface ChatCompletionsBodyBase extends ModelParams { - messages?: Array; - response_format?: object; + messages?: Array; + response_format?: object; } export interface ChatCompletionsBodyStreaming extends ChatCompletionsBodyBase { - stream?: true; - stream_options?: ChatCompletionStreamOptions + stream?: true; + stream_options?: ChatCompletionStreamOptions; } -export interface ChatCompletionsBodyNonStreaming extends ChatCompletionsBodyBase { - stream?: false; +export interface ChatCompletionsBodyNonStreaming + extends ChatCompletionsBodyBase { + stream?: false; } -export type ChatCompletionCreateParams = ChatCompletionsBodyNonStreaming | ChatCompletionsBodyStreaming; +export type ChatCompletionCreateParams = + | ChatCompletionsBodyNonStreaming + | ChatCompletionsBodyStreaming; interface Usage { - prompt_tokens?: number; - completion_tokens?: number; - total_tokens?: number; - [key: string]: any; + prompt_tokens?: number; + completion_tokens?: number; + total_tokens?: number; + [key: string]: any; } -interface FunctionType { - arguments?: string; - name?: string; - [key: string]: any; - } - interface Message { - role: string; - content: string; - refusal?: string; - function_call?: any; - tool_calls?: Array; - tool_call_id?: string; + role: string; + content: string; + refusal?: string; + function_call?: any; + tool_calls?: Array; + tool_call_id?: string; } export interface Logprobs { - content: Array | null; - refusal: Array | null; - [key: string]: any; + content: Array | null; + refusal: Array | null; + [key: string]: any; } interface Choices { - index?: number; - message?: Message; - delta?: Message; - finish_reason?: string; - logprobs?: Logprobs - [key: string]: any; + index?: number; + message?: Message; + delta?: Message; + finish_reason?: string; + logprobs?: Logprobs; + [key: string]: any; } interface ChatCompletion extends APIResponseType { - id: string; - object: string; - created: number; - model: string; - choices: Array; - usage: Usage; - service_tier?: string; - system_fingerprint?: string; - [key: string]: any; -} \ No newline at end of file + id: string; + object: string; + created: number; + model: string; + choices: Array; + usage: Usage; + service_tier?: string; + system_fingerprint?: string; + [key: string]: any; +} diff --git a/src/apis/completions.ts b/src/apis/completions.ts index ae40037..df66f63 100644 --- a/src/apis/completions.ts +++ b/src/apis/completions.ts @@ -1,92 +1,96 @@ -import { APIResponseType, ApiClientInterface } from "../_types/generalTypes"; -import { ModelParams } from "../_types/portkeyConstructs"; -import { ApiResource } from "../apiResource"; -import { APIPromise, RequestOptions } from "../baseClient"; -import { TEXT_COMPLETE_API } from "../constants"; -import { Stream } from "../streaming"; -import { overrideConfig } from "../utils"; -import { createHeaders } from "./createHeaders"; +import { APIResponseType, ApiClientInterface } from '../_types/generalTypes'; +import { ModelParams } from '../_types/portkeyConstructs'; +import { ApiResource } from '../apiResource'; +import { APIPromise, RequestOptions } from '../baseClient'; +import { TEXT_COMPLETE_API } from '../constants'; +import { Stream } from '../streaming'; +import { overrideConfig } from '../utils'; +import { createHeaders } from './createHeaders'; export class Completions extends ApiResource { - create( - _body: CompletionsBodyNonStreaming, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise; - create( - _body: CompletionsBodyStreaming, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise> - create( - _body: CompletionsBodyBase, - params?: ApiClientInterface, - opts?: RequestOptions, - ): APIPromise | TextCompletion>; - create( - _body: CompletionCreateParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise | APIPromise> { - const body = _body - // If config is present then override it. - if (params) { - const config = overrideConfig(this.client.config, params.config) - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params, config }) } - } - const stream = _body.stream ?? false - - this.client.responseHeaders - return this.post(TEXT_COMPLETE_API, { body, ...opts, stream }) as - | APIPromise - | APIPromise> + create( + _body: CompletionsBodyNonStreaming, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise; + create( + _body: CompletionsBodyStreaming, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise>; + create( + _body: CompletionsBodyBase, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise | TextCompletion>; + create( + _body: CompletionCreateParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise | APIPromise> { + const body = _body; + // If config is present then override it. + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } -} + const stream = _body.stream ?? false; + this.client.responseHeaders; + return this.post(TEXT_COMPLETE_API, { body, ...opts, stream }) as + | APIPromise + | APIPromise>; + } +} export interface CompletionsBodyBase extends ModelParams { - prompt: string; + prompt: string; } export interface CompletionsBodyStreaming extends CompletionsBodyBase { - stream?: true; + stream?: true; } export interface CompletionsBodyNonStreaming extends CompletionsBodyBase { - stream?: false; + stream?: false; } -export type CompletionCreateParams = CompletionsBodyNonStreaming | CompletionsBodyStreaming; +export type CompletionCreateParams = + | CompletionsBodyNonStreaming + | CompletionsBodyStreaming; interface Usage { - prompt_tokens?: number; - completion_tokens?: number; - total_tokens?: number; + prompt_tokens?: number; + completion_tokens?: number; + total_tokens?: number; } interface Logprobs { - text_offset?: Array; + text_offset?: Array; - token_logprobs?: Array; + token_logprobs?: Array; - tokens?: Array; + tokens?: Array; - top_logprobs?: Array>; - } + top_logprobs?: Array>; +} interface Choices { - index?: number; - text?: string; - logprobs: Logprobs; - finish_reason?: string; + index?: number; + text?: string; + logprobs: Logprobs; + finish_reason?: string; } interface TextCompletion extends APIResponseType { - id: string; - object: string; - created: number; - model: string; - choices: Array; - usage?: Usage; - system_fingerprint?: string; -} \ No newline at end of file + id: string; + object: string; + created: number; + model: string; + choices: Array; + usage?: Usage; + system_fingerprint?: string; +} diff --git a/src/apis/createHeaders.ts b/src/apis/createHeaders.ts index 54b9bc2..d1bbdf9 100644 --- a/src/apis/createHeaders.ts +++ b/src/apis/createHeaders.ts @@ -1,36 +1,37 @@ -import { getPortkeyHeader, isEmpty } from "../utils" +import { getPortkeyHeader, isEmpty } from '../utils'; -export const createHeaders = (config: Record): Record => { - const headers: Record = {} +export const createHeaders = ( + config: Record +): Record => { + const headers: Record = {}; - for (let k in config) { - let v = config[k]; - if (isEmpty(v)) continue; + for (let k in config) { + let v = config[k]; + if (isEmpty(v)) continue; - // convert to snakecase - if (k.toLocaleLowerCase() === "authorization") { - headers[k.toLowerCase()] = v || "" - continue - } + // convert to snakecase + if (k.toLocaleLowerCase() === 'authorization') { + headers[k.toLowerCase()] = v || ''; + continue; + } - // false logic (type is boolean, to handle flasy logic) - if (typeof v === "boolean") { - v = v.toString() - } + // false logic (type is boolean, to handle flasy logic) + if (typeof v === 'boolean') { + v = v.toString(); + } - // logic to handle forwardHeaders into a comma separated string - if (k === "forwardHeaders") { - v = v.join(',') - - } + // logic to handle forwardHeaders into a comma separated string + if (k === 'forwardHeaders') { + v = v.join(','); + } - k = k.replace('ID', 'Id') - .replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`) - if (!isEmpty(v) && typeof v == "object") { - v = JSON.stringify(v) - } - headers[getPortkeyHeader(k)] = v || "" - } - return headers - -} \ No newline at end of file + k = k + .replace('ID', 'Id') + .replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`); + if (!isEmpty(v) && typeof v == 'object') { + v = JSON.stringify(v); + } + headers[getPortkeyHeader(k)] = v || ''; + } + return headers; +}; diff --git a/src/apis/embeddings.ts b/src/apis/embeddings.ts index 51cd0ae..79fac60 100644 --- a/src/apis/embeddings.ts +++ b/src/apis/embeddings.ts @@ -1,32 +1,38 @@ -import { APIResponseType, ApiClientInterface } from "../_types/generalTypes"; -import { ModelParams } from "../_types/portkeyConstructs"; -import { ApiResource } from "../apiResource"; -import { APIPromise, RequestOptions } from "../baseClient"; -import { EMBEDDINGS_API } from "../constants"; -import { overrideConfig } from "../utils"; -import { createHeaders } from "./createHeaders"; +import { APIResponseType, ApiClientInterface } from '../_types/generalTypes'; +import { ModelParams } from '../_types/portkeyConstructs'; +import { ApiResource } from '../apiResource'; +import { APIPromise, RequestOptions } from '../baseClient'; +import { EMBEDDINGS_API } from '../constants'; +import { overrideConfig } from '../utils'; +import { createHeaders } from './createHeaders'; export interface EmbeddingsBody extends ModelParams { - input: string; - model?: string; - dimensions?: number; - encoding_format?: string; + input: string; + model?: string; + dimensions?: number; + encoding_format?: string; } -export type EmbeddingsResponse = Record & APIResponseType +export type EmbeddingsResponse = Record & APIResponseType; export class Embeddings extends ApiResource { - create( - _body: EmbeddingsBody, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise { - const body = _body - if (params) { - const config = overrideConfig(this.client.config, params.config) - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params, config }) } - } - const response = this.post(EMBEDDINGS_API, { body, ...opts }) - return response + create( + _body: EmbeddingsBody, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise { + const body = _body; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } + const response = this.post(EMBEDDINGS_API, { + body, + ...opts, + }); + return response; + } } diff --git a/src/apis/feedback.ts b/src/apis/feedback.ts index b77c814..08712d0 100644 --- a/src/apis/feedback.ts +++ b/src/apis/feedback.ts @@ -1,53 +1,65 @@ -import { APIResponseType, ApiClientInterface } from "../_types/generalTypes"; -import { ApiResource } from "../apiResource"; -import { APIPromise, RequestOptions } from "../baseClient"; -import { FEEDBACK_API } from "../constants"; -import { overrideConfig } from "../utils"; -import { createHeaders } from "./createHeaders"; +import { APIResponseType, ApiClientInterface } from '../_types/generalTypes'; +import { ApiResource } from '../apiResource'; +import { APIPromise, RequestOptions } from '../baseClient'; +import { FEEDBACK_API } from '../constants'; +import { overrideConfig } from '../utils'; +import { createHeaders } from './createHeaders'; interface FeedbackBodyBase { - traceID?: string; - feedbackID?: string; - value?: number; - weight?: number; - metadata?: Record + traceID?: string; + feedbackID?: string; + value?: number; + weight?: number; + metadata?: Record; } -type FeedbackBody = FeedbackBodyBase | Array +type FeedbackBody = FeedbackBodyBase | Array; export interface FeedbackResponse extends APIResponseType { - status: string; - message: string; - feedback_id: Array; + status: string; + message: string; + feedback_id: Array; } export class Feedback extends ApiResource { - create( - _body: FeedbackBody, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise { - const body = _body - if (params) { - const config = overrideConfig(this.client.config, params.config) - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params, config }) } - } - const response = this.post(FEEDBACK_API, { body, ...opts }) - return response + create( + _body: FeedbackBody, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise { + const body = _body; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } + const response = this.post(FEEDBACK_API, { + body, + ...opts, + }); + return response; + } - update( - _body: FeedbackBodyBase, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise { - const body = _body - const feedbackID = _body.feedbackID - if (params) { - const config = overrideConfig(this.client.config, params.config) - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params, config }) } - } - const response = this.put(FEEDBACK_API+'/'+feedbackID , { body, ...opts }) - return response + update( + _body: FeedbackBodyBase, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise { + const body = _body; + const feedbackID = _body.feedbackID; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } + const response = this.put( + FEEDBACK_API + '/' + feedbackID, + { body, ...opts } + ); + return response; + } } diff --git a/src/apis/files.ts b/src/apis/files.ts index 98009b9..566d47c 100644 --- a/src/apis/files.ts +++ b/src/apis/files.ts @@ -1,11 +1,10 @@ -import { ApiClientInterface } from "../_types/generalTypes"; -import { ApiResource } from "../apiResource"; -import { RequestOptions } from "../baseClient"; -import { finalResponse, initOpenAIClient, overrideConfig } from "../utils"; -import { createHeaders } from "./createHeaders"; +import { ApiClientInterface } from '../_types/generalTypes'; +import { ApiResource } from '../apiResource'; +import { RequestOptions } from '../baseClient'; +import { finalResponse, initOpenAIClient, overrideConfig } from '../utils'; +import { createHeaders } from './createHeaders'; export class MainFiles extends ApiResource { - async create( _body: FileCreateParams, params?: ApiClientInterface, @@ -20,8 +19,8 @@ export class MainFiles extends ApiResource { }; } - const OAIclient = initOpenAIClient(this.client); - + const OAIclient = initOpenAIClient(this.client); + // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore const result = await OAIclient.files.create(body, opts).withResponse(); @@ -43,7 +42,7 @@ export class MainFiles extends ApiResource { }; } - const OAIclient = initOpenAIClient(this.client); + const OAIclient = initOpenAIClient(this.client); const result = await OAIclient.files.list(query, opts).withResponse(); @@ -63,7 +62,7 @@ export class MainFiles extends ApiResource { }; } - const OAIclient = initOpenAIClient(this.client); + const OAIclient = initOpenAIClient(this.client); const result = await OAIclient.files.retrieve(fileId, opts).withResponse(); @@ -83,7 +82,7 @@ export class MainFiles extends ApiResource { }; } - const OAIclient = initOpenAIClient(this.client); + const OAIclient = initOpenAIClient(this.client); const result = await OAIclient.files.del(fileId, opts).withResponse(); @@ -109,7 +108,7 @@ export class MainFiles extends ApiResource { return finalResponse(result); } - + async retrieveContent( fileId: string, params?: ApiClientInterface, @@ -123,32 +122,30 @@ export class MainFiles extends ApiResource { }; } - const OAIclient = initOpenAIClient(this.client); + const OAIclient = initOpenAIClient(this.client); const result = await OAIclient.files.content(fileId, opts).withResponse(); return finalResponse(result); } - } - export interface FileCreateParams { - file: any; - purpose?: string; + file: any; + purpose?: string; } export interface FileObject { - id: string; - bytes?: number; - created_at?: number; - filename?: string; - object?: string; - purpose?: string; - status?: string; - status_details?: string; + id: string; + bytes?: number; + created_at?: number; + filename?: string; + object?: string; + purpose?: string; + status?: string; + status_details?: string; } export interface FileListParams { - purpose?: string; - } \ No newline at end of file + purpose?: string; +} diff --git a/src/apis/fineTuning.ts b/src/apis/fineTuning.ts index 9efbf62..db76942 100644 --- a/src/apis/fineTuning.ts +++ b/src/apis/fineTuning.ts @@ -1,148 +1,163 @@ -import { JobCreateParams, JobListEventsParams, JobListParams } from "openai/resources/fine-tuning/jobs/jobs"; -import { ApiClientInterface } from "../_types/generalTypes"; -import { ApiResource } from "../apiResource"; -import { RequestOptions } from "../baseClient"; -import { finalResponse, initOpenAIClient, overrideConfig } from "../utils"; -import { createHeaders } from "./createHeaders"; -import { CheckpointListParams } from "openai/resources/fine-tuning/jobs/checkpoints"; - - -export class FineTuning extends ApiResource{ - jobs: Jobs; - constructor(client:any) { - super(client); - this.jobs = new Jobs(client); - } +import { + JobCreateParams, + JobListEventsParams, + JobListParams, +} from 'openai/resources/fine-tuning/jobs/jobs'; +import { ApiClientInterface } from '../_types/generalTypes'; +import { ApiResource } from '../apiResource'; +import { RequestOptions } from '../baseClient'; +import { finalResponse, initOpenAIClient, overrideConfig } from '../utils'; +import { createHeaders } from './createHeaders'; +import { CheckpointListParams } from 'openai/resources/fine-tuning/jobs/checkpoints'; + +export class FineTuning extends ApiResource { + jobs: Jobs; + constructor(client: any) { + super(client); + this.jobs = new Jobs(client); + } } export class Jobs extends ApiResource { - checkpoints: Checkpoints; - constructor(client:any) { - super(client); - this.checkpoints = new Checkpoints(client); + checkpoints: Checkpoints; + constructor(client: any) { + super(client); + this.checkpoints = new Checkpoints(client); + } + + async create( + _body: JobCreateParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + const body: JobCreateParams = _body; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async create( - _body: JobCreateParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - const body: JobCreateParams = _body; - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.fineTuning.jobs.create(body, opts).withResponse(); - return finalResponse(result); - } - - async retrieve( - fineTuningJobId: string, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.fineTuning.jobs.retrieve(fineTuningJobId, opts).withResponse(); - return finalResponse(result); + const OAIclient = initOpenAIClient(this.client); + + const result = await OAIclient.fineTuning.jobs + .create(body, opts) + .withResponse(); + return finalResponse(result); + } + + async retrieve( + fineTuningJobId: string, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async list( - _query?: JobListParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - const query: JobListParams | undefined = _query; - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.fineTuning.jobs.list(query, opts).withResponse(); - return finalResponse(result); + const OAIclient = initOpenAIClient(this.client); + + const result = await OAIclient.fineTuning.jobs + .retrieve(fineTuningJobId, opts) + .withResponse(); + return finalResponse(result); + } + + async list( + _query?: JobListParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + const query: JobListParams | undefined = _query; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async cancel( - fineTuningJobId: string, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - const body = {} - const options = { body, ...opts } - - const result = await OAIclient.fineTuning.jobs.cancel(fineTuningJobId, options).withResponse(); - return finalResponse(result); + const OAIclient = initOpenAIClient(this.client); + + const result = await OAIclient.fineTuning.jobs + .list(query, opts) + .withResponse(); + return finalResponse(result); + } + + async cancel( + fineTuningJobId: string, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async listEvents( - fineTuningJobId: string, - _query?: JobListEventsParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - const query: JobListEventsParams | undefined = _query; - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.fineTuning.jobs.listEvents(fineTuningJobId, query, opts).withResponse(); - return finalResponse(result); + const OAIclient = initOpenAIClient(this.client); + const body = {}; + const options = { body, ...opts }; + + const result = await OAIclient.fineTuning.jobs + .cancel(fineTuningJobId, options) + .withResponse(); + return finalResponse(result); + } + + async listEvents( + fineTuningJobId: string, + _query?: JobListEventsParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + const query: JobListEventsParams | undefined = _query; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } + + const OAIclient = initOpenAIClient(this.client); + + const result = await OAIclient.fineTuning.jobs + .listEvents(fineTuningJobId, query, opts) + .withResponse(); + return finalResponse(result); + } } export class Checkpoints extends ApiResource { - async list( - fineTuningJobId: string, - _query?: CheckpointListParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - const query: CheckpointListParams | undefined = _query; - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.fineTuning.jobs.checkpoints.list(fineTuningJobId, query, opts).withResponse(); - return finalResponse(result); + async list( + fineTuningJobId: string, + _query?: CheckpointListParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + const query: CheckpointListParams | undefined = _query; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } -} \ No newline at end of file + + const OAIclient = initOpenAIClient(this.client); + + const result = await OAIclient.fineTuning.jobs.checkpoints + .list(fineTuningJobId, query, opts) + .withResponse(); + return finalResponse(result); + } +} diff --git a/src/apis/generations.ts b/src/apis/generations.ts index f089a9d..c4398a9 100644 --- a/src/apis/generations.ts +++ b/src/apis/generations.ts @@ -1,152 +1,167 @@ -import { APIResponseType, ApiClientInterface } from "../_types/generalTypes"; -import { ModelParams } from "../_types/portkeyConstructs"; -import { ApiResource } from "../apiResource"; -import { APIPromise, RequestOptions } from "../baseClient"; -import { Stream } from "../streaming"; -import { overrideConfig } from "../utils"; -import { createHeaders } from "./createHeaders"; +import { APIResponseType, ApiClientInterface } from '../_types/generalTypes'; +import { ModelParams } from '../_types/portkeyConstructs'; +import { ApiResource } from '../apiResource'; +import { APIPromise, RequestOptions } from '../baseClient'; +import { Stream } from '../streaming'; +import { overrideConfig } from '../utils'; +import { createHeaders } from './createHeaders'; export class Generations extends ApiResource { - create( - _body: GenerationsBody, - opts?: RequestOptions - ): APIPromise { - const warning = "This API has been deprecated. Please use the Prompt API for the saved prompt." - console.warn(warning) - const body = { "variables": _body.variables } - return this.post(`/v1/prompts/${_body.promptID}/generate`, { body, ...opts }) - } + create( + _body: GenerationsBody, + opts?: RequestOptions + ): APIPromise { + const warning = + 'This API has been deprecated. Please use the Prompt API for the saved prompt.'; + console.warn(warning); // eslint-disable-line no-console + const body = { variables: _body.variables }; + return this.post(`/v1/prompts/${_body.promptID}/generate`, { + body, + ...opts, + }); + } } export interface GenerationsBody extends ModelParams { - promptID: string; - variables?: Record; + promptID: string; + variables?: Record; } export interface Generation extends APIResponseType { - success: boolean; - data: Record; + success: boolean; + data: Record; } export interface PromptBodyBase extends ModelParams { - promptID?: string; - variables?: Record; + promptID?: string; + variables?: Record; } export interface PromptsCreateStreaming extends PromptBodyBase { - stream?: true; + stream?: true; } export interface PromptsCreateNonStreaming extends PromptBodyBase { - stream?: false; + stream?: false; } export interface Functions { - name?: string; - description?: string; - parameters?: object; + name?: string; + description?: string; + parameters?: object; } -export interface Tool{ - function?: Functions; - type?: string; +export interface Tool { + function?: Functions; + type?: string; } export interface Messages { - content?: string; - role?: string; + content?: string; + role?: string; } - -export type PromptsCreateParams = PromptsCreateNonStreaming | PromptsCreateStreaming + +export type PromptsCreateParams = + | PromptsCreateNonStreaming + | PromptsCreateStreaming; type PromptsResponse = Record & APIResponseType; type PromptRenderResponse = { - success: boolean; - data: { - messages?: Messages[]; - prompt?: string; - model?: string; - stream?: boolean; - suffix?: string; - max_tokens?: number; - temperature?: number; - top_k?: number; - top_p?: number; - n?: number; - stop_sequences?: string[]; - functions?: Functions[]; - function_call?: string | Functions; - logprobs?: boolean; - top_logprobs?: number; - echo?: boolean; - stop?: string | string[]; - presence_penalty?: number; - frequency_penalty?: number; - best_of?: number; - logit_bias?: { [key: string]: number }; - user?: string; - organization?: string; - tool_choice?: string; - tools?: Tool[]; - response_format?: object; - seed?: number; - }; - } & APIResponseType; + success: boolean; + data: { + messages?: Messages[]; + prompt?: string; + model?: string; + stream?: boolean; + suffix?: string; + max_tokens?: number; + temperature?: number; + top_k?: number; + top_p?: number; + n?: number; + stop_sequences?: string[]; + functions?: Functions[]; + function_call?: string | Functions; + logprobs?: boolean; + top_logprobs?: number; + echo?: boolean; + stop?: string | string[]; + presence_penalty?: number; + frequency_penalty?: number; + best_of?: number; + logit_bias?: { [key: string]: number }; + user?: string; + organization?: string; + tool_choice?: string; + tools?: Tool[]; + response_format?: object; + seed?: number; + }; +} & APIResponseType; export class Prompt extends ApiResource { - completions: PromptCompletions = new PromptCompletions(this.client); - - render( - _body: PromptsCreateParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise { - const body = _body - const promptId = _body.promptID - - if (params) { - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params }) } - } - const response = this.post(`/prompts/${promptId}/render`, { body, ...opts }) - return response - } -} + completions: PromptCompletions = new PromptCompletions(this.client); + render( + _body: PromptsCreateParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise { + const body = _body; + const promptId = _body.promptID; + + if (params) { + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params }), + }; + } + const response = this.post( + `/prompts/${promptId}/render`, + { body, ...opts } + ); + return response; + } +} export class PromptCompletions extends ApiResource { - create( - _body: PromptsCreateNonStreaming, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise; - create( - _body: PromptsCreateStreaming, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise>; - create( - _body: PromptsCreateParams, - params?: ApiClientInterface, - opts?: RequestOptions, - ): APIPromise | PromptsResponse>; - create( - _body: PromptsCreateParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise | APIPromise> { - if (params) { - const config = overrideConfig(this.client.config, params.config) - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params, config }) } - } - const promptId = _body.promptID - const body = _body - const stream = _body.stream ?? false - delete body.promptID - body.stream = stream - const response = this.post(`/prompts/${promptId}/completions`, { body, ...opts, stream }) as - | APIPromise - | APIPromise> - return response - } + create( + _body: PromptsCreateNonStreaming, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise; + create( + _body: PromptsCreateStreaming, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise>; + create( + _body: PromptsCreateParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise | PromptsResponse>; + create( + _body: PromptsCreateParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise | APIPromise> { + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; + } + const promptId = _body.promptID; + const body = _body; + const stream = _body.stream ?? false; + delete body.promptID; + body.stream = stream; + const response = this.post( + `/prompts/${promptId}/completions`, + { body, ...opts, stream } + ) as APIPromise | APIPromise>; + return response; + } } diff --git a/src/apis/images.ts b/src/apis/images.ts index 189cd5b..46ed357 100644 --- a/src/apis/images.ts +++ b/src/apis/images.ts @@ -1,8 +1,8 @@ -import { ApiClientInterface } from "../_types/generalTypes"; -import { ApiResource } from "../apiResource"; -import { RequestOptions } from "../baseClient"; -import { finalResponse, initOpenAIClient, overrideConfig } from "../utils"; -import { createHeaders } from "./createHeaders"; +import { ApiClientInterface } from '../_types/generalTypes'; +import { ApiResource } from '../apiResource'; +import { RequestOptions } from '../baseClient'; +import { finalResponse, initOpenAIClient, overrideConfig } from '../utils'; +import { createHeaders } from './createHeaders'; export interface ImagesBody { prompt: string; @@ -16,23 +16,23 @@ export interface ImagesBody { } export interface ImageEditParams { - image: any; - prompt: string; - mask?: any; - model?: string | null; - n?: number | null; - response_format?: string | null; - size?: string | null; - user?: string; + image: any; + prompt: string; + mask?: any; + model?: string | null; + n?: number | null; + response_format?: string | null; + size?: string | null; + user?: string; } export interface ImageCreateVariationParams { - image: any; - model?: string | null; - n?: number | null; - response_format?: string | null; - size?: string | null; - user?: string; + image: any; + model?: string | null; + n?: number | null; + response_format?: string | null; + size?: string | null; + user?: string; } export interface ImagesResponse { @@ -61,12 +61,12 @@ export class Images extends ApiResource { }; } - const OAIclient = initOpenAIClient(this.client); + const OAIclient = initOpenAIClient(this.client); // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore const result = await OAIclient.images.generate(body, opts).withResponse(); - + return finalResponse(result); } @@ -84,7 +84,7 @@ export class Images extends ApiResource { }; } - const OAIclient = initOpenAIClient(this.client); + const OAIclient = initOpenAIClient(this.client); // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore @@ -107,10 +107,12 @@ export class Images extends ApiResource { }; } - const OAIclient = initOpenAIClient(this.client); + const OAIclient = initOpenAIClient(this.client); // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore - const result = await OAIclient.images.createVariation(body, opts).withResponse(); + const result = await OAIclient.images + .createVariation(body, opts) + .withResponse(); return finalResponse(result); } diff --git a/src/apis/index.ts b/src/apis/index.ts index ea1cad9..594dc10 100644 --- a/src/apis/index.ts +++ b/src/apis/index.ts @@ -1,19 +1,19 @@ -export { Chat } from "./chatCompletions"; -export { Completions } from "./completions"; -export { createHeaders } from "./createHeaders"; -export { Feedback } from "./feedback"; -export { Generations, Prompt } from "./generations"; -export { postMethod } from "./postMethod"; -export { Embeddings } from "./embeddings"; -export { Images } from "./images"; -export { Assistants } from "./assistants"; -export { Threads } from "./threads"; -export { MainFiles } from "./files"; -export { Models } from "./models"; -export { Batches } from "./batches"; -export { FineTuning } from "./fineTuning" -export { Moderations } from "./moderations" -export { Audio } from "./audio" -export { VectorStores } from "./vectorStores" -export { BetaChat } from "./betaChat" -export { Uploads } from "./uploads" \ No newline at end of file +export { Chat } from './chatCompletions'; +export { Completions } from './completions'; +export { createHeaders } from './createHeaders'; +export { Feedback } from './feedback'; +export { Generations, Prompt } from './generations'; +export { postMethod } from './postMethod'; +export { Embeddings } from './embeddings'; +export { Images } from './images'; +export { Assistants } from './assistants'; +export { Threads } from './threads'; +export { MainFiles } from './files'; +export { Models } from './models'; +export { Batches } from './batches'; +export { FineTuning } from './fineTuning'; +export { Moderations } from './moderations'; +export { Audio } from './audio'; +export { VectorStores } from './vectorStores'; +export { BetaChat } from './betaChat'; +export { Uploads } from './uploads'; diff --git a/src/apis/models.ts b/src/apis/models.ts index 8705e81..60f26bb 100644 --- a/src/apis/models.ts +++ b/src/apis/models.ts @@ -1,14 +1,11 @@ -import { ApiClientInterface } from "../_types/generalTypes"; -import { ApiResource } from "../apiResource"; -import { RequestOptions } from "../baseClient"; -import { finalResponse, initOpenAIClient, overrideConfig } from "../utils"; -import { createHeaders } from "./createHeaders"; +import { ApiClientInterface } from '../_types/generalTypes'; +import { ApiResource } from '../apiResource'; +import { RequestOptions } from '../baseClient'; +import { finalResponse, initOpenAIClient, overrideConfig } from '../utils'; +import { createHeaders } from './createHeaders'; export class Models extends ApiResource { - async list( - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { + async list(params?: ApiClientInterface, opts?: RequestOptions): Promise { if (params) { const config = overrideConfig(this.client.config, params.config); this.client.customHeaders = { @@ -17,7 +14,7 @@ export class Models extends ApiResource { }; } - const OAIclient = initOpenAIClient(this.client); + const OAIclient = initOpenAIClient(this.client); const result = await OAIclient.models.list(opts).withResponse(); @@ -37,7 +34,7 @@ export class Models extends ApiResource { }; } - const OAIclient = initOpenAIClient(this.client); + const OAIclient = initOpenAIClient(this.client); const result = await OAIclient.models.retrieve(model, opts).withResponse(); @@ -57,7 +54,7 @@ export class Models extends ApiResource { }; } - const OAIclient = initOpenAIClient(this.client); + const OAIclient = initOpenAIClient(this.client); const result = await OAIclient.models.del(model, opts).withResponse(); diff --git a/src/apis/moderations.ts b/src/apis/moderations.ts index df1fc43..8860392 100644 --- a/src/apis/moderations.ts +++ b/src/apis/moderations.ts @@ -1,28 +1,30 @@ -import { ModerationCreateParams } from "openai/resources"; -import { ApiClientInterface } from "../_types/generalTypes"; -import { ApiResource } from "../apiResource"; -import { RequestOptions } from "../baseClient"; -import { finalResponse, initOpenAIClient, overrideConfig } from "../utils"; -import { createHeaders } from "./createHeaders"; +import { ModerationCreateParams } from 'openai/resources'; +import { ApiClientInterface } from '../_types/generalTypes'; +import { ApiResource } from '../apiResource'; +import { RequestOptions } from '../baseClient'; +import { finalResponse, initOpenAIClient, overrideConfig } from '../utils'; +import { createHeaders } from './createHeaders'; +export class Moderations extends ApiResource { + async create( + _body: ModerationCreateParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + const body: ModerationCreateParams = _body; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; + } -export class Moderations extends ApiResource{ - async create(_body: ModerationCreateParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - const body: ModerationCreateParams = _body; - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); + const OAIclient = initOpenAIClient(this.client); - const result = await OAIclient.moderations.create(body, opts).withResponse(); - return finalResponse(result); - } -} \ No newline at end of file + const result = await OAIclient.moderations + .create(body, opts) + .withResponse(); + return finalResponse(result); + } +} diff --git a/src/apis/postMethod.ts b/src/apis/postMethod.ts index cc2e50e..53f6bfd 100644 --- a/src/apis/postMethod.ts +++ b/src/apis/postMethod.ts @@ -1,55 +1,58 @@ -import { APIResponseType, ApiClientInterface } from "../_types/generalTypes"; -import { ApiResource } from "../apiResource"; -import { APIPromise, RequestOptions } from "../baseClient"; -import { Stream } from "../streaming"; -import { overrideConfig } from "../utils"; -import { createHeaders } from "./createHeaders"; +import { APIResponseType, ApiClientInterface } from '../_types/generalTypes'; +import { ApiResource } from '../apiResource'; +import { APIPromise, RequestOptions } from '../baseClient'; +import { Stream } from '../streaming'; +import { overrideConfig } from '../utils'; +import { createHeaders } from './createHeaders'; export class postMethod extends ApiResource { - create( - url: string, - _body: PostBodyNonStreaming, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise; - create( - url: string, - _body: PostBodyStreaming, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise> - create( - url: string, - _body: PostBodyParams, - params?: ApiClientInterface, - opts?: RequestOptions, - ): APIPromise> | APIPromise - create( - url: string, - _body: PostBodyParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise | APIPromise> { - const body = _body - if (params) { - const config = overrideConfig(this.client.config, params.config) - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params, config }) } - } - const response = this.post(url, { body, ...opts }) as - | APIPromise - | APIPromise> - return response + create( + url: string, + _body: PostBodyNonStreaming, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise; + create( + url: string, + _body: PostBodyStreaming, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise>; + create( + url: string, + _body: PostBodyParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise> | APIPromise; + create( + url: string, + _body: PostBodyParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise | APIPromise> { + const body = _body; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } + const response = this.post(url, { body, ...opts }) as + | APIPromise + | APIPromise>; + return response; + } } export type PostResponse = Record & APIResponseType; export interface PostBodyStreaming extends Record { - stream?: true; + stream?: true; } export interface PostBodyNonStreaming extends Record { - stream?: false; + stream?: false; } export type PostBodyParams = PostBodyNonStreaming | PostBodyStreaming; diff --git a/src/apis/threads.ts b/src/apis/threads.ts index b0187c5..34e8a85 100644 --- a/src/apis/threads.ts +++ b/src/apis/threads.ts @@ -1,146 +1,153 @@ -import { ApiClientInterface } from "../_types/generalTypes"; -import { ApiResource } from "../apiResource"; -import { RequestOptions } from "../baseClient"; - -import { finalResponse, initOpenAIClient, overrideConfig } from "../utils"; -import { createHeaders } from "./createHeaders"; +import { ApiClientInterface } from '../_types/generalTypes'; +import { ApiResource } from '../apiResource'; +import { RequestOptions } from '../baseClient'; +import { finalResponse, initOpenAIClient, overrideConfig } from '../utils'; +import { createHeaders } from './createHeaders'; export class Threads extends ApiResource { - - messages: Messages; - runs: Runs - - constructor(client:any) { - super(client); - this.messages = new Messages(client); - this.runs = new Runs(client); + messages: Messages; + runs: Runs; + + constructor(client: any) { + super(client); + this.messages = new Messages(client); + this.runs = new Runs(client); + } + + async create( + _body: ThreadCreateParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + const body: ThreadCreateParams = _body; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async create( - _body: ThreadCreateParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - const body: ThreadCreateParams = _body; - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - -const OAIclient = initOpenAIClient(this.client); - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore - const result = await OAIclient.beta.threads.create(body, opts).withResponse(); - - return finalResponse(result); + const OAIclient = initOpenAIClient(this.client); + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + const result = await OAIclient.beta.threads + .create(body, opts) + .withResponse(); + + return finalResponse(result); + } + + async retrieve( + threadId: string, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async retrieve( - threadId: string, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - -const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.beta.threads.retrieve(threadId, opts).withResponse(); - - return finalResponse(result); + const OAIclient = initOpenAIClient(this.client); + + const result = await OAIclient.beta.threads + .retrieve(threadId, opts) + .withResponse(); + + return finalResponse(result); + } + + async update( + threadId: string, + _body: ThreadUpdateParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + const body: ThreadUpdateParams = _body; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async update( - threadId: string, - _body: ThreadUpdateParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - const body: ThreadUpdateParams = _body; - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - -const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.beta.threads.update(threadId, body, opts).withResponse(); - - return finalResponse(result); + const OAIclient = initOpenAIClient(this.client); + + const result = await OAIclient.beta.threads + .update(threadId, body, opts) + .withResponse(); + + return finalResponse(result); + } + + async del( + threadId: string, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - - async del( - threadId: string, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - -const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.beta.threads.del(threadId, opts).withResponse(); - - return finalResponse(result); + + const OAIclient = initOpenAIClient(this.client); + + const result = await OAIclient.beta.threads + .del(threadId, opts) + .withResponse(); + + return finalResponse(result); + } + + async createAndRun( + _body: ThreadCreateAndRunParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + const body: ThreadCreateAndRunParams = _body; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async createAndRun( - _body: ThreadCreateAndRunParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - const body: ThreadCreateAndRunParams = _body; - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - -const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.beta.threads.createAndRun(body, opts).withResponse(); - - return finalResponse(result); + const OAIclient = initOpenAIClient(this.client); + + const result = await OAIclient.beta.threads + .createAndRun(body, opts) + .withResponse(); + + return finalResponse(result); + } + + async createAndRunPoll( + _body: ThreadCreateAndRunParamsNonStreaming, + params?: ApiClientInterface, + opts?: RequestOptions & { pollIntervalMs?: number } + ): Promise { + const body: ThreadCreateAndRunParamsNonStreaming = _body; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async createAndRunPoll( - _body: ThreadCreateAndRunParamsNonStreaming, - params?: ApiClientInterface, - opts?: RequestOptions & {pollIntervalMs?: number} - ): Promise { - const body: ThreadCreateAndRunParamsNonStreaming = _body; - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.beta.threads.createAndRunPoll(body, opts) - return result; + const OAIclient = initOpenAIClient(this.client); + const result = await OAIclient.beta.threads.createAndRunPoll(body, opts); + return result; } async createAndRunStream( @@ -156,443 +163,479 @@ const OAIclient = initOpenAIClient(this.client); ...createHeaders({ ...params, config }), }; } - + const OAIclient = initOpenAIClient(this.client); - + const result = await OAIclient.beta.threads.createAndRunStream(body, opts); return result; } - } - -export class Messages extends ApiResource{ - - async create( - threadId: string, - _body: MessageCreateParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - const body: MessageCreateParams = _body; - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - -const OAIclient = initOpenAIClient(this.client); - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore - const result = await OAIclient.beta.threads.messages.create(threadId, body, opts).withResponse(); - - return finalResponse(result); +export class Messages extends ApiResource { + async create( + threadId: string, + _body: MessageCreateParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + const body: MessageCreateParams = _body; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async list( - threadId: string, - _query?: MessageListParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - const query: MessageListParams | undefined = _query; - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - -const OAIclient = initOpenAIClient(this.client); - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore - const result = await OAIclient.beta.threads.messages.list(threadId, query, opts).withResponse(); - - return finalResponse(result); + const OAIclient = initOpenAIClient(this.client); + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + const result = await OAIclient.beta.threads.messages + .create(threadId, body, opts) + .withResponse(); + + return finalResponse(result); + } + + async list( + threadId: string, + _query?: MessageListParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + const query: MessageListParams | undefined = _query; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async retrieve( - threadId: string, - messageId: string, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - -const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.beta.threads.messages.retrieve(threadId, messageId, opts).withResponse(); - - return finalResponse(result); + const OAIclient = initOpenAIClient(this.client); + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + const result = await OAIclient.beta.threads.messages + .list(threadId, query, opts) + .withResponse(); + + return finalResponse(result); + } + async retrieve( + threadId: string, + messageId: string, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async update( - threadId: string, - messageId: string, - _body: MessageUpdateParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - const body: MessageUpdateParams = _body; - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - -const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.beta.threads.messages.update(threadId, messageId, body, opts).withResponse(); - - return finalResponse(result); + const OAIclient = initOpenAIClient(this.client); + + const result = await OAIclient.beta.threads.messages + .retrieve(threadId, messageId, opts) + .withResponse(); + + return finalResponse(result); + } + + async update( + threadId: string, + messageId: string, + _body: MessageUpdateParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + const body: MessageUpdateParams = _body; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } + const OAIclient = initOpenAIClient(this.client); -} + const result = await OAIclient.beta.threads.messages + .update(threadId, messageId, body, opts) + .withResponse(); + return finalResponse(result); + } +} -export class Runs extends ApiResource{ +export class Runs extends ApiResource { + steps: Steps; - steps: Steps; + constructor(client: any) { + super(client); + this.steps = new Steps(client); + } - constructor(client:any) { - super(client); - this.steps = new Steps(client); + async create( + threadId: string, + _body: RunCreateParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + const body: RunCreateParams = _body; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async create( - threadId: string, - _body: RunCreateParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - const body: RunCreateParams = _body; - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.beta.threads.runs.create(threadId, body, opts).withResponse(); - - return finalResponse(result); - } + const OAIclient = initOpenAIClient(this.client); + + const result = await OAIclient.beta.threads.runs + .create(threadId, body, opts) + .withResponse(); - async list( - threadId: string, - _query?: RunListParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - const query: RunListParams | undefined = _query; - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore - const result = await OAIclient.beta.threads.runs.list(threadId, query, opts).withResponse(); - - return finalResponse(result); + return finalResponse(result); + } + + async list( + threadId: string, + _query?: RunListParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + const query: RunListParams | undefined = _query; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async retrieve( - threadId: string, - runId: string, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.beta.threads.runs.retrieve(threadId, runId, opts).withResponse(); - - return finalResponse(result); + const OAIclient = initOpenAIClient(this.client); + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + const result = await OAIclient.beta.threads.runs + .list(threadId, query, opts) + .withResponse(); + + return finalResponse(result); + } + + async retrieve( + threadId: string, + runId: string, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async update( - threadId: string, - runId: string, - _body: RunUpdateParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - const body: RunUpdateParams = _body; - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.beta.threads.runs.update(threadId, runId, body, opts).withResponse(); - - return finalResponse(result); + const OAIclient = initOpenAIClient(this.client); + + const result = await OAIclient.beta.threads.runs + .retrieve(threadId, runId, opts) + .withResponse(); + + return finalResponse(result); + } + + async update( + threadId: string, + runId: string, + _body: RunUpdateParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + const body: RunUpdateParams = _body; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async submitToolOutputs( - threadId: string, - runId: string, - _body: RunSubmitToolOutputsParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - const body: RunSubmitToolOutputsParams = _body; - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.beta.threads.runs.submitToolOutputs(threadId, runId, body, opts).withResponse(); - - return finalResponse(result); + const OAIclient = initOpenAIClient(this.client); + + const result = await OAIclient.beta.threads.runs + .update(threadId, runId, body, opts) + .withResponse(); + + return finalResponse(result); + } + + async submitToolOutputs( + threadId: string, + runId: string, + _body: RunSubmitToolOutputsParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + const body: RunSubmitToolOutputsParams = _body; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async submitToolOutputsAndPoll( - threadId: string, - runId: string, - _body: RunSubmitToolOutputsParamsNonStreaming, - params?: ApiClientInterface, - opts?: RequestOptions & {pollIntervalMs?: number} - ): Promise { - const body: RunSubmitToolOutputsParamsNonStreaming = _body; - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.beta.threads.runs.submitToolOutputsAndPoll(threadId, runId, body, opts); - return result; + const OAIclient = initOpenAIClient(this.client); + + const result = await OAIclient.beta.threads.runs + .submitToolOutputs(threadId, runId, body, opts) + .withResponse(); + + return finalResponse(result); + } + + async submitToolOutputsAndPoll( + threadId: string, + runId: string, + _body: RunSubmitToolOutputsParamsNonStreaming, + params?: ApiClientInterface, + opts?: RequestOptions & { pollIntervalMs?: number } + ): Promise { + const body: RunSubmitToolOutputsParamsNonStreaming = _body; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async submitToolOutputsStream( - threadId: string, - runId: string, - _body: RunSubmitToolOutputsParamsStreaming, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - const body: RunSubmitToolOutputsParamsStreaming = _body; - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.beta.threads.runs.submitToolOutputsStream(threadId, runId, body, opts); - return result; + const OAIclient = initOpenAIClient(this.client); + + const result = await OAIclient.beta.threads.runs.submitToolOutputsAndPoll( + threadId, + runId, + body, + opts + ); + return result; + } + + async submitToolOutputsStream( + threadId: string, + runId: string, + _body: RunSubmitToolOutputsParamsStreaming, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + const body: RunSubmitToolOutputsParamsStreaming = _body; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async cancel( - threadId: string, - runId: string, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - const body = {} - const options = { body, ...opts } - - const result = await OAIclient.beta.threads.runs.cancel(threadId, runId, options).withResponse(); - - return finalResponse(result); + const OAIclient = initOpenAIClient(this.client); + + const result = await OAIclient.beta.threads.runs.submitToolOutputsStream( + threadId, + runId, + body, + opts + ); + return result; + } + + async cancel( + threadId: string, + runId: string, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async createAndPoll( - threadId: string, - _body: RunCreateParamsNonStreaming, - params?: ApiClientInterface, - opts?: RequestOptions & {pollIntervalMs?: number}, - ): Promise { - const body: RunCreateParamsNonStreaming = _body; - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.beta.threads.runs.createAndPoll(threadId, body, opts); - return result; + const OAIclient = initOpenAIClient(this.client); + const body = {}; + const options = { body, ...opts }; + + const result = await OAIclient.beta.threads.runs + .cancel(threadId, runId, options) + .withResponse(); + + return finalResponse(result); + } + + async createAndPoll( + threadId: string, + _body: RunCreateParamsNonStreaming, + params?: ApiClientInterface, + opts?: RequestOptions & { pollIntervalMs?: number } + ): Promise { + const body: RunCreateParamsNonStreaming = _body; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async createAndStream( - threadId: string, - _body: RunCreateParamsBaseStream, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - const body: RunCreateParamsBaseStream = _body; - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.beta.threads.runs.createAndStream(threadId, body, opts); - return result; + const OAIclient = initOpenAIClient(this.client); + + const result = await OAIclient.beta.threads.runs.createAndPoll( + threadId, + body, + opts + ); + return result; + } + + async createAndStream( + threadId: string, + _body: RunCreateParamsBaseStream, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + const body: RunCreateParamsBaseStream = _body; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async poll( - threadId: string, - runId: string, - params?: ApiClientInterface, - opts?: RequestOptions & {pollIntervalMs?: number} - ): Promise { - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.beta.threads.runs.poll(threadId, runId, opts); - return result + const OAIclient = initOpenAIClient(this.client); + + const result = await OAIclient.beta.threads.runs.createAndStream( + threadId, + body, + opts + ); + return result; + } + + async poll( + threadId: string, + runId: string, + params?: ApiClientInterface, + opts?: RequestOptions & { pollIntervalMs?: number } + ): Promise { + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async stream( - threadId: string, - _body: RunCreateParamsBaseStream, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - const body: RunCreateParamsBaseStream = _body; - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.beta.threads.runs.stream(threadId, body, opts); - return result; + const OAIclient = initOpenAIClient(this.client); + + const result = await OAIclient.beta.threads.runs.poll( + threadId, + runId, + opts + ); + return result; + } + + async stream( + threadId: string, + _body: RunCreateParamsBaseStream, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + const body: RunCreateParamsBaseStream = _body; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } + const OAIclient = initOpenAIClient(this.client); + + const result = await OAIclient.beta.threads.runs.stream( + threadId, + body, + opts + ); + return result; + } } -export class Steps extends ApiResource{ - - async list( - threadId: string, - runId: string, - _query?: StepListParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - const query: StepListParams | undefined = _query; - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - -const OAIclient = initOpenAIClient(this.client); - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore - const result = await OAIclient.beta.threads.runs.steps.list(threadId, runId, query, opts).withResponse(); - - return finalResponse(result); - } - - async retrieve( - threadId: string, - runId: string, - stepId: string, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - -const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.beta.threads.runs.steps.retrieve(threadId, runId, stepId, opts).withResponse(); - - return finalResponse(result); +export class Steps extends ApiResource { + async list( + threadId: string, + runId: string, + _query?: StepListParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + const query: StepListParams | undefined = _query; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } -} + const OAIclient = initOpenAIClient(this.client); + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + const result = await OAIclient.beta.threads.runs.steps + .list(threadId, runId, query, opts) + .withResponse(); + return finalResponse(result); + } + async retrieve( + threadId: string, + runId: string, + stepId: string, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; + } -export interface ThreadCreateParams { - messages?: Array; - metadata?: unknown | null; + const OAIclient = initOpenAIClient(this.client); + + const result = await OAIclient.beta.threads.runs.steps + .retrieve(threadId, runId, stepId, opts) + .withResponse(); + + return finalResponse(result); + } } +export interface ThreadCreateParams { + messages?: Array; + metadata?: unknown | null; +} export interface Message { content: string; @@ -601,86 +644,87 @@ export interface Message { metadata?: unknown | null; } - export interface ThreadUpdateParams { - metadata?: unknown | null; + metadata?: unknown | null; } export interface MessageCreateParams { - content: string; - role: string; - file_ids?: Array; - metadata?: unknown | null; + content: string; + role: string; + file_ids?: Array; + metadata?: unknown | null; } export interface MessageListParams extends CursorPageParams { - order?: string; + order?: string; } export interface CursorPageParams { - after?: string; - - limit?: number; + after?: string; + + limit?: number; } export interface FileListParams extends CursorPageParams { - before?: string; - order?: string; + before?: string; + order?: string; } export interface MessageUpdateParams { - metadata?: unknown | null; + metadata?: unknown | null; } export interface RunCreateParams { - assistant_id: string; - additional_instructions?: string | null; - instructions?: string | null; - metadata?: unknown | null; - model?: string | null; - tools?: Array | null; + assistant_id: string; + additional_instructions?: string | null; + instructions?: string | null; + metadata?: unknown | null; + model?: string | null; + tools?: Array | null; } export interface RunCreateParamsNonStreaming extends RunCreateParams { - stream?: false | null; + stream?: false | null; } export interface ThreadCreateAndRunParams { - - assistant_id: string; - instructions?: string | null; - metadata?: unknown | null; - model?: string | null; - thread?: any; - tools?: Array | null; + assistant_id: string; + instructions?: string | null; + metadata?: unknown | null; + model?: string | null; + thread?: any; + tools?: Array | null; } -export interface ThreadCreateAndRunParamsNonStreaming extends ThreadCreateAndRunParams{ - stream?: false | null; +export interface ThreadCreateAndRunParamsNonStreaming + extends ThreadCreateAndRunParams { + stream?: false | null; } -export type ThreadCreateAndRunParamsBaseStream = Omit & { +export type ThreadCreateAndRunParamsBaseStream = Omit< + ThreadCreateAndRunParams, + 'stream' +> & { stream?: true; }; export interface RunListParams extends CursorPageParams { - before?: string; - order?: string; + before?: string; + order?: string; } export interface StepListParams extends CursorPageParams { - before?: string; - order?: string; + before?: string; + order?: string; } export interface RunUpdateParams { - metadata?: unknown | null; + metadata?: unknown | null; } export interface RunSubmitToolOutputsParams { - tool_outputs: Array; + tool_outputs: Array; } - export interface ToolOutput { output?: string; tool_call_id?: string; @@ -690,10 +734,12 @@ export type RunCreateParamsBaseStream = Omit & { stream?: true; }; -export interface RunSubmitToolOutputsParamsNonStreaming extends RunSubmitToolOutputsParams { - stream?: false | null; +export interface RunSubmitToolOutputsParamsNonStreaming + extends RunSubmitToolOutputsParams { + stream?: false | null; } -export interface RunSubmitToolOutputsParamsStreaming extends RunSubmitToolOutputsParams { +export interface RunSubmitToolOutputsParamsStreaming + extends RunSubmitToolOutputsParams { stream: true; -} \ No newline at end of file +} diff --git a/src/apis/uploads.ts b/src/apis/uploads.ts index 46d369a..6b6fee7 100644 --- a/src/apis/uploads.ts +++ b/src/apis/uploads.ts @@ -1,20 +1,19 @@ -import { ApiClientInterface } from "../_types/generalTypes"; -import { ApiResource } from "../apiResource"; -import { RequestOptions } from "../baseClient"; -import { finalResponse, initOpenAIClient, overrideConfig } from "../utils"; -import { createHeaders } from "./createHeaders"; -import { UploadCompleteParams } from "openai/resources"; -import { Uploadable } from "openai/uploads"; +import { ApiClientInterface } from '../_types/generalTypes'; +import { ApiResource } from '../apiResource'; +import { RequestOptions } from '../baseClient'; +import { finalResponse, initOpenAIClient, overrideConfig } from '../utils'; +import { createHeaders } from './createHeaders'; +import { UploadCompleteParams } from 'openai/resources'; +import { Uploadable } from 'openai/uploads'; export class Uploads extends ApiResource { - parts: Parts + parts: Parts; constructor(client: any) { super(client); this.parts = new Parts(client); } - async create( _body: UploadCreateParams, params?: ApiClientInterface, @@ -46,9 +45,11 @@ export class Uploads extends ApiResource { }; } const OAIclient = initOpenAIClient(this.client); - const body = {} - const options = { body, ...opts } - const response = await OAIclient.uploads.cancel(uploadId, options).withResponse(); + const body = {}; + const options = { body, ...opts }; + const response = await OAIclient.uploads + .cancel(uploadId, options) + .withResponse(); return finalResponse(response); } @@ -67,30 +68,34 @@ export class Uploads extends ApiResource { }; } const OAIclient = initOpenAIClient(this.client); - const response = await OAIclient.uploads.complete(uploadId, body, opts).withResponse(); + const response = await OAIclient.uploads + .complete(uploadId, body, opts) + .withResponse(); return finalResponse(response); } } -export class Parts extends ApiResource{ - async create( - uploadId: string, - _body: PartCreateParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - const body: PartCreateParams = _body; - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - const OAIclient = initOpenAIClient(this.client); - const response = await OAIclient.uploads.parts.create(uploadId ,body, opts).withResponse(); - return finalResponse(response); +export class Parts extends ApiResource { + async create( + uploadId: string, + _body: PartCreateParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + const body: PartCreateParams = _body; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } + const OAIclient = initOpenAIClient(this.client); + const response = await OAIclient.uploads.parts + .create(uploadId, body, opts) + .withResponse(); + return finalResponse(response); + } } export interface UploadCreateParams { @@ -102,4 +107,4 @@ export interface UploadCreateParams { export interface PartCreateParams { data: Uploadable; -} \ No newline at end of file +} diff --git a/src/apis/vectorStores.ts b/src/apis/vectorStores.ts index f6a7e38..54b5460 100644 --- a/src/apis/vectorStores.ts +++ b/src/apis/vectorStores.ts @@ -1,13 +1,13 @@ -import { Uploadable } from "openai/uploads"; -import { ApiClientInterface } from "../_types/generalTypes"; -import { ApiResource } from "../apiResource"; -import { RequestOptions } from "../baseClient"; -import { finalResponse, initOpenAIClient, overrideConfig } from "../utils"; -import { createHeaders } from "./createHeaders"; +import { Uploadable } from 'openai/uploads'; +import { ApiClientInterface } from '../_types/generalTypes'; +import { ApiResource } from '../apiResource'; +import { RequestOptions } from '../baseClient'; +import { finalResponse, initOpenAIClient, overrideConfig } from '../utils'; +import { createHeaders } from './createHeaders'; export class VectorStores extends ApiResource { files: Files; - fileBatches: FileBatches + fileBatches: FileBatches; constructor(client: any) { super(client); @@ -111,7 +111,7 @@ export class VectorStores extends ApiResource { vectorStoreId: string, params?: ApiClientInterface, opts?: RequestOptions - ): Promise { + ): Promise { if (params) { const config = overrideConfig(this.client.config, params.config); this.client.customHeaders = { @@ -127,356 +127,385 @@ export class VectorStores extends ApiResource { .withResponse(); return finalResponse(result); - } - } -export class Files extends ApiResource{ - - - async create( - vectorStoreId: string, - _body: FileCreateParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - const body: FileCreateParams = _body; - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.beta.vectorStores - .files.create(vectorStoreId, body, opts) - .withResponse(); - - return finalResponse(result); +export class Files extends ApiResource { + async create( + vectorStoreId: string, + _body: FileCreateParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + const body: FileCreateParams = _body; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async retrieve( - vectorStoreId: string, - fileId: string, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.beta.vectorStores.files.retrieve(vectorStoreId, fileId, opts).withResponse(); - - return finalResponse(result); + const OAIclient = initOpenAIClient(this.client); + + const result = await OAIclient.beta.vectorStores.files + .create(vectorStoreId, body, opts) + .withResponse(); + + return finalResponse(result); + } + + async retrieve( + vectorStoreId: string, + fileId: string, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async list( - vectorStoreId: string, - _query?: FileListParams | RequestOptions, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - const query: FileListParams | RequestOptions| undefined = _query; - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore - const result = await OAIclient.beta.vectorStores.files.list(vectorStoreId, query, opts).withResponse(); - - return finalResponse(result); + const OAIclient = initOpenAIClient(this.client); + + const result = await OAIclient.beta.vectorStores.files + .retrieve(vectorStoreId, fileId, opts) + .withResponse(); + + return finalResponse(result); + } + + async list( + vectorStoreId: string, + _query?: FileListParams | RequestOptions, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + const query: FileListParams | RequestOptions | undefined = _query; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async del( - vectorStoreId: string, - fileId: string, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.beta.vectorStores.files.del(vectorStoreId, fileId, opts).withResponse(); - - return finalResponse(result); + const OAIclient = initOpenAIClient(this.client); + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + const result = await OAIclient.beta.vectorStores.files + .list(vectorStoreId, query, opts) + .withResponse(); + + return finalResponse(result); + } + + async del( + vectorStoreId: string, + fileId: string, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async createAndPoll( - vectorStoreId: string, - _body: FileCreateParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - const body: FileCreateParams = _body; - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.beta.vectorStores - .files.createAndPoll(vectorStoreId, body, opts); - - return result; + const OAIclient = initOpenAIClient(this.client); + + const result = await OAIclient.beta.vectorStores.files + .del(vectorStoreId, fileId, opts) + .withResponse(); + + return finalResponse(result); + } + + async createAndPoll( + vectorStoreId: string, + _body: FileCreateParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + const body: FileCreateParams = _body; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async poll( - vectorStoreId: string, - fileId: string, - params?: ApiClientInterface, - opts?: RequestOptions & { pollIntervalMs?: number } - ): Promise { - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.beta.vectorStores.files.poll(vectorStoreId, fileId, opts); - - return result; + const OAIclient = initOpenAIClient(this.client); + + const result = await OAIclient.beta.vectorStores.files.createAndPoll( + vectorStoreId, + body, + opts + ); + + return result; + } + + async poll( + vectorStoreId: string, + fileId: string, + params?: ApiClientInterface, + opts?: RequestOptions & { pollIntervalMs?: number } + ): Promise { + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async upload( - vectorStoreId: string, - file: Uploadable, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.beta.vectorStores.files.upload(vectorStoreId, file, opts); - - return result; + const OAIclient = initOpenAIClient(this.client); + + const result = await OAIclient.beta.vectorStores.files.poll( + vectorStoreId, + fileId, + opts + ); + + return result; + } + + async upload( + vectorStoreId: string, + file: Uploadable, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async uploadAndPoll( - vectorStoreId: string, - file: Uploadable, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.beta.vectorStores.files.uploadAndPoll(vectorStoreId, file, opts); - - return result; - + const OAIclient = initOpenAIClient(this.client); + + const result = await OAIclient.beta.vectorStores.files.upload( + vectorStoreId, + file, + opts + ); + + return result; + } + + async uploadAndPoll( + vectorStoreId: string, + file: Uploadable, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } + + const OAIclient = initOpenAIClient(this.client); + + const result = await OAIclient.beta.vectorStores.files.uploadAndPoll( + vectorStoreId, + file, + opts + ); + + return result; + } } -export class FileBatches extends ApiResource{ - - async create( - vectorStoreId: string, - _body: FileBatchCreateParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - const body: FileBatchCreateParams = _body; - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.beta.vectorStores - .fileBatches.create(vectorStoreId, body, opts) - .withResponse(); - - return finalResponse(result); +export class FileBatches extends ApiResource { + async create( + vectorStoreId: string, + _body: FileBatchCreateParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + const body: FileBatchCreateParams = _body; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async retrieve( - vectorStoreId: string, - batchId: string, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.beta.vectorStores.fileBatches.retrieve(vectorStoreId, batchId, opts).withResponse(); - - return finalResponse(result); + const OAIclient = initOpenAIClient(this.client); + + const result = await OAIclient.beta.vectorStores.fileBatches + .create(vectorStoreId, body, opts) + .withResponse(); + + return finalResponse(result); + } + + async retrieve( + vectorStoreId: string, + batchId: string, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async cancel( - vectorStoreId: string, - batchId: string, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - const body = {} - const options = { body, ...opts } - - const result = await OAIclient.beta.vectorStores.fileBatches.cancel(vectorStoreId, batchId, options).withResponse(); - - return finalResponse(result); - + const OAIclient = initOpenAIClient(this.client); + + const result = await OAIclient.beta.vectorStores.fileBatches + .retrieve(vectorStoreId, batchId, opts) + .withResponse(); + + return finalResponse(result); + } + + async cancel( + vectorStoreId: string, + batchId: string, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async createAndPoll( - vectorStoreId: string, - _body: FileBatchCreateParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - const body: FileBatchCreateParams = _body; - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.beta.vectorStores - .fileBatches.createAndPoll(vectorStoreId, body, opts); - - return result; + const OAIclient = initOpenAIClient(this.client); + const body = {}; + const options = { body, ...opts }; + + const result = await OAIclient.beta.vectorStores.fileBatches + .cancel(vectorStoreId, batchId, options) + .withResponse(); + + return finalResponse(result); + } + + async createAndPoll( + vectorStoreId: string, + _body: FileBatchCreateParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + const body: FileBatchCreateParams = _body; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async listFiles( - vectorStoreId: string, - batchId: string, - _query?: FileBatchListFilesParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - const query: FileBatchListFilesParams | undefined = _query; - - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore - const result = await OAIclient.beta.vectorStores.fileBatches.listFiles(vectorStoreId, batchId, query, opts).withResponse(); - - return finalResponse(result); + const OAIclient = initOpenAIClient(this.client); + + const result = await OAIclient.beta.vectorStores.fileBatches.createAndPoll( + vectorStoreId, + body, + opts + ); + + return result; + } + + async listFiles( + vectorStoreId: string, + batchId: string, + _query?: FileBatchListFilesParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + const query: FileBatchListFilesParams | undefined = _query; + + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async poll( - vectorStoreId: string, - batchId: string, - params?: ApiClientInterface, - opts?: RequestOptions & { pollIntervalMs?: number } - ): Promise { - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } - - const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.beta.vectorStores.fileBatches.poll(vectorStoreId, batchId, opts); - - return result; + const OAIclient = initOpenAIClient(this.client); + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + const result = await OAIclient.beta.vectorStores.fileBatches + .listFiles(vectorStoreId, batchId, query, opts) + .withResponse(); + + return finalResponse(result); + } + + async poll( + vectorStoreId: string, + batchId: string, + params?: ApiClientInterface, + opts?: RequestOptions & { pollIntervalMs?: number } + ): Promise { + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } - async uploadAndPoll( - vectorStoreId: string, - { files, fileIds = [] }: { files: Uploadable[]; fileIds?: string[] }, - params?: ApiClientInterface, - opts?: RequestOptions & { pollIntervalMs?: number; maxConcurrency?: number }, - ): Promise { - if(params){ - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - } - } - - const OAIclient = initOpenAIClient(this.client); - - const result = await OAIclient.beta.vectorStores.fileBatches.uploadAndPoll(vectorStoreId, { files, fileIds }, opts); - return result; + const OAIclient = initOpenAIClient(this.client); + + const result = await OAIclient.beta.vectorStores.fileBatches.poll( + vectorStoreId, + batchId, + opts + ); + + return result; + } + + async uploadAndPoll( + vectorStoreId: string, + { files, fileIds = [] }: { files: Uploadable[]; fileIds?: string[] }, + params?: ApiClientInterface, + opts?: RequestOptions & { pollIntervalMs?: number; maxConcurrency?: number } + ): Promise { + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; } -} + const OAIclient = initOpenAIClient(this.client); + const result = await OAIclient.beta.vectorStores.fileBatches.uploadAndPoll( + vectorStoreId, + { files, fileIds }, + opts + ); + return result; + } +} export interface ExpiresAfter { - anchor: "last_active_at"; + anchor: 'last_active_at'; days: number; } @@ -495,7 +524,7 @@ export interface VectorStoreUpdateParams { export interface VectorStoreListParams extends CursorPageParams { before?: string; - order?: "asc" | "desc"; + order?: 'asc' | 'desc'; } export interface CursorPageParams { @@ -504,23 +533,22 @@ export interface CursorPageParams { limit?: number; } - export interface FileCreateParams { - file_id: string; + file_id: string; } export interface FileListParams extends CursorPageParams { - before?: string; - filter?: 'in_progress' | 'completed' | 'failed' | 'cancelled'; - order?: 'asc' | 'desc'; - } + before?: string; + filter?: 'in_progress' | 'completed' | 'failed' | 'cancelled'; + order?: 'asc' | 'desc'; +} - export interface FileBatchCreateParams { - file_ids: Array; - } +export interface FileBatchCreateParams { + file_ids: Array; +} - export interface FileBatchListFilesParams extends CursorPageParams { - before?: string; - filter?: 'in_progress' | 'completed' | 'failed' | 'cancelled'; - order?: 'asc' | 'desc'; - } \ No newline at end of file +export interface FileBatchListFilesParams extends CursorPageParams { + before?: string; + filter?: 'in_progress' | 'completed' | 'failed' | 'cancelled'; + order?: 'asc' | 'desc'; +} diff --git a/src/baseClient.ts b/src/baseClient.ts index ddd529f..16de783 100644 --- a/src/baseClient.ts +++ b/src/baseClient.ts @@ -1,207 +1,290 @@ -import KeepAliveAgent from "agentkeepalive"; -import type { Agent } from "node:http"; -import { APIResponseType, ApiClientInterface, Headers } from "./_types/generalTypes"; -import { createHeaders } from "./apis"; -import { PORTKEY_HEADER_PREFIX } from "./constants"; -import { APIConnectionError, APIConnectionTimeoutError, APIError } from "./error"; -import { Stream, createResponseHeaders, safeJSON } from "./streaming"; -import { castToError, getPlatformProperties, parseBody } from "./utils"; -import { VERSION } from "./version"; -fetch -const defaultHttpAgent: Agent = new KeepAliveAgent({ keepAlive: true, timeout: 5 * 60 * 1000 }); +import KeepAliveAgent from 'agentkeepalive'; +import type { Agent } from 'node:http'; +import { + APIResponseType, + ApiClientInterface, + Headers, +} from './_types/generalTypes'; +import { createHeaders } from './apis'; +import { PORTKEY_HEADER_PREFIX } from './constants'; +import { + APIConnectionError, + APIConnectionTimeoutError, + APIError, +} from './error'; +import { Stream, createResponseHeaders, safeJSON } from './streaming'; +import { castToError, getPlatformProperties, parseBody } from './utils'; +import { VERSION } from './version'; +fetch; +const defaultHttpAgent: Agent = new KeepAliveAgent({ + keepAlive: true, + timeout: 5 * 60 * 1000, +}); export type Fetch = (url: string, init?: RequestInit) => Promise; -export type HTTPMethod = "post" | "get" | "put" | "delete" +export type HTTPMethod = 'post' | 'get' | 'put' | 'delete'; export type FinalRequestOptions = RequestOptions & { - method: HTTPMethod; - path: string; + method: HTTPMethod; + path: string; }; - export type RequestOptions = { - method?: HTTPMethod; - path?: string; - query?: Record | undefined; - body?: Record | undefined; - headers?: Headers | undefined; - httpAgent?: Agent; - stream?: boolean | undefined; -} + method?: HTTPMethod; + path?: string; + query?: Record | undefined; + body?: Record | undefined; + headers?: Headers | undefined; + httpAgent?: Agent; + stream?: boolean | undefined; +}; type APIResponseProps = { - response: Response; - options: FinalRequestOptions; - responseHeaders: globalThis.Headers + response: Response; + options: FinalRequestOptions; + responseHeaders: globalThis.Headers; }; type PromiseOrValue = T | Promise; async function defaultParseResponse(props: APIResponseProps): Promise { - const { response } = props; - if (props.options.stream) { - return new Stream(response) as any; - } + const { response } = props; + if (props.options.stream) { + return new Stream(response) as any; + } - const contentType = response.headers.get("content-type"); - if (contentType?.includes("application/json")) { - const headers = defaultParseHeaders(props) - const json = { - ...await response.json(), - getHeaders: () => headers - }; + const contentType = response.headers.get('content-type'); + if (contentType?.includes('application/json')) { + const headers = defaultParseHeaders(props); + const json = { + ...(await response.json()), + getHeaders: () => headers, + }; - return json as T; - } + return json as T; + } - const text = await response.text(); - return text as any as T; + const text = await response.text(); + return text as any as T; } function defaultParseHeaders(props: APIResponseProps): Record { - const { responseHeaders } = props; - const parsedHeaders = createResponseHeaders(responseHeaders) - const prefix = PORTKEY_HEADER_PREFIX - const filteredHeaders = Object.entries(parsedHeaders) - .filter(([key, _]) => key.startsWith(prefix)) - .map(([key, value]) => [key.replace(prefix, ''), value]) - return Object.fromEntries(filteredHeaders) + const { responseHeaders } = props; + const parsedHeaders = createResponseHeaders(responseHeaders); + const prefix = PORTKEY_HEADER_PREFIX; + const filteredHeaders = Object.entries(parsedHeaders) + .filter(([key, _]) => key.startsWith(prefix)) // eslint-disable-line @typescript-eslint/no-unused-vars + .map(([key, value]) => [key.replace(prefix, ''), value]); + return Object.fromEntries(filteredHeaders); } - export class APIPromise extends Promise { - private parsedPromise: Promise | undefined; - - constructor( - private responsePromise: Promise, - private parseResponse: (props: APIResponseProps) => PromiseOrValue = defaultParseResponse, - ) { - super((resolve) => { - // this is maybe a bit weird but this has to be a no-op to not implicitly - // parse the response body; instead .then, .catch, .finally are overridden - // to parse the response - resolve(null as any); - }); - } + private parsedPromise: Promise | undefined; - private parse(): Promise { - if (!this.parsedPromise) { - this.parsedPromise = this.responsePromise.then(this.parseResponse); - } - return this.parsedPromise; - } + constructor( + private responsePromise: Promise, + private parseResponse: ( + props: APIResponseProps + ) => PromiseOrValue = defaultParseResponse + ) { + super((resolve) => { + // this is maybe a bit weird but this has to be a no-op to not implicitly + // parse the response body; instead .then, .catch, .finally are overridden + // to parse the response + resolve(null as any); + }); + } - override then( - onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null, - onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null, - ): Promise { - return this.parse() - .then(onfulfilled, onrejected); + private parse(): Promise { + if (!this.parsedPromise) { + this.parsedPromise = this.responsePromise.then(this.parseResponse); } + return this.parsedPromise; + } - override catch( - onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null, - ): Promise { - return this.parse() - .catch(onrejected); - } + override then( + onfulfilled?: + | ((value: T) => TResult1 | PromiseLike) + | undefined + | null, + onrejected?: + | ((reason: any) => TResult2 | PromiseLike) + | undefined + | null + ): Promise { + return this.parse().then(onfulfilled, onrejected); + } - override finally(onfinally?: (() => void) | undefined | null): Promise { - return this.parse() - .finally(onfinally); - } + override catch( + onrejected?: + | ((reason: any) => TResult | PromiseLike) + | undefined + | null + ): Promise { + return this.parse().catch(onrejected); + } + + override finally(onfinally?: (() => void) | undefined | null): Promise { + return this.parse().finally(onfinally); + } } export abstract class ApiClient { - apiKey: string | null; - baseURL: string; - customHeaders: Record - responseHeaders: Record - portkeyHeaders: Record - - private fetch: Fetch; - constructor({ apiKey, baseURL, config, virtualKey, traceID, metadata, provider, Authorization, cacheForceRefresh, debug, customHost, openaiProject, openaiOrganization, awsSecretAccessKey, awsAccessKeyId, awsSessionToken, awsRegion, vertexProjectId, vertexRegion, workersAiAccountId, azureResourceName, azureDeploymentId, azureApiVersion, huggingfaceBaseUrl, forwardHeaders, cacheNamespace, requestTimeout, strictOpenAiCompliance }: ApiClientInterface) { - this.apiKey = apiKey ?? ""; - this.baseURL = baseURL ?? ""; - this.customHeaders = createHeaders({ apiKey, config, virtualKey, traceID, metadata, provider, Authorization, cacheForceRefresh, debug, customHost, cacheNamespace, openaiProject, openaiOrganization, awsSecretAccessKey, awsAccessKeyId, awsSessionToken, awsRegion, vertexProjectId, vertexRegion, workersAiAccountId, azureResourceName, azureDeploymentId, azureApiVersion, huggingfaceBaseUrl, forwardHeaders, requestTimeout, strictOpenAiCompliance }) - this.portkeyHeaders = this.defaultHeaders() - this.fetch = fetch; - this.responseHeaders = {} - } + apiKey: string | null; + baseURL: string; + customHeaders: Record; + responseHeaders: Record; + portkeyHeaders: Record; - protected defaultHeaders(): Record { - return { - "Content-Type": "application/json", - [`${PORTKEY_HEADER_PREFIX}package-version`]: `portkey-${VERSION}`, - ...getPlatformProperties() - } - } + private fetch: Fetch; + constructor({ + apiKey, + baseURL, + config, + virtualKey, + traceID, + metadata, + provider, + Authorization, + cacheForceRefresh, + debug, + customHost, + openaiProject, + openaiOrganization, + awsSecretAccessKey, + awsAccessKeyId, + awsSessionToken, + awsRegion, + vertexProjectId, + vertexRegion, + workersAiAccountId, + azureResourceName, + azureDeploymentId, + azureApiVersion, + huggingfaceBaseUrl, + forwardHeaders, + cacheNamespace, + requestTimeout, + strictOpenAiCompliance, + }: ApiClientInterface) { + this.apiKey = apiKey ?? ''; + this.baseURL = baseURL ?? ''; + this.customHeaders = createHeaders({ + apiKey, + config, + virtualKey, + traceID, + metadata, + provider, + Authorization, + cacheForceRefresh, + debug, + customHost, + cacheNamespace, + openaiProject, + openaiOrganization, + awsSecretAccessKey, + awsAccessKeyId, + awsSessionToken, + awsRegion, + vertexProjectId, + vertexRegion, + workersAiAccountId, + azureResourceName, + azureDeploymentId, + azureApiVersion, + huggingfaceBaseUrl, + forwardHeaders, + requestTimeout, + strictOpenAiCompliance, + }); + this.portkeyHeaders = this.defaultHeaders(); + this.fetch = fetch; + this.responseHeaders = {}; + } - _post(path: string, opts?: RequestOptions): APIPromise { - return this.methodRequest("post", path, opts); - } + protected defaultHeaders(): Record { + return { + 'Content-Type': 'application/json', + [`${PORTKEY_HEADER_PREFIX}package-version`]: `portkey-${VERSION}`, + ...getPlatformProperties(), + }; + } - _put(path: string, opts?: RequestOptions): APIPromise { - return this.methodRequest("put", path, opts); - } + _post( + path: string, + opts?: RequestOptions + ): APIPromise { + return this.methodRequest('post', path, opts); + } - protected generateError( - status: number | undefined, - errorResponse: object | undefined, - message: string | undefined, - headers: Headers | undefined, - ): APIError { - return APIError.generate( - status, - errorResponse, - message, - headers - ) - } + _put( + path: string, + opts?: RequestOptions + ): APIPromise { + return this.methodRequest('put', path, opts); + } - async request(opts: FinalRequestOptions): Promise { - // Build the request. - const { req, url } = this.buildRequest(opts); - // Make the call to rubeus. - const response = await this.fetch(url, req) - .catch(castToError) - // Parse the response and check for errors. - if (response instanceof Error) { - if (response.name === "AbortError") { - throw new APIConnectionTimeoutError(); - } - throw new APIConnectionError({ cause: response }); - } - this.responseHeaders = createResponseHeaders(response.headers) - if (!response.ok) { - const errText = await response.text() - .catch(() => "Unknown"); - const errJSON = safeJSON(errText); - const errMessage = errJSON ? undefined : errText; - throw this.generateError(response.status, errJSON, errMessage, this.responseHeaders) - - } - // Receive and format the response. - return { response, options: opts, responseHeaders: response.headers } - } + protected generateError( + status: number | undefined, + errorResponse: object | undefined, + message: string | undefined, + headers: Headers | undefined + ): APIError { + return APIError.generate(status, errorResponse, message, headers); + } - buildRequest(opts: FinalRequestOptions): { req: RequestInit, url: string } { - const url = new URL(this.baseURL + opts.path!) - const { method, body } = opts; - const reqHeaders: Record = { - ...this.defaultHeaders(), ...this.customHeaders, - }; - const httpAgent: Agent | undefined = defaultHttpAgent - const req: RequestInit = { - method, - body: JSON.stringify(parseBody(body)), - headers: reqHeaders, - ...(httpAgent && { agent: httpAgent }) - } - return { req: req, url: url.toString() } + async request(opts: FinalRequestOptions): Promise { + // Build the request. + const { req, url } = this.buildRequest(opts); + // Make the call to rubeus. + const response = await this.fetch(url, req).catch(castToError); + // Parse the response and check for errors. + if (response instanceof Error) { + if (response.name === 'AbortError') { + throw new APIConnectionTimeoutError(); + } + throw new APIConnectionError({ cause: response }); } - - methodRequest(method: HTTPMethod, path: string, opts?: RequestOptions): APIPromise { - return new APIPromise(this.request({ method, path, ...opts })) + this.responseHeaders = createResponseHeaders(response.headers); + if (!response.ok) { + const errText = await response.text().catch(() => 'Unknown'); + const errJSON = safeJSON(errText); + const errMessage = errJSON ? undefined : errText; + throw this.generateError( + response.status, + errJSON, + errMessage, + this.responseHeaders + ); } -} \ No newline at end of file + // Receive and format the response. + return { response, options: opts, responseHeaders: response.headers }; + } + + buildRequest(opts: FinalRequestOptions): { req: RequestInit; url: string } { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const url = new URL(this.baseURL + opts.path!); + const { method, body } = opts; + const reqHeaders: Record = { + ...this.defaultHeaders(), + ...this.customHeaders, + }; + const httpAgent: Agent | undefined = defaultHttpAgent; + const req: RequestInit = { + method, + body: JSON.stringify(parseBody(body)), + headers: reqHeaders, + ...(httpAgent && { agent: httpAgent }), + }; + return { req: req, url: url.toString() }; + } + + methodRequest( + method: HTTPMethod, + path: string, + opts?: RequestOptions + ): APIPromise { + return new APIPromise(this.request({ method, path, ...opts })); + } +} diff --git a/src/client.ts b/src/client.ts index 89f05b2..f53780e 100644 --- a/src/client.ts +++ b/src/client.ts @@ -1,163 +1,160 @@ -import { ApiClientInterface } from "./_types/generalTypes"; -import * as API from "./apis"; -import { PostBodyParams, PostResponse } from "./apis/postMethod"; -import { ApiClient, APIPromise, RequestOptions } from "./baseClient"; -import { MISSING_API_KEY_ERROR_MESSAGE, PORTKEY_BASE_URL } from "./constants"; -import { Stream } from "./streaming"; -import { castToError, readEnv } from "./utils"; +import { ApiClientInterface } from './_types/generalTypes'; +import * as API from './apis'; +import { PostBodyParams, PostResponse } from './apis/postMethod'; +import { ApiClient, APIPromise, RequestOptions } from './baseClient'; +import { MISSING_API_KEY_ERROR_MESSAGE, PORTKEY_BASE_URL } from './constants'; +import { Stream } from './streaming'; +import { castToError, readEnv } from './utils'; export class Portkey extends ApiClient { - declare apiKey: string | null; - declare baseURL: string; - virtualKey: string | null; - config: Record | string | null | undefined; - provider: string | null | undefined; - traceID: string | null | undefined; - metadata: Record | null | undefined; - Authorization?: string; - cacheForceRefresh?: boolean | null | undefined; - debug?: boolean | null | undefined; - customHost?: string | null | undefined; - openaiProject?: string | null | undefined; - openaiOrganization?: string | null | undefined; - awsSecretAccessKey?: string | null | undefined; - awsAccessKeyId?: string | null | undefined; - awsSessionToken?: string | null | undefined; - awsRegion?: string | null | undefined; - vertexProjectId?: string | null | undefined; - vertexRegion?: string | null | undefined; - workersAiAccountId?: string | null | undefined; - azureResourceName?: string | null | undefined; - azureDeploymentId?: string | null | undefined; - azureApiVersion?: string | null | undefined; - huggingfaceBaseUrl?: string | null | undefined; - forwardHeaders?: Array | null | undefined; - requestTimeout?: number | null | undefined; - cacheNamespace?: string | null | undefined; - strictOpenAiCompliance?: boolean | null | undefined; - constructor({ - apiKey = readEnv("PORTKEY_API_KEY") ?? null, - baseURL = readEnv("PORTKEY_BASE_URL") ?? null, - config, - virtualKey, - provider, - traceID, - metadata, - Authorization, - cacheForceRefresh, - debug, - customHost, - openaiProject, - openaiOrganization, - awsSecretAccessKey, - awsAccessKeyId, - awsSessionToken, - awsRegion, - vertexProjectId, - vertexRegion, - workersAiAccountId, - azureResourceName, - azureDeploymentId, - azureApiVersion, - huggingfaceBaseUrl, - forwardHeaders, - cacheNamespace, - requestTimeout, - strictOpenAiCompliance, - }: ApiClientInterface) { + declare apiKey: string | null; + declare baseURL: string; + virtualKey: string | null; + config: Record | string | null | undefined; + provider: string | null | undefined; + traceID: string | null | undefined; + metadata: Record | null | undefined; + Authorization?: string; + cacheForceRefresh?: boolean | null | undefined; + debug?: boolean | null | undefined; + customHost?: string | null | undefined; + openaiProject?: string | null | undefined; + openaiOrganization?: string | null | undefined; + awsSecretAccessKey?: string | null | undefined; + awsAccessKeyId?: string | null | undefined; + awsSessionToken?: string | null | undefined; + awsRegion?: string | null | undefined; + vertexProjectId?: string | null | undefined; + vertexRegion?: string | null | undefined; + workersAiAccountId?: string | null | undefined; + azureResourceName?: string | null | undefined; + azureDeploymentId?: string | null | undefined; + azureApiVersion?: string | null | undefined; + huggingfaceBaseUrl?: string | null | undefined; + forwardHeaders?: Array | null | undefined; + requestTimeout?: number | null | undefined; + cacheNamespace?: string | null | undefined; + strictOpenAiCompliance?: boolean | null | undefined; + constructor({ + apiKey = readEnv('PORTKEY_API_KEY') ?? null, + baseURL = readEnv('PORTKEY_BASE_URL') ?? null, + config, + virtualKey, + provider, + traceID, + metadata, + Authorization, + cacheForceRefresh, + debug, + customHost, + openaiProject, + openaiOrganization, + awsSecretAccessKey, + awsAccessKeyId, + awsSessionToken, + awsRegion, + vertexProjectId, + vertexRegion, + workersAiAccountId, + azureResourceName, + azureDeploymentId, + azureApiVersion, + huggingfaceBaseUrl, + forwardHeaders, + cacheNamespace, + requestTimeout, + strictOpenAiCompliance, + }: ApiClientInterface) { + super({ + apiKey, + baseURL, + config, + virtualKey, + provider, + traceID, + metadata, + Authorization, + cacheForceRefresh, + debug, + customHost, + cacheNamespace, + openaiProject, + openaiOrganization, + awsSecretAccessKey, + awsAccessKeyId, + awsSessionToken, + awsRegion, + vertexProjectId, + vertexRegion, + workersAiAccountId, + azureResourceName, + azureDeploymentId, + azureApiVersion, + huggingfaceBaseUrl, + forwardHeaders, + requestTimeout, + strictOpenAiCompliance, + }); - super({ - apiKey, - baseURL, - config, - virtualKey, - provider, - traceID, - metadata, - Authorization, - cacheForceRefresh, - debug, - customHost, - cacheNamespace, - openaiProject, - openaiOrganization, - awsSecretAccessKey, - awsAccessKeyId, - awsSessionToken, - awsRegion, - vertexProjectId, - vertexRegion, - workersAiAccountId, - azureResourceName, - azureDeploymentId, - azureApiVersion, - huggingfaceBaseUrl, - forwardHeaders, - requestTimeout, - strictOpenAiCompliance, - }); + this.apiKey = apiKey; + if (!this.apiKey) { + throw castToError(MISSING_API_KEY_ERROR_MESSAGE); + } + this.virtualKey = virtualKey || null; + this.config = config || null; + this.baseURL = baseURL || PORTKEY_BASE_URL; + this.provider = provider; + this.traceID = traceID; + this.metadata = metadata; + this.cacheForceRefresh = cacheForceRefresh; + this.debug = debug; + this.customHost = customHost; + this.cacheNamespace = cacheNamespace; + this.openaiProject = openaiProject; + this.openaiOrganization = openaiOrganization; + this.awsSecretAccessKey = awsSecretAccessKey; + this.awsAccessKeyId = awsAccessKeyId; + this.awsSessionToken = awsSessionToken; + this.awsRegion = awsRegion; + this.vertexProjectId = vertexProjectId; + this.vertexRegion = vertexRegion; + this.workersAiAccountId = workersAiAccountId; + this.azureResourceName = azureResourceName; + this.azureDeploymentId = azureDeploymentId; + this.azureApiVersion = azureApiVersion; + this.huggingfaceBaseUrl = huggingfaceBaseUrl; + this.forwardHeaders = forwardHeaders; + this.requestTimeout = requestTimeout; + this.strictOpenAiCompliance = strictOpenAiCompliance; + } - this.apiKey = apiKey; - if (!this.apiKey) { - throw castToError(MISSING_API_KEY_ERROR_MESSAGE) - } - this.virtualKey = virtualKey || null - this.config = config || null - this.baseURL = baseURL || PORTKEY_BASE_URL; - this.provider = provider - this.traceID = traceID - this.metadata = metadata - this.cacheForceRefresh = cacheForceRefresh; - this.debug = debug; - this.customHost = customHost; - this.cacheNamespace = cacheNamespace;; - this.openaiProject = openaiProject; - this.openaiOrganization = openaiOrganization; - this.awsSecretAccessKey = awsSecretAccessKey; - this.awsAccessKeyId = awsAccessKeyId; - this.awsSessionToken = awsSessionToken; - this.awsRegion = awsRegion; - this.vertexProjectId = vertexProjectId; - this.vertexRegion = vertexRegion; - this.workersAiAccountId = workersAiAccountId; - this.azureResourceName = azureResourceName; - this.azureDeploymentId = azureDeploymentId; - this.azureApiVersion = azureApiVersion; - this.huggingfaceBaseUrl = huggingfaceBaseUrl; - this.forwardHeaders = forwardHeaders; - this.requestTimeout = requestTimeout; - this.strictOpenAiCompliance = strictOpenAiCompliance; - } + completions: API.Completions = new API.Completions(this); + chat = new API.Chat(this); + embeddings = new API.Embeddings(this); + files = new API.MainFiles(this); + images = new API.Images(this); + models = new API.Models(this); + generations = new API.Generations(this); + prompts = new API.Prompt(this); + feedback = new API.Feedback(this); + batches = new API.Batches(this); + fineTuning = new API.FineTuning(this); + moderations = new API.Moderations(this); + audio = new API.Audio(this); + uploads = new API.Uploads(this); + beta = { + assistants: new API.Assistants(this), + threads: new API.Threads(this), + vectorStores: new API.VectorStores(this), + chat: new API.BetaChat(this), + }; - completions: API.Completions = new API.Completions(this); - chat = new API.Chat(this); - embeddings = new API.Embeddings(this); - files = new API.MainFiles(this); - images = new API.Images(this); - models = new API.Models(this); - generations = new API.Generations(this); - prompts = new API.Prompt(this); - feedback = new API.Feedback(this); - batches = new API.Batches(this); - fineTuning = new API.FineTuning(this); - moderations = new API.Moderations(this); - audio = new API.Audio(this); - uploads = new API.Uploads(this); - beta = { - assistants: new API.Assistants(this), - threads: new API.Threads(this), - vectorStores: new API.VectorStores(this), - chat: new API.BetaChat(this), - }; - - - post = ( - url: string, - _body: PostBodyParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise> | APIPromise => { - return new API.postMethod(this).create(url, _body, params, opts) - }; - -} \ No newline at end of file + post = ( + url: string, + _body: PostBodyParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise> | APIPromise => { + return new API.postMethod(this).create(url, _body, params, opts); + }; +} diff --git a/src/constants.ts b/src/constants.ts index 7d0aed1..7d5e595 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -7,35 +7,36 @@ Here's how you get it: 1. Visit https://app.portkey.ai/ 1. Click on your profile icon on the top left 2. From the dropdown menu, click on "Copy API Key" -` +`; export const MISSING_BASE_URL = `No Base url provided. Please provide a valid base url. For example: https://api.portkey.ai -` +`; -export const MISSING_CONFIG_MESSAGE = "The 'config' parameter is not set. Please provide a valid Config object" - -export const MISSING_MODE_MESSAGE = "The 'mode' parameter is not set. Please provide a valid mode literal." +export const MISSING_CONFIG_MESSAGE = + "The 'config' parameter is not set. Please provide a valid Config object"; +export const MISSING_MODE_MESSAGE = + "The 'mode' parameter is not set. Please provide a valid mode literal."; export const INVALID_PORTKEY_MODE = `Argument of type '{}' cannot be assigned to parameter "mode" of \ type "ModesLiteral | Modes | None" -` +`; -export const DEFAULT_MAX_RETRIES = 2 -export const DEFAULT_TIMEOUT = 60 -export const PORTKEY_HEADER_PREFIX = "x-portkey-" -export const PORTKEY_BASE_URL = "https://api.portkey.ai/v1" -export const PORTKEY_GATEWAY_URL = PORTKEY_BASE_URL +export const DEFAULT_MAX_RETRIES = 2; +export const DEFAULT_TIMEOUT = 60; +export const PORTKEY_HEADER_PREFIX = 'x-portkey-'; +export const PORTKEY_BASE_URL = 'https://api.portkey.ai/v1'; +export const PORTKEY_GATEWAY_URL = PORTKEY_BASE_URL; -export const PORTKEY_API_KEY_ENV = "PORTKEY_API_KEY" -export const PORTKEY_PROXY_ENV = "PORTKEY_PROXY" +export const PORTKEY_API_KEY_ENV = 'PORTKEY_API_KEY'; +export const PORTKEY_PROXY_ENV = 'PORTKEY_PROXY'; -export const OPEN_AI_API_KEY = "DUMMY-KEY" +export const OPEN_AI_API_KEY = 'DUMMY-KEY'; // API routes -export const CHAT_COMPLETE_API = "/chat/completions" -export const TEXT_COMPLETE_API = "/completions" -export const PROMPT_API = "/prompt/complete" -export const FEEDBACK_API = "/feedback" -export const EMBEDDINGS_API = "/embeddings" \ No newline at end of file +export const CHAT_COMPLETE_API = '/chat/completions'; +export const TEXT_COMPLETE_API = '/completions'; +export const PROMPT_API = '/prompt/complete'; +export const FEEDBACK_API = '/feedback'; +export const EMBEDDINGS_API = '/embeddings'; diff --git a/src/error.ts b/src/error.ts index ee25362..78f39bc 100644 --- a/src/error.ts +++ b/src/error.ts @@ -1,132 +1,138 @@ -import { Headers } from "./_types/generalTypes"; -import { castToError } from "./utils"; +import { Headers } from './_types/generalTypes'; +import { castToError } from './utils'; export class APIError extends Error { - readonly status: number | undefined; - readonly headers: Headers | undefined; - readonly error: Object | undefined; - - constructor ( - status: number | undefined, - error: Object | undefined, - message: string | undefined, - headers: Headers | undefined, - ) { - super(APIError.makeMessage(error, message)); - this.status = status; - this.headers = headers; - this.error = error; - } - - private static makeMessage (error: any, message: string | undefined) { - return ( - error?.message ? - typeof error.message === "string" ? error.message - : JSON.stringify(error.message) - : error ? JSON.stringify(error) - : message || "Unknown error occurred" - ); - } - - static generate ( - status: number | undefined, - errorResponse: Object | undefined, - message: string | undefined, - headers: Headers | undefined, - ) { - if (!status) { - return new APIConnectionError({ cause: castToError(errorResponse) }); - } - - const error = errorResponse as Record; - - if (status === 400) { - return new BadRequestError(status, error, message, headers); - } - - if (status === 401) { - return new AuthenticationError(status, error, message, headers); - } - - if (status === 403) { - return new PermissionDeniedError(status, error, message, headers); - } - - if (status === 404) { - return new NotFoundError(status, error, message, headers); - } - - if (status === 409) { - return new ConflictError(status, error, message, headers); - } - - if (status === 422) { - return new UnprocessableEntityError(status, error, message, headers); - } - - if (status === 429) { - return new RateLimitError(status, error, message, headers); - } - - if (status >= 500) { - return new InternalServerError(status, error, message, headers); - } - - return new APIError(status, error, message, headers); - } + readonly status: number | undefined; + readonly headers: Headers | undefined; + readonly error: Object | undefined; + + constructor( + status: number | undefined, + error: Object | undefined, + message: string | undefined, + headers: Headers | undefined + ) { + super(APIError.makeMessage(error, message)); + this.status = status; + this.headers = headers; + this.error = error; + } + + private static makeMessage(error: any, message: string | undefined) { + return error?.message + ? typeof error.message === 'string' + ? error.message + : JSON.stringify(error.message) + : error + ? JSON.stringify(error) + : message || 'Unknown error occurred'; + } + + static generate( + status: number | undefined, + errorResponse: Object | undefined, + message: string | undefined, + headers: Headers | undefined + ) { + if (!status) { + return new APIConnectionError({ cause: castToError(errorResponse) }); + } + + const error = errorResponse as Record; + + if (status === 400) { + return new BadRequestError(status, error, message, headers); + } + + if (status === 401) { + return new AuthenticationError(status, error, message, headers); + } + + if (status === 403) { + return new PermissionDeniedError(status, error, message, headers); + } + + if (status === 404) { + return new NotFoundError(status, error, message, headers); + } + + if (status === 409) { + return new ConflictError(status, error, message, headers); + } + + if (status === 422) { + return new UnprocessableEntityError(status, error, message, headers); + } + + if (status === 429) { + return new RateLimitError(status, error, message, headers); + } + + if (status >= 500) { + return new InternalServerError(status, error, message, headers); + } + + return new APIError(status, error, message, headers); + } } export class APIUserAbortError extends APIError { - override readonly status: undefined = undefined; + override readonly status: undefined = undefined; - constructor ({ message }: { message?: string } = {}) { - super(undefined, undefined, message || "Request was aborted.", undefined); - } + constructor({ message }: { message?: string } = {}) { + super(undefined, undefined, message || 'Request was aborted.', undefined); + } } export class APIConnectionError extends APIError { - override readonly status: undefined = undefined; - - constructor ({ message, cause }: { message?: string; cause?: Error | undefined }) { - super(undefined, undefined, message || "Connection error.", undefined); - // in some environments the 'cause' property is already declared - // @ts-ignore - if (cause) this.cause = cause; - } + override readonly status: undefined = undefined; + + constructor({ + message, + cause, + }: { + message?: string; + cause?: Error | undefined; + }) { + super(undefined, undefined, message || 'Connection error.', undefined); + // in some environments the 'cause' property is already declared + // @ts-ignore + if (cause) this.cause = cause; + } } export class APIConnectionTimeoutError extends APIConnectionError { - constructor ({ message }: { message?: string } = {}) { - super({ message: message ?? "Request timed out." }); - } + constructor({ message }: { message?: string } = {}) { + super({ message: message ?? 'Request timed out.' }); + } } export class BadRequestError extends APIError { - override readonly status: 400 = 400; + override readonly status: 400 = 400; } export class AuthenticationError extends APIError { - override readonly status: 401 = 401; + override readonly status: 401 = 401; } export class PermissionDeniedError extends APIError { - override readonly status: 403 = 403; + override readonly status: 403 = 403; } export class NotFoundError extends APIError { - override readonly status: 404 = 404; + override readonly status: 404 = 404; } export class ConflictError extends APIError { - override readonly status: 409 = 409; + override readonly status: 409 = 409; } export class UnprocessableEntityError extends APIError { - override readonly status: 422 = 422; + override readonly status: 422 = 422; } export class RateLimitError extends APIError { - override readonly status: 429 = 429; + override readonly status: 429 = 429; } -export class InternalServerError extends APIError { } +export class InternalServerError extends APIError {} diff --git a/src/index.ts b/src/index.ts index 2eb8507..70f3e85 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,9 +1,9 @@ -import * as apis from "./apis"; -import * as client from "./client"; -import * as consts from "./constants"; +import * as apis from './apis'; +import * as client from './client'; +import * as consts from './constants'; export import Portkey = client.Portkey; -export import PORTKEY_GATEWAY_URL = consts.PORTKEY_GATEWAY_URL -export import createHeaders = apis.createHeaders +export import PORTKEY_GATEWAY_URL = consts.PORTKEY_GATEWAY_URL; +export import createHeaders = apis.createHeaders; export default Portkey; diff --git a/src/streaming.ts b/src/streaming.ts index f05c368..86ddbdb 100644 --- a/src/streaming.ts +++ b/src/streaming.ts @@ -1,154 +1,156 @@ -import { Fetch } from "./baseClient"; -import { APIError } from "./error"; +import { Fetch } from './baseClient'; +import { APIError } from './error'; type Bytes = string | ArrayBuffer | Uint8Array | Buffer | null | undefined; type ServerSentEvent = { - event: string | null; - data: string; - raw: string[]; + event: string | null; + data: string; + raw: string[]; }; export const safeJSON = (text: string) => { - try { - return JSON.parse(text); - } catch (err) { - return undefined; - } + try { + return JSON.parse(text); + } catch (err) { + return undefined; + } }; export const createResponseHeaders = ( - headers: Awaited>["headers"], + headers: Awaited>['headers'] ): Record => { - return new Proxy( - Object.fromEntries( - // @ts-ignore - headers.entries(), - ), - { - get(target, name) { - const key = name.toString(); - return target[key.toLowerCase()] || target[key]; - }, - }, - ); + return new Proxy( + Object.fromEntries( + // @ts-ignore + headers.entries() + ), + { + get(target, name) { + const key = name.toString(); + return target[key.toLowerCase()] || target[key]; + }, + } + ); }; - export class Stream implements AsyncIterable { - - private response: Response; - private decoder: SSEDecoder; - - constructor(response: Response) { - this.response = response; - this.decoder = new SSEDecoder(); - } - - private async *iterMessages(): AsyncGenerator { - if (!this.response.body) { - throw new Error("Attempted to iterate over a response with no body"); - } - const lineDecoder = new LineDecoder(); - - const iter = readableStreamAsyncIterable(this.response.body); - for await (const chunk of iter) { - for (const line of lineDecoder.decode(chunk)) { - const sse = this.decoder.decode(line); - if (sse) yield sse; - } - } - - for (const line of lineDecoder.flush()) { - const sse = this.decoder.decode(line); - if (sse) yield sse; - } - } - - async *[Symbol.asyncIterator](): AsyncIterator { - try { - for await (const sse of this.iterMessages()) { - if (sse.data.startsWith('[DONE]')) { - continue; - } - if (sse.event === null) { - try { - yield JSON.parse(sse.data) - } catch (e) { - console.error("Could not parse message into JSON:", sse.data); - console.error("From chunk:", sse.raw); - throw e; - } - } - - if (sse.event === "ping") { - continue; - } - - if (sse.event === "error") { - throw APIError - } - } - } catch (e) { - if (e instanceof Error && e.name === "AbortError") return; - throw e; - } - } + private response: Response; + private decoder: SSEDecoder; + + constructor(response: Response) { + this.response = response; + this.decoder = new SSEDecoder(); + } + + private async *iterMessages(): AsyncGenerator< + ServerSentEvent, + void, + unknown + > { + if (!this.response.body) { + throw new Error('Attempted to iterate over a response with no body'); + } + const lineDecoder = new LineDecoder(); + + const iter = readableStreamAsyncIterable(this.response.body); + for await (const chunk of iter) { + for (const line of lineDecoder.decode(chunk)) { + const sse = this.decoder.decode(line); + if (sse) yield sse; + } + } + + for (const line of lineDecoder.flush()) { + const sse = this.decoder.decode(line); + if (sse) yield sse; + } + } + + async *[Symbol.asyncIterator](): AsyncIterator { + try { + for await (const sse of this.iterMessages()) { + if (sse.data.startsWith('[DONE]')) { + continue; + } + if (sse.event === null) { + try { + yield JSON.parse(sse.data); + } catch (e) { + console.error('Could not parse message into JSON:', sse.data); + console.error('From chunk:', sse.raw); + throw e; + } + } + + if (sse.event === 'ping') { + continue; + } + + if (sse.event === 'error') { + throw APIError; + } + } + } catch (e) { + if (e instanceof Error && e.name === 'AbortError') return; + throw e; + } + } } class SSEDecoder { - private data: string[]; - private event: string | null; - private chunks: string[]; - - constructor() { - this.event = null; - this.data = []; - this.chunks = []; - } - - decode(line: string) { - if (line.endsWith("\r")) { - line = line.substring(0, line.length - 1); - } - - if (!line) { - // empty line and we didn't previously encounter any messages - if (!this.event && !this.data.length) return null; - - const sse: ServerSentEvent = { - event: this.event, - data: this.data.join("\n"), - raw: this.chunks, - }; - - this.event = null; - this.data = []; - this.chunks = []; - - return sse; - } - - this.chunks.push(line); - - if (line.startsWith(":")) { - return null; - } - - let [fieldname, _, value] = partition(line, ":"); - - if (value.startsWith(" ")) { - value = value.substring(1); - } - - if (fieldname === "event") { - this.event = value; - } else if (fieldname === "data") { - this.data.push(value); - } - - return null; - } + private data: string[]; + private event: string | null; + private chunks: string[]; + + constructor() { + this.event = null; + this.data = []; + this.chunks = []; + } + + decode(line: string) { + if (line.endsWith('\r')) { + line = line.substring(0, line.length - 1); + } + + if (!line) { + // empty line and we didn't previously encounter any messages + if (!this.event && !this.data.length) return null; + + const sse: ServerSentEvent = { + event: this.event, + data: this.data.join('\n'), + raw: this.chunks, + }; + + this.event = null; + this.data = []; + this.chunks = []; + + return sse; + } + + this.chunks.push(line); + + if (line.startsWith(':')) { + return null; + } + + let [fieldname, _, value] = partition(line, ':'); + + if (value.startsWith(' ')) { + value = value.substring(1); + } + + if (fieldname === 'event') { + this.event = value; + } else if (fieldname === 'data') { + this.data.push(value); + } + + return null; + } } /** @@ -158,111 +160,117 @@ class SSEDecoder { * https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258 */ class LineDecoder { - // prettier-ignore - static NEWLINE_CHARS = new Set(["\n", "\r", "\x0b", "\x0c", "\x1c", "\x1d", "\x1e", "\x85", "\u2028", "\u2029"]); - static NEWLINE_REGEXP = /\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g; - - buffer: string[]; - trailingCR: boolean; - textDecoder: any; // TextDecoder found in browsers; not typed to avoid pulling in either "dom" or "node" types. - - constructor() { - this.buffer = []; - this.trailingCR = false; - } - - decode(chunk: Bytes): string[] { - let text = this.decodeText(chunk); - - if (this.trailingCR) { - text = "\r" + text; - this.trailingCR = false; - } - if (text.endsWith("\r")) { - this.trailingCR = true; - text = text.slice(0, -1); - } - - if (!text) { - return []; - } - - const trailingNewline = LineDecoder.NEWLINE_CHARS.has(text[text.length - 1] || ""); - let lines = text.split(LineDecoder.NEWLINE_REGEXP); - - if (lines.length === 1 && !trailingNewline) { - this.buffer.push(lines[0]!); - return []; - } - - if (this.buffer.length > 0) { - lines = [this.buffer.join("") + lines[0], ...lines.slice(1)]; - this.buffer = []; - } - - if (!trailingNewline) { - this.buffer = [lines.pop() || ""]; - } - - return lines; - } - - decodeText(bytes: Bytes): string { - if (bytes == null) return ""; - if (typeof bytes === "string") return bytes; - - // Node: - if (typeof Buffer !== "undefined") { - if (bytes instanceof Buffer) { - return bytes.toString(); - } - if (bytes instanceof Uint8Array) { - return Buffer.from(bytes) - .toString(); - } - - throw new Error( - `Unexpected: received non-Uint8Array (${bytes.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`, - ); - } - - // Browser - if (typeof TextDecoder !== "undefined") { - if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) { - this.textDecoder ??= new TextDecoder("utf8"); - return this.textDecoder.decode(bytes); - } - - throw new Error( - `Unexpected: received non-Uint8Array/ArrayBuffer (${(bytes as any).constructor.name - }) in a web platform. Please report this error.`, - ); - } - - throw new Error( - "Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.", - ); - } - - flush(): string[] { - if (!this.buffer.length && !this.trailingCR) { - return []; - } - - const lines = [this.buffer.join("")]; - this.buffer = []; - this.trailingCR = false; - return lines; - } + // prettier-ignore + static NEWLINE_CHARS = new Set(["\n", "\r", "\x0b", "\x0c", "\x1c", "\x1d", "\x1e", "\x85", "\u2028", "\u2029"]); + static NEWLINE_REGEXP = /\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g; + + buffer: string[]; + trailingCR: boolean; + textDecoder: any; // TextDecoder found in browsers; not typed to avoid pulling in either "dom" or "node" types. + + constructor() { + this.buffer = []; + this.trailingCR = false; + } + + decode(chunk: Bytes): string[] { + let text = this.decodeText(chunk); + + if (this.trailingCR) { + text = '\r' + text; + this.trailingCR = false; + } + if (text.endsWith('\r')) { + this.trailingCR = true; + text = text.slice(0, -1); + } + + if (!text) { + return []; + } + + const trailingNewline = LineDecoder.NEWLINE_CHARS.has( + text[text.length - 1] || '' + ); + let lines = text.split(LineDecoder.NEWLINE_REGEXP); + + if (lines.length === 1 && !trailingNewline) { + this.buffer.push(lines[0]!); + return []; + } + + if (this.buffer.length > 0) { + lines = [this.buffer.join('') + lines[0], ...lines.slice(1)]; + this.buffer = []; + } + + if (!trailingNewline) { + this.buffer = [lines.pop() || '']; + } + + return lines; + } + + decodeText(bytes: Bytes): string { + if (bytes == null) return ''; + if (typeof bytes === 'string') return bytes; + + // Node: + if (typeof Buffer !== 'undefined') { + if (bytes instanceof Buffer) { + return bytes.toString(); + } + if (bytes instanceof Uint8Array) { + return Buffer.from(bytes).toString(); + } + + throw new Error( + `Unexpected: received non-Uint8Array (${bytes.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.` + ); + } + + // Browser + if (typeof TextDecoder !== 'undefined') { + if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) { + this.textDecoder ??= new TextDecoder('utf8'); + return this.textDecoder.decode(bytes); + } + + throw new Error( + `Unexpected: received non-Uint8Array/ArrayBuffer (${ + (bytes as any).constructor.name + }) in a web platform. Please report this error.` + ); + } + + throw new Error( + 'Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.' + ); + } + + flush(): string[] { + if (!this.buffer.length && !this.trailingCR) { + return []; + } + + const lines = [this.buffer.join('')]; + this.buffer = []; + this.trailingCR = false; + return lines; + } } function partition(str: string, delimiter: string): [string, string, string] { - const index = str.indexOf(delimiter); - if (index !== -1) { - return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)]; - } - - return [str, "", ""]; + const index = str.indexOf(delimiter); + if (index !== -1) { + return [ + str.substring(0, index), + delimiter, + str.substring(index + delimiter.length), + ]; + } + + return [str, '', '']; } /** @@ -272,28 +280,28 @@ function partition(str: string, delimiter: string): [string, string, string] { * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490 */ function readableStreamAsyncIterable(stream: any): AsyncIterableIterator { - if (stream[Symbol.asyncIterator]) return stream; - - const reader = stream.getReader(); - return { - async next() { - try { - const result = await reader.read(); - if (result?.done) reader.releaseLock(); // release lock when stream becomes closed - return result; - } catch (e) { - reader.releaseLock(); // release lock when stream becomes errored - throw e; - } - }, - async return() { - const cancelPromise = reader.cancel(); - reader.releaseLock(); - await cancelPromise; - return { done: true, value: undefined }; - }, - [Symbol.asyncIterator]() { - return this; - }, - }; + if (stream[Symbol.asyncIterator]) return stream; + + const reader = stream.getReader(); + return { + async next() { + try { + const result = await reader.read(); + if (result?.done) reader.releaseLock(); // release lock when stream becomes closed + return result; + } catch (e) { + reader.releaseLock(); // release lock when stream becomes errored + throw e; + } + }, + async return() { + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; + return { done: true, value: undefined }; + }, + [Symbol.asyncIterator]() { + return this; + }, + }; } diff --git a/src/utils.ts b/src/utils.ts index 3a718c0..f690192 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,132 +1,140 @@ -import { OPEN_AI_API_KEY, PORTKEY_HEADER_PREFIX } from "./constants"; -import { createResponseHeaders } from "./streaming"; -import OpenAI from "openai"; -import type { Portkey } from "./index"; +import { OPEN_AI_API_KEY, PORTKEY_HEADER_PREFIX } from './constants'; +import { createResponseHeaders } from './streaming'; +import OpenAI from 'openai'; +import type { Portkey } from './index'; type PlatformProperties = { - "x-portkey-runtime"?: string, - "x-portkey-runtime-version"?: string, -} + 'x-portkey-runtime'?: string; + 'x-portkey-runtime-version'?: string; +}; export const getPlatformProperties = (): PlatformProperties => { - if (Object.prototype.toString.call(typeof process !== "undefined" ? process : 0) === "[object process]") { - return { - [`${PORTKEY_HEADER_PREFIX}runtime`]: "node", - [`${PORTKEY_HEADER_PREFIX}runtime-version`]: process.version, - }; - } - return {} -} - + if ( + Object.prototype.toString.call( + typeof process !== 'undefined' ? process : 0 + ) === '[object process]' + ) { + return { + [`${PORTKEY_HEADER_PREFIX}runtime`]: 'node', + [`${PORTKEY_HEADER_PREFIX}runtime-version`]: process.version, + }; + } + return {}; +}; export const readEnv = (env: string): string | undefined => { - if (typeof process !== "undefined") { - return process.env?.[env] ?? undefined; - } - return undefined; + if (typeof process !== 'undefined') { + return process.env?.[env] ?? undefined; + } + return undefined; }; export const castToError = (err: any): Error => { - if (err instanceof Error) return err; - return new Error(err); + if (err instanceof Error) return err; + return new Error(err); }; export const isEmpty = (value: unknown) => { - // Check if the value is null or undefined - if (value == null) { - return true; - } - - // Check if the value is a string and has zero length - if (typeof value === 'string' && value.trim().length === 0) { - return true; - } - - // Check if the value is an array and has zero elements - if (Array.isArray(value) && value.length === 0) { - return true; - } - - // Check if the value is an object and has zero keys - if (typeof value === 'object' && Object.keys(value).length === 0) { - return true; - } - - // If none of the above conditions are met, the value is not empty - return false; -} + // Check if the value is null or undefined + if (value == null) { + return true; + } + + // Check if the value is a string and has zero length + if (typeof value === 'string' && value.trim().length === 0) { + return true; + } + + // Check if the value is an array and has zero elements + if (Array.isArray(value) && value.length === 0) { + return true; + } + + // Check if the value is an object and has zero keys + if (typeof value === 'object' && Object.keys(value).length === 0) { + return true; + } + + // If none of the above conditions are met, the value is not empty + return false; +}; export const getPortkeyHeader = (key: string): string => { - return `${PORTKEY_HEADER_PREFIX}${key}` -} + return `${PORTKEY_HEADER_PREFIX}${key}`; +}; -type Config = Record | string | null | undefined +type Config = Record | string | null | undefined; -export const overrideConfig = (initialConfig?: Config, updatedConfig?: Config): Config => { - if (isEmpty(updatedConfig)) { - return initialConfig - } - return updatedConfig -} +export const overrideConfig = ( + initialConfig?: Config, + updatedConfig?: Config +): Config => { + if (isEmpty(updatedConfig)) { + return initialConfig; + } + return updatedConfig; +}; +export const parseBody = ( + data: Record | undefined | null +): Record => { + // Making sure that every key in the body is in snake case + if (isEmpty(data)) { + return {}; + } + const parsedData: Record = {}; + for (let k in data) { + const v = data[k]; + // convert to snakecase + k = k + .replace('ID', 'Id') + .replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`); + + parsedData[k] = v; + } + return parsedData; +}; -export const parseBody = (data: Record | undefined | null): Record => { - // Making sure that every key in the body is in snake case - if (isEmpty(data)) { - return {} - } - const parsedData: Record = {} - for (let k in data) { - const v = data[k] - // convert to snakecase - k = k.replace('ID', 'Id') - .replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`) - - parsedData[k] = v - } - return parsedData +export function finalResponse(response: any) { + const headers = portkeyHeaders(response.response.headers); + const json = { + ...(response.data?.body || response.data), + getHeaders: () => headers, + }; + return json; } -export function finalResponse(response:any) { +export function portkeyHeaders(headers: any) { + const parsedHeaders = createResponseHeaders(headers); + const prefix = PORTKEY_HEADER_PREFIX; + const filteredHeaders = Object.entries(parsedHeaders) + .filter(([key, _]) => key.startsWith(prefix)) // eslint-disable-line @typescript-eslint/no-unused-vars + .map(([key, value]) => [key.replace(prefix, ''), value]); - const headers = portkeyHeaders(response.response.headers); - const json = { - ...response.data?.body || response.data, - getHeaders: () => headers - } - return json + return Object.fromEntries(filteredHeaders); } -export function portkeyHeaders(headers:any) { - - const parsedHeaders = createResponseHeaders(headers); - const prefix = PORTKEY_HEADER_PREFIX - const filteredHeaders = Object.entries(parsedHeaders) - .filter(([key, _]) => key.startsWith(prefix)) - .map(([key, value]) => [key.replace(prefix, ''), value]) - - return Object.fromEntries(filteredHeaders) +export function defaultHeadersBuilder(client: any) { + const customHeaders = client.customHeaders; + const portkeyHeaders = client.portkeyHeaders; + + // Logic to add Bearer only if it is not present. + // Else it would be added everytime a request is made + if ( + Object.prototype.hasOwnProperty.call(customHeaders, 'authorization') && + !customHeaders['authorization'].startsWith('Bearer') + ) { + client.customHeaders['authorization'] = + 'Bearer ' + client.customHeaders['authorization']; + } + + return { ...customHeaders, ...portkeyHeaders }; } -export function defaultHeadersBuilder(client: any){ - - const customHeaders = client.customHeaders - const portkeyHeaders = client.portkeyHeaders - - // Logic to add Bearer only if it is not present. - // Else it would be added everytime a request is made - if (Object.prototype.hasOwnProperty.call(customHeaders, "authorization") && !customHeaders["authorization"].startsWith("Bearer")){ - client.customHeaders["authorization"] = - "Bearer " + client.customHeaders["authorization"]; - } - - return {...customHeaders, ...portkeyHeaders} +export function initOpenAIClient(client: Portkey) { + return new OpenAI({ + apiKey: client.apiKey || readEnv('OPENAI_API_KEY') || OPEN_AI_API_KEY, + baseURL: client.baseURL, + defaultHeaders: defaultHeadersBuilder(client), + maxRetries: 0, + }); } - -export function initOpenAIClient(client: Portkey){ - return new OpenAI({ - apiKey: client.apiKey || readEnv("OPENAI_API_KEY") || OPEN_AI_API_KEY, - baseURL: client.baseURL, - defaultHeaders: defaultHeadersBuilder(client), - maxRetries: 0 - }) -} \ No newline at end of file diff --git a/src/version.ts b/src/version.ts index f4c159d..91feea3 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1 +1 @@ -export const VERSION = "1.4.0-rc.1"; \ No newline at end of file +export const VERSION = '1.4.0-rc.1'; From 19be3cf227899e06da9b7d62b37bac706f0fb83e Mon Sep 17 00:00:00 2001 From: csgulati09 Date: Mon, 23 Sep 2024 17:30:50 +0530 Subject: [PATCH 2/5] fix: body and query type for linting --- src/apis/assistants.ts | 2 +- src/apis/images.ts | 2 +- src/apis/moderations.ts | 5 ++--- src/apis/threads.ts | 10 +++++----- src/apis/uploads.ts | 5 ++--- src/apis/vectorStores.ts | 4 +--- 6 files changed, 12 insertions(+), 16 deletions(-) diff --git a/src/apis/assistants.ts b/src/apis/assistants.ts index c987065..0982ef8 100644 --- a/src/apis/assistants.ts +++ b/src/apis/assistants.ts @@ -88,7 +88,7 @@ export class Assistants extends ApiResource { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore const result = await OAIclient.beta.assistants - .list(query, opts) + .list(query as any, opts) .withResponse(); return finalResponse(result); diff --git a/src/apis/images.ts b/src/apis/images.ts index 46ed357..398c9fc 100644 --- a/src/apis/images.ts +++ b/src/apis/images.ts @@ -111,7 +111,7 @@ export class Images extends ApiResource { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore const result = await OAIclient.images - .createVariation(body, opts) + .createVariation(body as any, opts) .withResponse(); return finalResponse(result); diff --git a/src/apis/moderations.ts b/src/apis/moderations.ts index 8860392..da64cad 100644 --- a/src/apis/moderations.ts +++ b/src/apis/moderations.ts @@ -1,4 +1,3 @@ -import { ModerationCreateParams } from 'openai/resources'; import { ApiClientInterface } from '../_types/generalTypes'; import { ApiResource } from '../apiResource'; import { RequestOptions } from '../baseClient'; @@ -7,11 +6,11 @@ import { createHeaders } from './createHeaders'; export class Moderations extends ApiResource { async create( - _body: ModerationCreateParams, + _body: any, params?: ApiClientInterface, opts?: RequestOptions ): Promise { - const body: ModerationCreateParams = _body; + const body: any = _body; if (params) { const config = overrideConfig(this.client.config, params.config); this.client.customHeaders = { diff --git a/src/apis/threads.ts b/src/apis/threads.ts index 34e8a85..abe6538 100644 --- a/src/apis/threads.ts +++ b/src/apis/threads.ts @@ -33,7 +33,7 @@ export class Threads extends ApiResource { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore const result = await OAIclient.beta.threads - .create(body, opts) + .create(body as any, opts) .withResponse(); return finalResponse(result); @@ -191,7 +191,7 @@ export class Messages extends ApiResource { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore const result = await OAIclient.beta.threads.messages - .create(threadId, body, opts) + .create(threadId, body as any, opts) .withResponse(); return finalResponse(result); @@ -216,7 +216,7 @@ export class Messages extends ApiResource { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore const result = await OAIclient.beta.threads.messages - .list(threadId, query, opts) + .list(threadId, query as any, opts) .withResponse(); return finalResponse(result); @@ -322,7 +322,7 @@ export class Runs extends ApiResource { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore const result = await OAIclient.beta.threads.runs - .list(threadId, query, opts) + .list(threadId, query as any, opts) .withResponse(); return finalResponse(result); @@ -601,7 +601,7 @@ export class Steps extends ApiResource { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore const result = await OAIclient.beta.threads.runs.steps - .list(threadId, runId, query, opts) + .list(threadId, runId, query as any, opts) .withResponse(); return finalResponse(result); diff --git a/src/apis/uploads.ts b/src/apis/uploads.ts index 6b6fee7..4a80ed0 100644 --- a/src/apis/uploads.ts +++ b/src/apis/uploads.ts @@ -3,7 +3,6 @@ import { ApiResource } from '../apiResource'; import { RequestOptions } from '../baseClient'; import { finalResponse, initOpenAIClient, overrideConfig } from '../utils'; import { createHeaders } from './createHeaders'; -import { UploadCompleteParams } from 'openai/resources'; import { Uploadable } from 'openai/uploads'; export class Uploads extends ApiResource { @@ -55,11 +54,11 @@ export class Uploads extends ApiResource { async complete( uploadId: string, - _body: UploadCompleteParams, + _body: any, params?: ApiClientInterface, opts?: RequestOptions ): Promise { - const body: UploadCompleteParams = _body; + const body: any = _body; if (params) { const config = overrideConfig(this.client.config, params.config); this.client.customHeaders = { diff --git a/src/apis/vectorStores.ts b/src/apis/vectorStores.ts index 54b5460..726eef0 100644 --- a/src/apis/vectorStores.ts +++ b/src/apis/vectorStores.ts @@ -194,10 +194,8 @@ export class Files extends ApiResource { } const OAIclient = initOpenAIClient(this.client); - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore const result = await OAIclient.beta.vectorStores.files - .list(vectorStoreId, query, opts) + .list(vectorStoreId, query as any, opts) .withResponse(); return finalResponse(result); From 776f2935326af1318ea3a9f02efa937e1439d06b Mon Sep 17 00:00:00 2001 From: csgulati09 Date: Wed, 25 Sep 2024 17:36:27 +0530 Subject: [PATCH 3/5] fix: merge conflicts --- package-lock.json | 4 +- package.json | 2 +- src/_types/generalTypes.ts | 57 ++++----- src/apis/betaChat.ts | 9 +- src/apis/moderations.ts | 15 ++- src/apis/uploads.ts | 16 ++- src/baseClient.ts | 75 ++---------- src/client.ts | 243 +++++++++++++++++++------------------ src/version.ts | 2 +- 9 files changed, 192 insertions(+), 231 deletions(-) diff --git a/package-lock.json b/package-lock.json index b9f7888..7ff188c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "portkey-ai", - "version": "1.4.0-rc.1", + "version": "1.4.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "portkey-ai", - "version": "1.4.0-rc.1", + "version": "1.4.0", "license": "MIT", "dependencies": { "agentkeepalive": "^4.5.0", diff --git a/package.json b/package.json index 998e451..25e61f6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "portkey-ai", - "version": "1.4.0-rc.1", + "version": "1.4.0", "description": "Node client library for the Portkey API", "types": "dist/src/index.d.ts", "main": "dist/src/index.js", diff --git a/src/_types/generalTypes.ts b/src/_types/generalTypes.ts index 49b9ac8..e63df04 100644 --- a/src/_types/generalTypes.ts +++ b/src/_types/generalTypes.ts @@ -1,34 +1,35 @@ export type Headers = Record; export interface ApiClientInterface { - apiKey?: string | null; - baseURL?: string | null; - virtualKey?: string | null | undefined; - config?: Record | string | null | undefined; - provider?: string | null | undefined; - traceID?: string | null | undefined; - metadata?: Record | null | undefined; - Authorization?: string | null | undefined; - cacheForceRefresh?: boolean | null | undefined; - debug?: boolean | null | undefined; - customHost?: string | null | undefined; - openaiProject?: string | null | undefined; - openaiOrganization?: string | null | undefined; - awsSecretAccessKey?: string | null | undefined; - awsAccessKeyId?: string | null | undefined; - awsSessionToken?: string | null | undefined; - awsRegion?: string | null | undefined; - vertexProjectId?: string | null | undefined; - vertexRegion?: string | null | undefined; - workersAiAccountId?: string | null | undefined; - azureResourceName?: string | null | undefined; - azureDeploymentId?: string | null | undefined; - azureApiVersion?: string | null | undefined; - huggingfaceBaseUrl?: string | null | undefined; - forwardHeaders?: Array | null | undefined; - cacheNamespace?: string | null | undefined; - requestTimeout?: number | null | undefined; - strictOpenAiCompliance?: boolean | null | undefined; + apiKey?: string | null; + baseURL?: string | null; + virtualKey?: string | null | undefined; + config?: Record | string | null | undefined; + provider?: string | null | undefined; + traceID?: string | null | undefined; + metadata?: Record | null | undefined; + Authorization?: string | null | undefined; + cacheForceRefresh?: boolean | null | undefined; + debug?: boolean | null | undefined; + customHost?: string | null | undefined; + openaiProject?: string | null | undefined; + openaiOrganization?: string | null | undefined; + awsSecretAccessKey?: string | null | undefined; + awsAccessKeyId?: string | null | undefined; + awsSessionToken?: string | null | undefined; + awsRegion?: string | null | undefined; + vertexProjectId?: string | null | undefined; + vertexRegion?: string | null | undefined; + workersAiAccountId?: string | null | undefined; + azureResourceName?: string | null | undefined; + azureDeploymentId?: string | null | undefined; + azureApiVersion?: string | null | undefined; + huggingfaceBaseUrl?: string | null | undefined; + forwardHeaders?: Array | null | undefined; + cacheNamespace?: string | null | undefined; + requestTimeout?: number | null | undefined; + strictOpenAiCompliance?: boolean | null | undefined; + anthropicBeta?: string | null | undefined; } export interface APIResponseType { diff --git a/src/apis/betaChat.ts b/src/apis/betaChat.ts index ac58edf..a0160a0 100644 --- a/src/apis/betaChat.ts +++ b/src/apis/betaChat.ts @@ -11,8 +11,9 @@ import { import { ChatCompletionStreamingFunctionRunnerParams, ChatCompletionStreamingToolRunnerParams, -} from 'openai/lib/ChatCompletionStreamingRunner'; -import { ChatCompletionParseParams } from 'openai/resources/beta/chat/completions'; +} from "openai/lib/ChatCompletionStreamingRunner"; +import { ChatCompletionParseParams } from "openai/resources/beta/chat/completions"; + export class BetaChat extends ApiResource { completions: Completions; @@ -24,7 +25,9 @@ export class BetaChat extends ApiResource { } export class Completions extends ApiResource { - async parse( + + async parse + ( _body: Params, params?: ApiClientInterface, opts?: RequestOptions diff --git a/src/apis/moderations.ts b/src/apis/moderations.ts index da64cad..1e4b255 100644 --- a/src/apis/moderations.ts +++ b/src/apis/moderations.ts @@ -1,8 +1,13 @@ -import { ApiClientInterface } from '../_types/generalTypes'; -import { ApiResource } from '../apiResource'; -import { RequestOptions } from '../baseClient'; -import { finalResponse, initOpenAIClient, overrideConfig } from '../utils'; -import { createHeaders } from './createHeaders'; +import { ApiClientInterface } from "../_types/generalTypes"; +import { ApiResource } from "../apiResource"; +import { RequestOptions } from "../baseClient"; +import { finalResponse, initOpenAIClient, overrideConfig } from "../utils"; +import { createHeaders } from "./createHeaders"; + +export interface ModerationCreateParams { + input: string | Array; + model?: any ; +} export class Moderations extends ApiResource { async create( diff --git a/src/apis/uploads.ts b/src/apis/uploads.ts index 4a80ed0..e3fcd3a 100644 --- a/src/apis/uploads.ts +++ b/src/apis/uploads.ts @@ -1,10 +1,14 @@ -import { ApiClientInterface } from '../_types/generalTypes'; -import { ApiResource } from '../apiResource'; -import { RequestOptions } from '../baseClient'; -import { finalResponse, initOpenAIClient, overrideConfig } from '../utils'; -import { createHeaders } from './createHeaders'; -import { Uploadable } from 'openai/uploads'; +import { ApiClientInterface } from "../_types/generalTypes"; +import { ApiResource } from "../apiResource"; +import { RequestOptions } from "../baseClient"; +import { finalResponse, initOpenAIClient, overrideConfig } from "../utils"; +import { createHeaders } from "./createHeaders"; +import { Uploadable } from "openai/uploads"; +export interface UploadCompleteParams { + part_ids: Array; + md5?: string; +} export class Uploads extends ApiResource { parts: Parts; diff --git a/src/baseClient.ts b/src/baseClient.ts index 16de783..1b5ed29 100644 --- a/src/baseClient.ts +++ b/src/baseClient.ts @@ -136,72 +136,15 @@ export abstract class ApiClient { responseHeaders: Record; portkeyHeaders: Record; - private fetch: Fetch; - constructor({ - apiKey, - baseURL, - config, - virtualKey, - traceID, - metadata, - provider, - Authorization, - cacheForceRefresh, - debug, - customHost, - openaiProject, - openaiOrganization, - awsSecretAccessKey, - awsAccessKeyId, - awsSessionToken, - awsRegion, - vertexProjectId, - vertexRegion, - workersAiAccountId, - azureResourceName, - azureDeploymentId, - azureApiVersion, - huggingfaceBaseUrl, - forwardHeaders, - cacheNamespace, - requestTimeout, - strictOpenAiCompliance, - }: ApiClientInterface) { - this.apiKey = apiKey ?? ''; - this.baseURL = baseURL ?? ''; - this.customHeaders = createHeaders({ - apiKey, - config, - virtualKey, - traceID, - metadata, - provider, - Authorization, - cacheForceRefresh, - debug, - customHost, - cacheNamespace, - openaiProject, - openaiOrganization, - awsSecretAccessKey, - awsAccessKeyId, - awsSessionToken, - awsRegion, - vertexProjectId, - vertexRegion, - workersAiAccountId, - azureResourceName, - azureDeploymentId, - azureApiVersion, - huggingfaceBaseUrl, - forwardHeaders, - requestTimeout, - strictOpenAiCompliance, - }); - this.portkeyHeaders = this.defaultHeaders(); - this.fetch = fetch; - this.responseHeaders = {}; - } + private fetch: Fetch; + constructor({ apiKey, baseURL, config, virtualKey, traceID, metadata, provider, Authorization, cacheForceRefresh, debug, customHost, openaiProject, openaiOrganization, awsSecretAccessKey, awsAccessKeyId, awsSessionToken, awsRegion, vertexProjectId, vertexRegion, workersAiAccountId, azureResourceName, azureDeploymentId, azureApiVersion, huggingfaceBaseUrl, forwardHeaders, cacheNamespace, requestTimeout, strictOpenAiCompliance, anthropicBeta }: ApiClientInterface) { + this.apiKey = apiKey ?? ""; + this.baseURL = baseURL ?? ""; + this.customHeaders = createHeaders({ apiKey, config, virtualKey, traceID, metadata, provider, Authorization, cacheForceRefresh, debug, customHost, cacheNamespace, openaiProject, openaiOrganization, awsSecretAccessKey, awsAccessKeyId, awsSessionToken, awsRegion, vertexProjectId, vertexRegion, workersAiAccountId, azureResourceName, azureDeploymentId, azureApiVersion, huggingfaceBaseUrl, forwardHeaders, requestTimeout, strictOpenAiCompliance, anthropicBeta }) + this.portkeyHeaders = this.defaultHeaders() + this.fetch = fetch; + this.responseHeaders = {} + } protected defaultHeaders(): Record { return { diff --git a/src/client.ts b/src/client.ts index f53780e..326b74a 100644 --- a/src/client.ts +++ b/src/client.ts @@ -7,126 +7,131 @@ import { Stream } from './streaming'; import { castToError, readEnv } from './utils'; export class Portkey extends ApiClient { - declare apiKey: string | null; - declare baseURL: string; - virtualKey: string | null; - config: Record | string | null | undefined; - provider: string | null | undefined; - traceID: string | null | undefined; - metadata: Record | null | undefined; - Authorization?: string; - cacheForceRefresh?: boolean | null | undefined; - debug?: boolean | null | undefined; - customHost?: string | null | undefined; - openaiProject?: string | null | undefined; - openaiOrganization?: string | null | undefined; - awsSecretAccessKey?: string | null | undefined; - awsAccessKeyId?: string | null | undefined; - awsSessionToken?: string | null | undefined; - awsRegion?: string | null | undefined; - vertexProjectId?: string | null | undefined; - vertexRegion?: string | null | undefined; - workersAiAccountId?: string | null | undefined; - azureResourceName?: string | null | undefined; - azureDeploymentId?: string | null | undefined; - azureApiVersion?: string | null | undefined; - huggingfaceBaseUrl?: string | null | undefined; - forwardHeaders?: Array | null | undefined; - requestTimeout?: number | null | undefined; - cacheNamespace?: string | null | undefined; - strictOpenAiCompliance?: boolean | null | undefined; - constructor({ - apiKey = readEnv('PORTKEY_API_KEY') ?? null, - baseURL = readEnv('PORTKEY_BASE_URL') ?? null, - config, - virtualKey, - provider, - traceID, - metadata, - Authorization, - cacheForceRefresh, - debug, - customHost, - openaiProject, - openaiOrganization, - awsSecretAccessKey, - awsAccessKeyId, - awsSessionToken, - awsRegion, - vertexProjectId, - vertexRegion, - workersAiAccountId, - azureResourceName, - azureDeploymentId, - azureApiVersion, - huggingfaceBaseUrl, - forwardHeaders, - cacheNamespace, - requestTimeout, - strictOpenAiCompliance, - }: ApiClientInterface) { - super({ - apiKey, - baseURL, - config, - virtualKey, - provider, - traceID, - metadata, - Authorization, - cacheForceRefresh, - debug, - customHost, - cacheNamespace, - openaiProject, - openaiOrganization, - awsSecretAccessKey, - awsAccessKeyId, - awsSessionToken, - awsRegion, - vertexProjectId, - vertexRegion, - workersAiAccountId, - azureResourceName, - azureDeploymentId, - azureApiVersion, - huggingfaceBaseUrl, - forwardHeaders, - requestTimeout, - strictOpenAiCompliance, - }); + declare apiKey: string | null; + declare baseURL: string; + virtualKey: string | null; + config: Record | string | null | undefined; + provider: string | null | undefined; + traceID: string | null | undefined; + metadata: Record | null | undefined; + Authorization?: string; + cacheForceRefresh?: boolean | null | undefined; + debug?: boolean | null | undefined; + customHost?: string | null | undefined; + openaiProject?: string | null | undefined; + openaiOrganization?: string | null | undefined; + awsSecretAccessKey?: string | null | undefined; + awsAccessKeyId?: string | null | undefined; + awsSessionToken?: string | null | undefined; + awsRegion?: string | null | undefined; + vertexProjectId?: string | null | undefined; + vertexRegion?: string | null | undefined; + workersAiAccountId?: string | null | undefined; + azureResourceName?: string | null | undefined; + azureDeploymentId?: string | null | undefined; + azureApiVersion?: string | null | undefined; + huggingfaceBaseUrl?: string | null | undefined; + forwardHeaders?: Array | null | undefined; + requestTimeout?: number | null | undefined; + cacheNamespace?: string | null | undefined; + strictOpenAiCompliance?: boolean | null | undefined; + anthropicBeta?: string | null | undefined; + constructor({ + apiKey = readEnv("PORTKEY_API_KEY") ?? null, + baseURL = readEnv("PORTKEY_BASE_URL") ?? null, + config, + virtualKey, + provider, + traceID, + metadata, + Authorization, + cacheForceRefresh, + debug, + customHost, + openaiProject, + openaiOrganization, + awsSecretAccessKey, + awsAccessKeyId, + awsSessionToken, + awsRegion, + vertexProjectId, + vertexRegion, + workersAiAccountId, + azureResourceName, + azureDeploymentId, + azureApiVersion, + huggingfaceBaseUrl, + forwardHeaders, + cacheNamespace, + requestTimeout, + strictOpenAiCompliance, + anthropicBeta, + }: ApiClientInterface) { - this.apiKey = apiKey; - if (!this.apiKey) { - throw castToError(MISSING_API_KEY_ERROR_MESSAGE); - } - this.virtualKey = virtualKey || null; - this.config = config || null; - this.baseURL = baseURL || PORTKEY_BASE_URL; - this.provider = provider; - this.traceID = traceID; - this.metadata = metadata; - this.cacheForceRefresh = cacheForceRefresh; - this.debug = debug; - this.customHost = customHost; - this.cacheNamespace = cacheNamespace; - this.openaiProject = openaiProject; - this.openaiOrganization = openaiOrganization; - this.awsSecretAccessKey = awsSecretAccessKey; - this.awsAccessKeyId = awsAccessKeyId; - this.awsSessionToken = awsSessionToken; - this.awsRegion = awsRegion; - this.vertexProjectId = vertexProjectId; - this.vertexRegion = vertexRegion; - this.workersAiAccountId = workersAiAccountId; - this.azureResourceName = azureResourceName; - this.azureDeploymentId = azureDeploymentId; - this.azureApiVersion = azureApiVersion; - this.huggingfaceBaseUrl = huggingfaceBaseUrl; - this.forwardHeaders = forwardHeaders; - this.requestTimeout = requestTimeout; - this.strictOpenAiCompliance = strictOpenAiCompliance; - } + super({ + apiKey, + baseURL, + config, + virtualKey, + provider, + traceID, + metadata, + Authorization, + cacheForceRefresh, + debug, + customHost, + cacheNamespace, + openaiProject, + openaiOrganization, + awsSecretAccessKey, + awsAccessKeyId, + awsSessionToken, + awsRegion, + vertexProjectId, + vertexRegion, + workersAiAccountId, + azureResourceName, + azureDeploymentId, + azureApiVersion, + huggingfaceBaseUrl, + forwardHeaders, + requestTimeout, + strictOpenAiCompliance, + anthropicBeta, + }); + + this.apiKey = apiKey; + if (!this.apiKey) { + throw castToError(MISSING_API_KEY_ERROR_MESSAGE) + } + this.virtualKey = virtualKey || null + this.config = config || null + this.baseURL = baseURL || PORTKEY_BASE_URL; + this.provider = provider + this.traceID = traceID + this.metadata = metadata + this.cacheForceRefresh = cacheForceRefresh; + this.debug = debug; + this.customHost = customHost; + this.cacheNamespace = cacheNamespace;; + this.openaiProject = openaiProject; + this.openaiOrganization = openaiOrganization; + this.awsSecretAccessKey = awsSecretAccessKey; + this.awsAccessKeyId = awsAccessKeyId; + this.awsSessionToken = awsSessionToken; + this.awsRegion = awsRegion; + this.vertexProjectId = vertexProjectId; + this.vertexRegion = vertexRegion; + this.workersAiAccountId = workersAiAccountId; + this.azureResourceName = azureResourceName; + this.azureDeploymentId = azureDeploymentId; + this.azureApiVersion = azureApiVersion; + this.huggingfaceBaseUrl = huggingfaceBaseUrl; + this.forwardHeaders = forwardHeaders; + this.requestTimeout = requestTimeout; + this.strictOpenAiCompliance = strictOpenAiCompliance; + this.anthropicBeta = anthropicBeta; + } completions: API.Completions = new API.Completions(this); chat = new API.Chat(this); diff --git a/src/version.ts b/src/version.ts index 91feea3..fabcbfb 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1 +1 @@ -export const VERSION = '1.4.0-rc.1'; +export const VERSION = "1.4.0"; \ No newline at end of file From d84d88b12085f3fda8ab637daaec23d625bb32ad Mon Sep 17 00:00:00 2001 From: csgulati09 Date: Wed, 25 Sep 2024 17:37:45 +0530 Subject: [PATCH 4/5] fix: formatting fixed --- src/_types/generalTypes.ts | 58 ++++----- src/apis/betaChat.ts | 9 +- src/apis/moderations.ts | 14 +-- src/apis/uploads.ts | 14 +-- src/baseClient.ts | 77 ++++++++++-- src/client.ts | 247 ++++++++++++++++++------------------- src/version.ts | 2 +- 7 files changed, 238 insertions(+), 183 deletions(-) diff --git a/src/_types/generalTypes.ts b/src/_types/generalTypes.ts index e63df04..74dd8ee 100644 --- a/src/_types/generalTypes.ts +++ b/src/_types/generalTypes.ts @@ -1,35 +1,35 @@ export type Headers = Record; export interface ApiClientInterface { - apiKey?: string | null; - baseURL?: string | null; - virtualKey?: string | null | undefined; - config?: Record | string | null | undefined; - provider?: string | null | undefined; - traceID?: string | null | undefined; - metadata?: Record | null | undefined; - Authorization?: string | null | undefined; - cacheForceRefresh?: boolean | null | undefined; - debug?: boolean | null | undefined; - customHost?: string | null | undefined; - openaiProject?: string | null | undefined; - openaiOrganization?: string | null | undefined; - awsSecretAccessKey?: string | null | undefined; - awsAccessKeyId?: string | null | undefined; - awsSessionToken?: string | null | undefined; - awsRegion?: string | null | undefined; - vertexProjectId?: string | null | undefined; - vertexRegion?: string | null | undefined; - workersAiAccountId?: string | null | undefined; - azureResourceName?: string | null | undefined; - azureDeploymentId?: string | null | undefined; - azureApiVersion?: string | null | undefined; - huggingfaceBaseUrl?: string | null | undefined; - forwardHeaders?: Array | null | undefined; - cacheNamespace?: string | null | undefined; - requestTimeout?: number | null | undefined; - strictOpenAiCompliance?: boolean | null | undefined; - anthropicBeta?: string | null | undefined; + apiKey?: string | null; + baseURL?: string | null; + virtualKey?: string | null | undefined; + config?: Record | string | null | undefined; + provider?: string | null | undefined; + traceID?: string | null | undefined; + metadata?: Record | null | undefined; + Authorization?: string | null | undefined; + cacheForceRefresh?: boolean | null | undefined; + debug?: boolean | null | undefined; + customHost?: string | null | undefined; + openaiProject?: string | null | undefined; + openaiOrganization?: string | null | undefined; + awsSecretAccessKey?: string | null | undefined; + awsAccessKeyId?: string | null | undefined; + awsSessionToken?: string | null | undefined; + awsRegion?: string | null | undefined; + vertexProjectId?: string | null | undefined; + vertexRegion?: string | null | undefined; + workersAiAccountId?: string | null | undefined; + azureResourceName?: string | null | undefined; + azureDeploymentId?: string | null | undefined; + azureApiVersion?: string | null | undefined; + huggingfaceBaseUrl?: string | null | undefined; + forwardHeaders?: Array | null | undefined; + cacheNamespace?: string | null | undefined; + requestTimeout?: number | null | undefined; + strictOpenAiCompliance?: boolean | null | undefined; + anthropicBeta?: string | null | undefined; } export interface APIResponseType { diff --git a/src/apis/betaChat.ts b/src/apis/betaChat.ts index a0160a0..ac58edf 100644 --- a/src/apis/betaChat.ts +++ b/src/apis/betaChat.ts @@ -11,9 +11,8 @@ import { import { ChatCompletionStreamingFunctionRunnerParams, ChatCompletionStreamingToolRunnerParams, -} from "openai/lib/ChatCompletionStreamingRunner"; -import { ChatCompletionParseParams } from "openai/resources/beta/chat/completions"; - +} from 'openai/lib/ChatCompletionStreamingRunner'; +import { ChatCompletionParseParams } from 'openai/resources/beta/chat/completions'; export class BetaChat extends ApiResource { completions: Completions; @@ -25,9 +24,7 @@ export class BetaChat extends ApiResource { } export class Completions extends ApiResource { - - async parse - ( + async parse( _body: Params, params?: ApiClientInterface, opts?: RequestOptions diff --git a/src/apis/moderations.ts b/src/apis/moderations.ts index 1e4b255..b6657e5 100644 --- a/src/apis/moderations.ts +++ b/src/apis/moderations.ts @@ -1,12 +1,12 @@ -import { ApiClientInterface } from "../_types/generalTypes"; -import { ApiResource } from "../apiResource"; -import { RequestOptions } from "../baseClient"; -import { finalResponse, initOpenAIClient, overrideConfig } from "../utils"; -import { createHeaders } from "./createHeaders"; +import { ApiClientInterface } from '../_types/generalTypes'; +import { ApiResource } from '../apiResource'; +import { RequestOptions } from '../baseClient'; +import { finalResponse, initOpenAIClient, overrideConfig } from '../utils'; +import { createHeaders } from './createHeaders'; export interface ModerationCreateParams { - input: string | Array; - model?: any ; + input: string | Array; + model?: any; } export class Moderations extends ApiResource { diff --git a/src/apis/uploads.ts b/src/apis/uploads.ts index e3fcd3a..8785345 100644 --- a/src/apis/uploads.ts +++ b/src/apis/uploads.ts @@ -1,13 +1,13 @@ -import { ApiClientInterface } from "../_types/generalTypes"; -import { ApiResource } from "../apiResource"; -import { RequestOptions } from "../baseClient"; -import { finalResponse, initOpenAIClient, overrideConfig } from "../utils"; -import { createHeaders } from "./createHeaders"; -import { Uploadable } from "openai/uploads"; +import { ApiClientInterface } from '../_types/generalTypes'; +import { ApiResource } from '../apiResource'; +import { RequestOptions } from '../baseClient'; +import { finalResponse, initOpenAIClient, overrideConfig } from '../utils'; +import { createHeaders } from './createHeaders'; +import { Uploadable } from 'openai/uploads'; export interface UploadCompleteParams { part_ids: Array; - md5?: string; + md5?: string; } export class Uploads extends ApiResource { parts: Parts; diff --git a/src/baseClient.ts b/src/baseClient.ts index 1b5ed29..b78a666 100644 --- a/src/baseClient.ts +++ b/src/baseClient.ts @@ -136,15 +136,74 @@ export abstract class ApiClient { responseHeaders: Record; portkeyHeaders: Record; - private fetch: Fetch; - constructor({ apiKey, baseURL, config, virtualKey, traceID, metadata, provider, Authorization, cacheForceRefresh, debug, customHost, openaiProject, openaiOrganization, awsSecretAccessKey, awsAccessKeyId, awsSessionToken, awsRegion, vertexProjectId, vertexRegion, workersAiAccountId, azureResourceName, azureDeploymentId, azureApiVersion, huggingfaceBaseUrl, forwardHeaders, cacheNamespace, requestTimeout, strictOpenAiCompliance, anthropicBeta }: ApiClientInterface) { - this.apiKey = apiKey ?? ""; - this.baseURL = baseURL ?? ""; - this.customHeaders = createHeaders({ apiKey, config, virtualKey, traceID, metadata, provider, Authorization, cacheForceRefresh, debug, customHost, cacheNamespace, openaiProject, openaiOrganization, awsSecretAccessKey, awsAccessKeyId, awsSessionToken, awsRegion, vertexProjectId, vertexRegion, workersAiAccountId, azureResourceName, azureDeploymentId, azureApiVersion, huggingfaceBaseUrl, forwardHeaders, requestTimeout, strictOpenAiCompliance, anthropicBeta }) - this.portkeyHeaders = this.defaultHeaders() - this.fetch = fetch; - this.responseHeaders = {} - } + private fetch: Fetch; + constructor({ + apiKey, + baseURL, + config, + virtualKey, + traceID, + metadata, + provider, + Authorization, + cacheForceRefresh, + debug, + customHost, + openaiProject, + openaiOrganization, + awsSecretAccessKey, + awsAccessKeyId, + awsSessionToken, + awsRegion, + vertexProjectId, + vertexRegion, + workersAiAccountId, + azureResourceName, + azureDeploymentId, + azureApiVersion, + huggingfaceBaseUrl, + forwardHeaders, + cacheNamespace, + requestTimeout, + strictOpenAiCompliance, + anthropicBeta, + }: ApiClientInterface) { + this.apiKey = apiKey ?? ''; + this.baseURL = baseURL ?? ''; + this.customHeaders = createHeaders({ + apiKey, + config, + virtualKey, + traceID, + metadata, + provider, + Authorization, + cacheForceRefresh, + debug, + customHost, + cacheNamespace, + openaiProject, + openaiOrganization, + awsSecretAccessKey, + awsAccessKeyId, + awsSessionToken, + awsRegion, + vertexProjectId, + vertexRegion, + workersAiAccountId, + azureResourceName, + azureDeploymentId, + azureApiVersion, + huggingfaceBaseUrl, + forwardHeaders, + requestTimeout, + strictOpenAiCompliance, + anthropicBeta, + }); + this.portkeyHeaders = this.defaultHeaders(); + this.fetch = fetch; + this.responseHeaders = {}; + } protected defaultHeaders(): Record { return { diff --git a/src/client.ts b/src/client.ts index 326b74a..e8a9cab 100644 --- a/src/client.ts +++ b/src/client.ts @@ -7,131 +7,130 @@ import { Stream } from './streaming'; import { castToError, readEnv } from './utils'; export class Portkey extends ApiClient { - declare apiKey: string | null; - declare baseURL: string; - virtualKey: string | null; - config: Record | string | null | undefined; - provider: string | null | undefined; - traceID: string | null | undefined; - metadata: Record | null | undefined; - Authorization?: string; - cacheForceRefresh?: boolean | null | undefined; - debug?: boolean | null | undefined; - customHost?: string | null | undefined; - openaiProject?: string | null | undefined; - openaiOrganization?: string | null | undefined; - awsSecretAccessKey?: string | null | undefined; - awsAccessKeyId?: string | null | undefined; - awsSessionToken?: string | null | undefined; - awsRegion?: string | null | undefined; - vertexProjectId?: string | null | undefined; - vertexRegion?: string | null | undefined; - workersAiAccountId?: string | null | undefined; - azureResourceName?: string | null | undefined; - azureDeploymentId?: string | null | undefined; - azureApiVersion?: string | null | undefined; - huggingfaceBaseUrl?: string | null | undefined; - forwardHeaders?: Array | null | undefined; - requestTimeout?: number | null | undefined; - cacheNamespace?: string | null | undefined; - strictOpenAiCompliance?: boolean | null | undefined; - anthropicBeta?: string | null | undefined; - constructor({ - apiKey = readEnv("PORTKEY_API_KEY") ?? null, - baseURL = readEnv("PORTKEY_BASE_URL") ?? null, - config, - virtualKey, - provider, - traceID, - metadata, - Authorization, - cacheForceRefresh, - debug, - customHost, - openaiProject, - openaiOrganization, - awsSecretAccessKey, - awsAccessKeyId, - awsSessionToken, - awsRegion, - vertexProjectId, - vertexRegion, - workersAiAccountId, - azureResourceName, - azureDeploymentId, - azureApiVersion, - huggingfaceBaseUrl, - forwardHeaders, - cacheNamespace, - requestTimeout, - strictOpenAiCompliance, - anthropicBeta, - }: ApiClientInterface) { + declare apiKey: string | null; + declare baseURL: string; + virtualKey: string | null; + config: Record | string | null | undefined; + provider: string | null | undefined; + traceID: string | null | undefined; + metadata: Record | null | undefined; + Authorization?: string; + cacheForceRefresh?: boolean | null | undefined; + debug?: boolean | null | undefined; + customHost?: string | null | undefined; + openaiProject?: string | null | undefined; + openaiOrganization?: string | null | undefined; + awsSecretAccessKey?: string | null | undefined; + awsAccessKeyId?: string | null | undefined; + awsSessionToken?: string | null | undefined; + awsRegion?: string | null | undefined; + vertexProjectId?: string | null | undefined; + vertexRegion?: string | null | undefined; + workersAiAccountId?: string | null | undefined; + azureResourceName?: string | null | undefined; + azureDeploymentId?: string | null | undefined; + azureApiVersion?: string | null | undefined; + huggingfaceBaseUrl?: string | null | undefined; + forwardHeaders?: Array | null | undefined; + requestTimeout?: number | null | undefined; + cacheNamespace?: string | null | undefined; + strictOpenAiCompliance?: boolean | null | undefined; + anthropicBeta?: string | null | undefined; + constructor({ + apiKey = readEnv('PORTKEY_API_KEY') ?? null, + baseURL = readEnv('PORTKEY_BASE_URL') ?? null, + config, + virtualKey, + provider, + traceID, + metadata, + Authorization, + cacheForceRefresh, + debug, + customHost, + openaiProject, + openaiOrganization, + awsSecretAccessKey, + awsAccessKeyId, + awsSessionToken, + awsRegion, + vertexProjectId, + vertexRegion, + workersAiAccountId, + azureResourceName, + azureDeploymentId, + azureApiVersion, + huggingfaceBaseUrl, + forwardHeaders, + cacheNamespace, + requestTimeout, + strictOpenAiCompliance, + anthropicBeta, + }: ApiClientInterface) { + super({ + apiKey, + baseURL, + config, + virtualKey, + provider, + traceID, + metadata, + Authorization, + cacheForceRefresh, + debug, + customHost, + cacheNamespace, + openaiProject, + openaiOrganization, + awsSecretAccessKey, + awsAccessKeyId, + awsSessionToken, + awsRegion, + vertexProjectId, + vertexRegion, + workersAiAccountId, + azureResourceName, + azureDeploymentId, + azureApiVersion, + huggingfaceBaseUrl, + forwardHeaders, + requestTimeout, + strictOpenAiCompliance, + anthropicBeta, + }); - super({ - apiKey, - baseURL, - config, - virtualKey, - provider, - traceID, - metadata, - Authorization, - cacheForceRefresh, - debug, - customHost, - cacheNamespace, - openaiProject, - openaiOrganization, - awsSecretAccessKey, - awsAccessKeyId, - awsSessionToken, - awsRegion, - vertexProjectId, - vertexRegion, - workersAiAccountId, - azureResourceName, - azureDeploymentId, - azureApiVersion, - huggingfaceBaseUrl, - forwardHeaders, - requestTimeout, - strictOpenAiCompliance, - anthropicBeta, - }); - - this.apiKey = apiKey; - if (!this.apiKey) { - throw castToError(MISSING_API_KEY_ERROR_MESSAGE) - } - this.virtualKey = virtualKey || null - this.config = config || null - this.baseURL = baseURL || PORTKEY_BASE_URL; - this.provider = provider - this.traceID = traceID - this.metadata = metadata - this.cacheForceRefresh = cacheForceRefresh; - this.debug = debug; - this.customHost = customHost; - this.cacheNamespace = cacheNamespace;; - this.openaiProject = openaiProject; - this.openaiOrganization = openaiOrganization; - this.awsSecretAccessKey = awsSecretAccessKey; - this.awsAccessKeyId = awsAccessKeyId; - this.awsSessionToken = awsSessionToken; - this.awsRegion = awsRegion; - this.vertexProjectId = vertexProjectId; - this.vertexRegion = vertexRegion; - this.workersAiAccountId = workersAiAccountId; - this.azureResourceName = azureResourceName; - this.azureDeploymentId = azureDeploymentId; - this.azureApiVersion = azureApiVersion; - this.huggingfaceBaseUrl = huggingfaceBaseUrl; - this.forwardHeaders = forwardHeaders; - this.requestTimeout = requestTimeout; - this.strictOpenAiCompliance = strictOpenAiCompliance; - this.anthropicBeta = anthropicBeta; - } + this.apiKey = apiKey; + if (!this.apiKey) { + throw castToError(MISSING_API_KEY_ERROR_MESSAGE); + } + this.virtualKey = virtualKey || null; + this.config = config || null; + this.baseURL = baseURL || PORTKEY_BASE_URL; + this.provider = provider; + this.traceID = traceID; + this.metadata = metadata; + this.cacheForceRefresh = cacheForceRefresh; + this.debug = debug; + this.customHost = customHost; + this.cacheNamespace = cacheNamespace; + this.openaiProject = openaiProject; + this.openaiOrganization = openaiOrganization; + this.awsSecretAccessKey = awsSecretAccessKey; + this.awsAccessKeyId = awsAccessKeyId; + this.awsSessionToken = awsSessionToken; + this.awsRegion = awsRegion; + this.vertexProjectId = vertexProjectId; + this.vertexRegion = vertexRegion; + this.workersAiAccountId = workersAiAccountId; + this.azureResourceName = azureResourceName; + this.azureDeploymentId = azureDeploymentId; + this.azureApiVersion = azureApiVersion; + this.huggingfaceBaseUrl = huggingfaceBaseUrl; + this.forwardHeaders = forwardHeaders; + this.requestTimeout = requestTimeout; + this.strictOpenAiCompliance = strictOpenAiCompliance; + this.anthropicBeta = anthropicBeta; + } completions: API.Completions = new API.Completions(this); chat = new API.Chat(this); diff --git a/src/version.ts b/src/version.ts index fabcbfb..b44ee38 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1 +1 @@ -export const VERSION = "1.4.0"; \ No newline at end of file +export const VERSION = '1.4.0'; From a0d30fdfd36d485baf635c4bcfb58c6827d9d2ea Mon Sep 17 00:00:00 2001 From: csgulati09 Date: Thu, 10 Oct 2024 14:10:53 +0530 Subject: [PATCH 5/5] fix: prettier changes --- src/_types/generalTypes.ts | 6 +- src/_types/portkeyConstructs.ts | 6 +- src/apiResource.ts | 18 +- src/apis/admin.ts | 876 ++++++++++++++++++-------------- src/apis/apiKeys.ts | 255 +++++----- src/apis/assistants.ts | 44 +- src/apis/betaChat.ts | 5 +- src/apis/configs.ts | 238 +++++---- src/apis/embeddings.ts | 8 +- src/apis/files.ts | 12 +- src/apis/images.ts | 32 +- src/apis/index.ts | 46 +- src/apis/moderations.ts | 34 +- src/apis/threads.ts | 32 +- src/apis/uploads.ts | 12 +- src/apis/vectorStores.ts | 22 +- src/apis/virtualKeys.ts | 234 +++++---- src/baseClient.ts | 81 +-- src/client.ts | 72 +-- src/utils.ts | 42 +- src/version.ts | 2 +- 21 files changed, 1137 insertions(+), 940 deletions(-) diff --git a/src/_types/generalTypes.ts b/src/_types/generalTypes.ts index e216fe2..2655290 100644 --- a/src/_types/generalTypes.ts +++ b/src/_types/generalTypes.ts @@ -24,15 +24,15 @@ export interface ApiClientInterface { azureResourceName?: string | null | undefined; azureDeploymentId?: string | null | undefined; azureApiVersion?: string | null | undefined; - azureEndpointName?: string | null | undefined; + azureEndpointName?: string | null | undefined; huggingfaceBaseUrl?: string | null | undefined; forwardHeaders?: Array | null | undefined; cacheNamespace?: string | null | undefined; requestTimeout?: number | null | undefined; strictOpenAiCompliance?: boolean | null | undefined; anthropicBeta?: string | null | undefined; - anthropicVersion?: string | null | undefined; - mistralFimCompletion?: string | null | undefined; + anthropicVersion?: string | null | undefined; + mistralFimCompletion?: string | null | undefined; } export interface APIResponseType { diff --git a/src/_types/portkeyConstructs.ts b/src/_types/portkeyConstructs.ts index 7831aa2..6ced280 100644 --- a/src/_types/portkeyConstructs.ts +++ b/src/_types/portkeyConstructs.ts @@ -4,9 +4,9 @@ export interface RetrySettings { } export interface FunctionInterface { - name: string; - description: string; - parameters: string; + name: string; + description: string; + parameters: string; } export interface ModelParams { diff --git a/src/apiResource.ts b/src/apiResource.ts index a8ca244..9ae2993 100644 --- a/src/apiResource.ts +++ b/src/apiResource.ts @@ -4,14 +4,14 @@ export class ApiResource { protected client: Portkey; protected post: Portkey['_post']; protected put: Portkey['_put']; - protected getMethod: Portkey["_get"] - protected deleteMethod: Portkey["_delete"] + protected getMethod: Portkey['_get']; + protected deleteMethod: Portkey['_delete']; - constructor(client: Portkey) { - this.client = client - this.post = client._post.bind(client) - this.put = client._put.bind(client) - this.getMethod = client._get.bind(client) - this.deleteMethod = client._delete.bind(client) // delete is a reserved word - } + constructor(client: Portkey) { + this.client = client; + this.post = client._post.bind(client); + this.put = client._put.bind(client); + this.getMethod = client._get.bind(client); + this.deleteMethod = client._delete.bind(client); // delete is a reserved word + } } diff --git a/src/apis/admin.ts b/src/apis/admin.ts index 0f912a6..1b05aa7 100644 --- a/src/apis/admin.ts +++ b/src/apis/admin.ts @@ -1,494 +1,588 @@ -import { ApiResource } from "../apiResource"; -import { APIResponseType, ApiClientInterface } from "../_types/generalTypes"; -import { APIPromise, RequestOptions } from "../baseClient"; -import { createHeaders } from "./createHeaders"; -import { toQueryParams } from "../utils"; +import { ApiResource } from '../apiResource'; +import { APIResponseType, ApiClientInterface } from '../_types/generalTypes'; +import { APIPromise, RequestOptions } from '../baseClient'; +import { createHeaders } from './createHeaders'; +import { toQueryParams } from '../utils'; -export interface UsersGetParams{ - userId?: string; +export interface UsersGetParams { + userId?: string; } export interface UsersGetResponse extends APIResponseType { - object?: string, - id?: string, - first_name?: string, - last_name?: string, - role?: string, - email?: string, - created_at?: Date, - last_updated_at?: Date - workspace_ids?: string[] + object?: string; + id?: string; + first_name?: string; + last_name?: string; + role?: string; + email?: string; + created_at?: Date; + last_updated_at?: Date; + workspace_ids?: string[]; } -export interface UsersListParams{ - pageSize?: number|string; - currentPage?: number; - email?: string; - role?: "admin" | "member" | "owner" | any; +export interface UsersListParams { + pageSize?: number | string; + currentPage?: number; + email?: string; + role?: 'admin' | 'member' | 'owner' | any; } export interface UsersListResponse extends APIResponseType { - total?: number, - object?: string, - data?: UsersGetResponse[] + total?: number; + object?: string; + data?: UsersGetResponse[]; } -export interface UsersUpdateParams{ - userId?: string, - role?: "admin" | "member" | any, +export interface UsersUpdateParams { + userId?: string; + role?: 'admin' | 'member' | any; } -export interface UsersDeleteParams{ - userId?: string; +export interface UsersDeleteParams { + userId?: string; } -export interface UserInviteParams{ - email?: string, - role?: string, - workspaces?: Record[] - workspace_api_key_details?: Record +export interface UserInviteParams { + email?: string; + role?: string; + workspaces?: Record[]; + workspace_api_key_details?: Record; } export interface UserInviteResponse extends APIResponseType { - id?: string, - invite_link?: string, + id?: string; + invite_link?: string; } -export interface UserInviteGetParams{ - inviteId?: string, +export interface UserInviteGetParams { + inviteId?: string; } export interface UserInviteGetResponse extends APIResponseType { - object?: string, - id?: string, - email?: string, - role?: "admin"| "member" | any, - created_at?: Date, - expires_at?: Date, - accepted_at?: Date|null, - status?: string - invited_by?: string + object?: string; + id?: string; + email?: string; + role?: 'admin' | 'member' | any; + created_at?: Date; + expires_at?: Date; + accepted_at?: Date | null; + status?: string; + invited_by?: string; } -export interface UserInviteListParams{ - email?: string, - role?: "admin" | "member" | any, - status?: "pending" | "accepted" | "expired"| "cancelled"| any, - pageSize?: number, - currentPage?: number +export interface UserInviteListParams { + email?: string; + role?: 'admin' | 'member' | any; + status?: 'pending' | 'accepted' | 'expired' | 'cancelled' | any; + pageSize?: number; + currentPage?: number; } export interface UserInviteListResponse extends APIResponseType { - object?: string, - total?: number, - data?: UserInviteGetResponse[] + object?: string; + total?: number; + data?: UserInviteGetResponse[]; } export interface UserInviteDeleteParams { - inviteId?: string, + inviteId?: string; } -export interface WorkspacesAddParams{ - name?: string, - description?: string, - defaults?: Record, - users?: string[], +export interface WorkspacesAddParams { + name?: string; + description?: string; + defaults?: Record; + users?: string[]; } export interface WorkspacesAddResponse extends APIResponseType { - id?: string, - slug?: string, - name?: string, - description?: string, - created_at?: Date, - last_updated_at?: Date, - defaults?: Record, - users?: Record[], - object?: string, + id?: string; + slug?: string; + name?: string; + description?: string; + created_at?: Date; + last_updated_at?: Date; + defaults?: Record; + users?: Record[]; + object?: string; } export interface WorkspacesGetParams { - workspaceId?: string; + workspaceId?: string; } export interface WorkspacesGetResponse extends APIResponseType { - id?: string, - slug?: string, - name?: string, - description?: string, - created_at?: Date, - last_updated_at?: Date, - defaults?: Record | null, - users?: Record[], + id?: string; + slug?: string; + name?: string; + description?: string; + created_at?: Date; + last_updated_at?: Date; + defaults?: Record | null; + users?: Record[]; } export interface WorkspacesListParams { - page_size?: number; - current_page?: number; + page_size?: number; + current_page?: number; } export interface WorkspacesListResponse extends APIResponseType { - total?: number, - object?: string, - data?: WorkspacesGetResponse[] + total?: number; + object?: string; + data?: WorkspacesGetResponse[]; } -export interface WorkspacesUpdateParams{ - workspaceId?: string, - name?: string, - description?: string, - defaults?: Record, +export interface WorkspacesUpdateParams { + workspaceId?: string; + name?: string; + description?: string; + defaults?: Record; } export interface WorkspacesUpdateResponse extends APIResponseType { - id?: string, - slug?: string, - name?: string, - description?: string, - created_at?: Date, - is_default?:number, - last_updated_at?: Date, - defaults?: Record, - object?: string, + id?: string; + slug?: string; + name?: string; + description?: string; + created_at?: Date; + is_default?: number; + last_updated_at?: Date; + defaults?: Record; + object?: string; } -export interface WorkspacesDeleteParams{ - workspaceId?: string; - name?: string; +export interface WorkspacesDeleteParams { + workspaceId?: string; + name?: string; } -export interface WorkspaceMemberAddParams{ - workspaceId?: string, - users?: { id: string, role: "member" | "admin" }[], +export interface WorkspaceMemberAddParams { + workspaceId?: string; + users?: { id: string; role: 'member' | 'admin' }[]; } -export interface WorkspaceMemberGetParams{ - workspaceId?: string, - userId?: string, +export interface WorkspaceMemberGetParams { + workspaceId?: string; + userId?: string; } export interface WorkspaceMemberGetResponse extends APIResponseType { - first_name?: string, - last_name?: string, - org_role?: string, - role?: string, - created_at?: Date, - last_updated_at?: Date, - status?: string - workspace_id?: string, - scopes?: string[], - settings?: Record| null, - object?: string, + first_name?: string; + last_name?: string; + org_role?: string; + role?: string; + created_at?: Date; + last_updated_at?: Date; + status?: string; + workspace_id?: string; + scopes?: string[]; + settings?: Record | null; + object?: string; } export interface WorkspaceMemberListParams { - workspaceId?: string, - page_size?: number, - current_page?: number, - email?: string, - role?: "admin" | "manager" | "member" | any, + workspaceId?: string; + page_size?: number; + current_page?: number; + email?: string; + role?: 'admin' | 'manager' | 'member' | any; } export interface WorkspaceMemberListResponse extends APIResponseType { - total?: number, - object?: string, - data?: WorkspaceMemberGetResponse[] + total?: number; + object?: string; + data?: WorkspaceMemberGetResponse[]; } -export interface WorkspaceMemberDeleteParams{ - workspaceId?: string, - userId?: string, +export interface WorkspaceMemberDeleteParams { + workspaceId?: string; + userId?: string; } -export interface WorkspaceMemberUpdateParams{ - workspaceId?: string, - userId?: string, - role?: "admin" | "member" | any, +export interface WorkspaceMemberUpdateParams { + workspaceId?: string; + userId?: string; + role?: 'admin' | 'member' | any; } // Function to convert UsersGetParams to query parameters - export class Admin extends ApiResource { - users: Users - workspaces: Workspaces - constructor(client: any) { - super(client); - this.users = new Users(client); - this.workspaces= new Workspaces(client); - } + users: Users; + workspaces: Workspaces; + constructor(client: any) { + super(client); + this.users = new Users(client); + this.workspaces = new Workspaces(client); + } } - export class Users extends ApiResource { - - invites: Invites= new Invites(this.client); - - retrieve( - _body: UsersGetParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise { - const body = _body; - const userId = body.userId; - - if (params) { - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params }) } - } - const response = this.getMethod(`/admin/users/${userId}`, {...opts }); - return response; + invites: Invites = new Invites(this.client); + + retrieve( + _body: UsersGetParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise { + const body = _body; + const userId = body.userId; + + if (params) { + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params }), + }; } - - list( - _body: UsersListParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise { - const body = _body; - if (params) { - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params }) } - } - const query = toQueryParams(body); - const response = this.getMethod(`/admin/users${query}`, { ...opts }); - return response; + const response = this.getMethod( + `/admin/users/${userId}`, + { ...opts } + ); + return response; + } + + list( + _body: UsersListParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise { + const body = _body; + if (params) { + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params }), + }; } - - update( - _body: UsersUpdateParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise { - const body = _body; - const userId = body.userId; - delete body.userId; - if (params) { - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params }) } - } - const response = this.put(`/admin/users/${userId}`, { body, ...opts }); - return response; + const query = toQueryParams(body); + const response = this.getMethod(`/admin/users${query}`, { + ...opts, + }); + return response; + } + + update( + _body: UsersUpdateParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise { + const body = _body; + const userId = body.userId; + delete body.userId; + if (params) { + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params }), + }; } - - delete( - _body: UsersDeleteParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise { - const body = _body; - const userId = body.userId; - if (params){ - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params }) } - } - const response = this.deleteMethod(`/admin/users/${userId}`, { body, ...opts }); - return response; + const response = this.put(`/admin/users/${userId}`, { body, ...opts }); + return response; + } + + delete( + _body: UsersDeleteParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise { + const body = _body; + const userId = body.userId; + if (params) { + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params }), + }; } - + const response = this.deleteMethod(`/admin/users/${userId}`, { + body, + ...opts, + }); + return response; + } } - export class Invites extends ApiResource { - - - create( - _body: UserInviteParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise { - const body = _body; - if (params) { - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params }) } - } - const response = this.post('/admin/users/invites', { body, ...opts }); - return response; + create( + _body: UserInviteParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise { + const body = _body; + if (params) { + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params }), + }; } - - retrieve( - _body: UserInviteGetParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise { - const body=_body; - const inviteId = body.inviteId; - if (params) { - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params }) } - } - const response = this.getMethod(`/admin/users/invites/${inviteId}`, { ...opts }); - return response; + const response = this.post('/admin/users/invites', { + body, + ...opts, + }); + return response; + } + + retrieve( + _body: UserInviteGetParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise { + const body = _body; + const inviteId = body.inviteId; + if (params) { + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params }), + }; } - - list( - _body?: UserInviteListParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise { - const body = _body; - if (params) { - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params }) } - } - const query = body ? toQueryParams(body) : ''; - const response = this.getMethod(`/admin/users/invites${query}`, { ...opts }); - return response; + const response = this.getMethod( + `/admin/users/invites/${inviteId}`, + { ...opts } + ); + return response; + } + + list( + _body?: UserInviteListParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise { + const body = _body; + if (params) { + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params }), + }; } - - delete( - _body: UserInviteDeleteParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise { - const body = _body; - const inviteId = body.inviteId; - if (params){ - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params }) } - } - const response = this.deleteMethod(`/admin/users/invites/${inviteId}`, { body, ...opts }); - return response; + const query = body ? toQueryParams(body) : ''; + const response = this.getMethod( + `/admin/users/invites${query}`, + { ...opts } + ); + return response; + } + + delete( + _body: UserInviteDeleteParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise { + const body = _body; + const inviteId = body.inviteId; + if (params) { + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params }), + }; } - + const response = this.deleteMethod( + `/admin/users/invites/${inviteId}`, + { body, ...opts } + ); + return response; + } } export class Workspaces extends ApiResource { - users: Member = new Member(this.client); - - create( - _body: WorkspacesAddParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise { - const body = _body; - if (params) { - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params }) } - } - const response = this.post('/admin/workspaces', { body, ...opts }); - return response; + users: Member = new Member(this.client); + + create( + _body: WorkspacesAddParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise { + const body = _body; + if (params) { + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params }), + }; } - retrieve( - _body: WorkspacesGetParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise { - const body = _body; - const workspaceId = body.workspaceId; - - if (params) { - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params }) } - } - const response = this.getMethod(`/admin/workspaces/${workspaceId}`, { ...opts }); - return response; + const response = this.post('/admin/workspaces', { + body, + ...opts, + }); + return response; + } + retrieve( + _body: WorkspacesGetParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise { + const body = _body; + const workspaceId = body.workspaceId; + + if (params) { + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params }), + }; } - - list( - _body: WorkspacesListParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise { - const body = _body; - if (params) { - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params }) } - } - const query = toQueryParams(body); - const response = this.getMethod(`/admin/workspaces${query}`, { ...opts }); - return response; + const response = this.getMethod( + `/admin/workspaces/${workspaceId}`, + { ...opts } + ); + return response; + } + + list( + _body: WorkspacesListParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise { + const body = _body; + if (params) { + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params }), + }; } - - update( - _body: WorkspacesUpdateParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise { - const body = _body; - const workspaceId = body.workspaceId; - delete body.workspaceId; - if (params) { - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params }) } - } - const response = this.put(`/admin/workspaces/${workspaceId}`, { body, ...opts }); - return response; + const query = toQueryParams(body); + const response = this.getMethod( + `/admin/workspaces${query}`, + { ...opts } + ); + return response; + } + + update( + _body: WorkspacesUpdateParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise { + const body = _body; + const workspaceId = body.workspaceId; + delete body.workspaceId; + if (params) { + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params }), + }; } - - delete( - _body: WorkspacesDeleteParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise { - const body = _body; - const workspaceId = body.workspaceId; - if (params){ - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params }) } - } - const response = this.deleteMethod(`/admin/workspaces/${workspaceId}`, { body, ...opts }); - return response; + const response = this.put( + `/admin/workspaces/${workspaceId}`, + { body, ...opts } + ); + return response; + } + + delete( + _body: WorkspacesDeleteParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise { + const body = _body; + const workspaceId = body.workspaceId; + if (params) { + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params }), + }; } - + const response = this.deleteMethod( + `/admin/workspaces/${workspaceId}`, + { body, ...opts } + ); + return response; + } } export class Member extends ApiResource { - - create( - _body: WorkspaceMemberAddParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise { - const body = _body; - const workspaceId = body.workspaceId; - if (params) { - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params }) } - } - const response = this.post(`/admin/workspaces/${workspaceId}/users`, { body, ...opts }); - return response; + create( + _body: WorkspaceMemberAddParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise { + const body = _body; + const workspaceId = body.workspaceId; + if (params) { + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params }), + }; } - - retrieve( - _body: WorkspaceMemberGetParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise { - const body = _body; - const workspaceId = body.workspaceId; - const userId = body.userId; - if (params) { - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params }) } - } - const response = this.getMethod(`/admin/workspaces/${workspaceId}/users/${userId}`, { ...opts }); - return response; + const response = this.post(`/admin/workspaces/${workspaceId}/users`, { + body, + ...opts, + }); + return response; + } + + retrieve( + _body: WorkspaceMemberGetParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise { + const body = _body; + const workspaceId = body.workspaceId; + const userId = body.userId; + if (params) { + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params }), + }; } - - list( - _body: WorkspaceMemberListParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise { - const body = _body; - const workspaceId = body.workspaceId; - if (params) { - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params }) } - } - const query = toQueryParams(body); - const response = this.getMethod(`/admin/workspaces/${workspaceId}/users${query}`, { ...opts }); - return response; + const response = this.getMethod( + `/admin/workspaces/${workspaceId}/users/${userId}`, + { ...opts } + ); + return response; + } + + list( + _body: WorkspaceMemberListParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise { + const body = _body; + const workspaceId = body.workspaceId; + if (params) { + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params }), + }; } - - delete( - _body: WorkspaceMemberDeleteParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise { - const body = _body; - const workspaceId = body.workspaceId; - const userId = body.userId; - if (params){ - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params }) } - } - const response = this.deleteMethod(`/admin/workspaces/${workspaceId}/users/${userId}`, { body, ...opts }); - return response; + const query = toQueryParams(body); + const response = this.getMethod( + `/admin/workspaces/${workspaceId}/users${query}`, + { ...opts } + ); + return response; + } + + delete( + _body: WorkspaceMemberDeleteParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise { + const body = _body; + const workspaceId = body.workspaceId; + const userId = body.userId; + if (params) { + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params }), + }; } - update( - _body: WorkspaceMemberUpdateParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise { - const body = _body; - const workspaceId = body.workspaceId; - const userId = body.userId; - delete body.workspaceId; - if (params) { - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params }) } - } - const response = this.put(`/admin/workspaces/${workspaceId}/users/${userId}`, { body, ...opts }); - return response; + const response = this.deleteMethod( + `/admin/workspaces/${workspaceId}/users/${userId}`, + { body, ...opts } + ); + return response; + } + update( + _body: WorkspaceMemberUpdateParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise { + const body = _body; + const workspaceId = body.workspaceId; + const userId = body.userId; + delete body.workspaceId; + if (params) { + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params }), + }; } -} \ No newline at end of file + const response = this.put( + `/admin/workspaces/${workspaceId}/users/${userId}`, + { body, ...opts } + ); + return response; + } +} diff --git a/src/apis/apiKeys.ts b/src/apis/apiKeys.ts index 84ba40d..f30196e 100644 --- a/src/apis/apiKeys.ts +++ b/src/apis/apiKeys.ts @@ -1,138 +1,163 @@ -import { ApiResource } from "../apiResource"; -import { APIResponseType, ApiClientInterface } from "../_types/generalTypes"; -import { APIPromise, RequestOptions } from "../baseClient"; -import { createHeaders } from "./createHeaders"; -import { toQueryParams } from "../utils"; +import { ApiResource } from '../apiResource'; +import { APIResponseType, ApiClientInterface } from '../_types/generalTypes'; +import { APIPromise, RequestOptions } from '../baseClient'; +import { createHeaders } from './createHeaders'; +import { toQueryParams } from '../utils'; export interface ApiKeysAddParams { - type?: string; - "sub-type"?: string; - name?: string; - description?: string; - workspace_id?:string; - user_id?:string; - rate_limits?: Record[]; - usage_limits?: Record; - scopes: string[]; - defaults?: Record; + type?: string; + 'sub-type'?: string; + name?: string; + description?: string; + workspace_id?: string; + user_id?: string; + rate_limits?: Record[]; + usage_limits?: Record; + scopes: string[]; + defaults?: Record; } export interface ApiKeysAddResponse extends APIResponseType { - id?: string; - key?: string; - object?: string; + id?: string; + key?: string; + object?: string; } export interface ApiKeysGetParams { - id?: string; + id?: string; } export interface ApiKeysGetResponse extends APIResponseType { - id?: string; - key?: string; - name?: string; - description?: string; - type?: string; - organisation_id?: string; - workspace_id?: string; - user_id?: string; - status?: string; - created_at?: Date; - last_updated_at?: Date; - creation_mode?: string; - rate_limits?: Record[]; - usage_limits?: Record; - reset_usage?:number; - scopes?: string[]; - defaults?: Record; - object?: string; + id?: string; + key?: string; + name?: string; + description?: string; + type?: string; + organisation_id?: string; + workspace_id?: string; + user_id?: string; + status?: string; + created_at?: Date; + last_updated_at?: Date; + creation_mode?: string; + rate_limits?: Record[]; + usage_limits?: Record; + reset_usage?: number; + scopes?: string[]; + defaults?: Record; + object?: string; } export interface ApiKeysUpdateParams { - id?: string; - name?: string; - description?: string; - rate_limits?: Record[]; - usage_limits?: Record; - scopes?: string[]; - defaults?: Record; + id?: string; + name?: string; + description?: string; + rate_limits?: Record[]; + usage_limits?: Record; + scopes?: string[]; + defaults?: Record; } export interface ApiKeysListParams { - page_size?: number; - current_page?: number; - workspace_id?: string; + page_size?: number; + current_page?: number; + workspace_id?: string; } export interface ApiKeysListResponse extends APIResponseType { - total?: number; - object?: string; - data?: Record[]; + total?: number; + object?: string; + data?: Record[]; } export interface ApiKeysDeleteParams { - id?: string; + id?: string; } export class ApiKeys extends ApiResource { - create( - _body: ApiKeysAddParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise { - const body = _body; - const type = body.type; - const subType = body["sub-type"]; - if (params) { - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params }) } - } - const response = this.post(`/api-keys/${type}/${subType}`, { body, ...opts }); - return response; - } + create( + _body: ApiKeysAddParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise { + const body = _body; + const type = body.type; + const subType = body['sub-type']; + if (params) { + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params }), + }; + } + const response = this.post( + `/api-keys/${type}/${subType}`, + { body, ...opts } + ); + return response; + } - retrieve( - _body: ApiKeysGetParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise { - const body = _body; - const id = body.id; - if (params) { - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params }) } - } - const response = this.getMethod(`/api-keys/${id}`, { ...opts }); - return response; - } + retrieve( + _body: ApiKeysGetParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise { + const body = _body; + const id = body.id; + if (params) { + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params }), + }; + } + const response = this.getMethod(`/api-keys/${id}`, { + ...opts, + }); + return response; + } - update( - _body: ApiKeysUpdateParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise { - const body = _body; - const id = body.id; - if (params) { - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params }) } - } - const response = this.put(`/api-keys/${id}`, { body, ...opts }); - return response; - } - list( - _body: ApiKeysListParams, - params?: ApiClientInterface, - opts?: RequestOptions - ):APIPromise{ - const body = _body; - if (params) { - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params }) } - } - const query = toQueryParams(body); - const response = this.getMethod(`/api-keys${query}`, {...opts }); - return response; + update( + _body: ApiKeysUpdateParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise { + const body = _body; + const id = body.id; + if (params) { + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params }), + }; + } + const response = this.put(`/api-keys/${id}`, { body, ...opts }); + return response; + } + list( + _body: ApiKeysListParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise { + const body = _body; + if (params) { + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params }), + }; } - delete( - _body: ApiKeysDeleteParams, - params?: ApiClientInterface, - opts?: RequestOptions - ):APIPromise{ - const body = _body; - const id=body.id; - if (params) { - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params }) } - } - const response = this.deleteMethod(`/api-keys/${id}`, { body, ...opts }); - return response; + const query = toQueryParams(body); + const response = this.getMethod(`/api-keys${query}`, { + ...opts, + }); + return response; + } + delete( + _body: ApiKeysDeleteParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise { + const body = _body; + const id = body.id; + if (params) { + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params }), + }; } + const response = this.deleteMethod(`/api-keys/${id}`, { + body, + ...opts, + }); + return response; + } } diff --git a/src/apis/assistants.ts b/src/apis/assistants.ts index e5f45b6..efe08cd 100644 --- a/src/apis/assistants.ts +++ b/src/apis/assistants.ts @@ -5,17 +5,17 @@ import { finalResponse, initOpenAIClient, overrideConfig } from '../utils'; import { createHeaders } from './createHeaders'; export interface AssistantCreateParams { - model: string; - description?: string | null; - instructions?: string | null; - metadata?: unknown | null; - name?: string | null; - tools?: Array; - response_format?: any | null; - temperature?: number | null; - tool_resources?: any | null; - top_p?: number | null; - [key: string]: any; + model: string; + description?: string | null; + instructions?: string | null; + metadata?: unknown | null; + name?: string | null; + tools?: Array; + response_format?: any | null; + temperature?: number | null; + tool_resources?: any | null; + top_p?: number | null; + [key: string]: any; } export interface FileCreateParams { @@ -28,9 +28,9 @@ export interface FileListParams extends CursorPageParams { } export interface CursorPageParams { - after?: string; - limit?: number; - [key: string]: any; + after?: string; + limit?: number; + [key: string]: any; } export interface AssistantListParams extends CursorPageParams { @@ -39,14 +39,14 @@ export interface AssistantListParams extends CursorPageParams { } export interface AssistantUpdateParams { - description?: string | null; - file_ids?: Array; - instructions?: string | null; - metadata?: unknown | null; - model?: string; - name?: string | null; - tools?: Array; - [key: string]: any; + description?: string | null; + file_ids?: Array; + instructions?: string | null; + metadata?: unknown | null; + model?: string; + name?: string | null; + tools?: Array; + [key: string]: any; } export class Assistants extends ApiResource { diff --git a/src/apis/betaChat.ts b/src/apis/betaChat.ts index b612a08..ac58edf 100644 --- a/src/apis/betaChat.ts +++ b/src/apis/betaChat.ts @@ -11,9 +11,8 @@ import { import { ChatCompletionStreamingFunctionRunnerParams, ChatCompletionStreamingToolRunnerParams, -} from "openai/lib/ChatCompletionStreamingRunner"; -import { ChatCompletionParseParams } from "openai/resources/beta/chat/completions"; - +} from 'openai/lib/ChatCompletionStreamingRunner'; +import { ChatCompletionParseParams } from 'openai/resources/beta/chat/completions'; export class BetaChat extends ApiResource { completions: Completions; diff --git a/src/apis/configs.ts b/src/apis/configs.ts index e0fdf6d..fc56615 100644 --- a/src/apis/configs.ts +++ b/src/apis/configs.ts @@ -1,132 +1,158 @@ -import { ApiResource } from "../apiResource"; -import { APIResponseType, ApiClientInterface } from "../_types/generalTypes"; -import { APIPromise, RequestOptions } from "../baseClient"; -import { createHeaders } from "./createHeaders"; -import { toQueryParams } from "../utils"; +import { ApiResource } from '../apiResource'; +import { APIResponseType, ApiClientInterface } from '../_types/generalTypes'; +import { APIPromise, RequestOptions } from '../baseClient'; +import { createHeaders } from './createHeaders'; +import { toQueryParams } from '../utils'; export interface ConfigsAddParams { - name?: string; - config?: Record; - isDefault?: number; - workspace_id?:string; + name?: string; + config?: Record; + isDefault?: number; + workspace_id?: string; } export interface ConfigsAddResponse extends APIResponseType { - id?: string; - version_id?: string; - slug?: string; - object?: string; + id?: string; + version_id?: string; + slug?: string; + object?: string; } export interface ConfigsGetParams { - slug?: string; + slug?: string; } export interface ConfigsGetResponse extends APIResponseType { - id?: string; - name?: string; - workspace_id?: string; - slug?: string; - organization_id?: string; - is_default?: number; - status?: string; - owner_id?: string; - created_at?: string; - updated_by?: string; - last_updated_at?: string; - config?: Record; - format?: string; - type?: string; - version_id?: string; - object?: string; + id?: string; + name?: string; + workspace_id?: string; + slug?: string; + organization_id?: string; + is_default?: number; + status?: string; + owner_id?: string; + created_at?: string; + updated_by?: string; + last_updated_at?: string; + config?: Record; + format?: string; + type?: string; + version_id?: string; + object?: string; } export interface CongfigsListParams { - workspace_id?: string; + workspace_id?: string; } export interface ConfigsListResponse extends APIResponseType { - object?: boolean; - total?: number; - data?: Record[]; + object?: boolean; + total?: number; + data?: Record[]; } export interface ConfigsUpdateParams { - slug?: string; - name?: string; - config?: Record; - status?: string; + slug?: string; + name?: string; + config?: Record; + status?: string; } export interface ConfigsUpdateResponse extends APIResponseType { - version_id?: string; - object?: string; + version_id?: string; + object?: string; } export interface ConfigsDeleteParams { - id?: string; + id?: string; } export class Configs extends ApiResource { - constructor(client: any) { - super(client); + constructor(client: any) { + super(client); + } + create( + _body: ConfigsAddParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise { + const body = _body; + if (params) { + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params }), + }; } - create( - _body: ConfigsAddParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise { - const body = _body; - if (params) { - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params }) } - } - const response = this.post('/configs', { body, ...opts }); - return response; - } + const response = this.post('/configs', { + body, + ...opts, + }); + return response; + } - retrieve( - _body: ConfigsGetParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise { - const body = _body; - const slug = body.slug; - if (params) { - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params }) } - } - const response = this.getMethod(`/configs/${slug}`, { ...opts }); - return response; - } + retrieve( + _body: ConfigsGetParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise { + const body = _body; + const slug = body.slug; + if (params) { + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params }), + }; + } + const response = this.getMethod(`/configs/${slug}`, { + ...opts, + }); + return response; + } - update( - _body: ConfigsUpdateParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise { - const body = _body; - const slug = body.slug; - if (params) { - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params }) } - } - const response = this.put(`/configs/${slug}`, { body, ...opts }); - return response; - } - list( - _body?:CongfigsListParams, - params?: ApiClientInterface, - opts?: RequestOptions - ):APIPromise{ - const body = _body; - const query = toQueryParams(body); - if (params) { - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params }) } - } - const response = this.getMethod(`/configs${query}`, {...opts}); - return response; + update( + _body: ConfigsUpdateParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise { + const body = _body; + const slug = body.slug; + if (params) { + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params }), + }; + } + const response = this.put(`/configs/${slug}`, { + body, + ...opts, + }); + return response; + } + list( + _body?: CongfigsListParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise { + const body = _body; + const query = toQueryParams(body); + if (params) { + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params }), + }; } - delete( - _body:ConfigsDeleteParams, - params?: ApiClientInterface, - opts?: RequestOptions - ):APIPromise{ - const body = _body; - const configId = body.id; - if (params) { - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params }) } - } - const response = this.deleteMethod(`/configs/${configId}`, {...opts}); - return response; + const response = this.getMethod(`/configs${query}`, { + ...opts, + }); + return response; + } + delete( + _body: ConfigsDeleteParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise { + const body = _body; + const configId = body.id; + if (params) { + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params }), + }; } + const response = this.deleteMethod(`/configs/${configId}`, { + ...opts, + }); + return response; + } } - diff --git a/src/apis/embeddings.ts b/src/apis/embeddings.ts index 68403a6..de7c1b1 100644 --- a/src/apis/embeddings.ts +++ b/src/apis/embeddings.ts @@ -7,10 +7,10 @@ import { overrideConfig } from '../utils'; import { createHeaders } from './createHeaders'; export interface EmbeddingsBody extends ModelParams { - input: string | number | (string | number)[] | (string | number)[][]; - model?: string; - dimensions?: number; - encoding_format?: string; + input: string | number | (string | number)[] | (string | number)[][]; + model?: string; + dimensions?: number; + encoding_format?: string; } export type EmbeddingsResponse = Record & APIResponseType; diff --git a/src/apis/files.ts b/src/apis/files.ts index 3cd1255..c410885 100644 --- a/src/apis/files.ts +++ b/src/apis/files.ts @@ -131,9 +131,9 @@ export class MainFiles extends ApiResource { } export interface FileCreateParams { - file: any; - purpose?: string; - [key: string]: any; + file: any; + purpose?: string; + [key: string]: any; } export interface FileObject { @@ -148,6 +148,6 @@ export interface FileObject { } export interface FileListParams { - purpose?: string; - [key: string]: any; - } \ No newline at end of file + purpose?: string; + [key: string]: any; +} diff --git a/src/apis/images.ts b/src/apis/images.ts index 2f08b5d..8282cc9 100644 --- a/src/apis/images.ts +++ b/src/apis/images.ts @@ -17,25 +17,25 @@ export interface ImagesBody { } export interface ImageEditParams { - image: any; - prompt: string; - mask?: any; - model?: string | null; - n?: number | null; - response_format?: string | null; - size?: string | null; - user?: string; - [key: string]: any; + image: any; + prompt: string; + mask?: any; + model?: string | null; + n?: number | null; + response_format?: string | null; + size?: string | null; + user?: string; + [key: string]: any; } export interface ImageCreateVariationParams { - image: any; - model?: string | null; - n?: number | null; - response_format?: string | null; - size?: string | null; - user?: string; - [key: string]: any; + image: any; + model?: string | null; + n?: number | null; + response_format?: string | null; + size?: string | null; + user?: string; + [key: string]: any; } export interface ImagesResponse { diff --git a/src/apis/index.ts b/src/apis/index.ts index 6deac4b..92b00e0 100644 --- a/src/apis/index.ts +++ b/src/apis/index.ts @@ -1,23 +1,23 @@ -export { Chat } from "./chatCompletions"; -export { Completions } from "./completions"; -export { createHeaders } from "./createHeaders"; -export { Feedback } from "./feedback"; -export { Generations, Prompt } from "./generations"; -export { postMethod } from "./postMethod"; -export { Embeddings } from "./embeddings"; -export { Images } from "./images"; -export { Assistants } from "./assistants"; -export { Threads } from "./threads"; -export { MainFiles } from "./files"; -export { Models } from "./models"; -export { Admin } from "./admin"; -export { Configs } from "./configs"; -export { Batches } from "./batches"; -export { VirtualKeys } from "./virtualKeys"; -export { FineTuning } from "./fineTuning" -export { Moderations } from "./moderations" -export { Audio } from "./audio" -export { VectorStores } from "./vectorStores" -export { BetaChat } from "./betaChat" -export { Uploads } from "./uploads" -export { ApiKeys } from "./apiKeys" +export { Chat } from './chatCompletions'; +export { Completions } from './completions'; +export { createHeaders } from './createHeaders'; +export { Feedback } from './feedback'; +export { Generations, Prompt } from './generations'; +export { postMethod } from './postMethod'; +export { Embeddings } from './embeddings'; +export { Images } from './images'; +export { Assistants } from './assistants'; +export { Threads } from './threads'; +export { MainFiles } from './files'; +export { Models } from './models'; +export { Admin } from './admin'; +export { Configs } from './configs'; +export { Batches } from './batches'; +export { VirtualKeys } from './virtualKeys'; +export { FineTuning } from './fineTuning'; +export { Moderations } from './moderations'; +export { Audio } from './audio'; +export { VectorStores } from './vectorStores'; +export { BetaChat } from './betaChat'; +export { Uploads } from './uploads'; +export { ApiKeys } from './apiKeys'; diff --git a/src/apis/moderations.ts b/src/apis/moderations.ts index 00e2b37..c908745 100644 --- a/src/apis/moderations.ts +++ b/src/apis/moderations.ts @@ -5,25 +5,25 @@ import { finalResponse, initOpenAIClient, overrideConfig } from '../utils'; import { createHeaders } from './createHeaders'; export interface ModerationCreateParams { - input: string | Array; - model?: any ; - [key: string]: any; + input: string | Array; + model?: any; + [key: string]: any; } -export class Moderations extends ApiResource{ - async create( - _body: ModerationCreateParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): Promise { - const body: ModerationCreateParams = _body; - if (params) { - const config = overrideConfig(this.client.config, params.config); - this.client.customHeaders = { - ...this.client.customHeaders, - ...createHeaders({ ...params, config }), - }; - } +export class Moderations extends ApiResource { + async create( + _body: ModerationCreateParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): Promise { + const body: ModerationCreateParams = _body; + if (params) { + const config = overrideConfig(this.client.config, params.config); + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params, config }), + }; + } const OAIclient = initOpenAIClient(this.client); diff --git a/src/apis/threads.ts b/src/apis/threads.ts index 7094e7d..bedc7c5 100644 --- a/src/apis/threads.ts +++ b/src/apis/threads.ts @@ -633,9 +633,9 @@ export class Steps extends ApiResource { } export interface ThreadCreateParams { - messages?: Array; - metadata?: unknown | null; - [key: string]: any; + messages?: Array; + metadata?: unknown | null; + [key: string]: any; } export interface Message { @@ -646,16 +646,16 @@ export interface Message { } export interface ThreadUpdateParams { - metadata?: unknown | null; - [key: string]: any; + metadata?: unknown | null; + [key: string]: any; } export interface MessageCreateParams { - content: string; - role: string; - file_ids?: Array; - metadata?: unknown | null; - [key: string]: any; + content: string; + role: string; + file_ids?: Array; + metadata?: unknown | null; + [key: string]: any; } export interface MessageListParams extends CursorPageParams { @@ -674,8 +674,8 @@ export interface FileListParams extends CursorPageParams { } export interface MessageUpdateParams { - metadata?: unknown | null; - [key: string]: any; + metadata?: unknown | null; + [key: string]: any; } export interface RunCreateParams { @@ -723,13 +723,13 @@ export interface StepListParams extends CursorPageParams { } export interface RunUpdateParams { - metadata?: unknown | null; - [key: string]: any; + metadata?: unknown | null; + [key: string]: any; } export interface RunSubmitToolOutputsParams { - tool_outputs: Array; - [key: string]: any; + tool_outputs: Array; + [key: string]: any; } export interface ToolOutput { diff --git a/src/apis/uploads.ts b/src/apis/uploads.ts index 44468f4..4fd901b 100644 --- a/src/apis/uploads.ts +++ b/src/apis/uploads.ts @@ -1,9 +1,9 @@ -import { ApiClientInterface } from "../_types/generalTypes"; -import { ApiResource } from "../apiResource"; -import { RequestOptions } from "../baseClient"; -import { finalResponse, initOpenAIClient, overrideConfig } from "../utils"; -import { createHeaders } from "./createHeaders"; -import { Uploadable } from "openai/uploads"; +import { ApiClientInterface } from '../_types/generalTypes'; +import { ApiResource } from '../apiResource'; +import { RequestOptions } from '../baseClient'; +import { finalResponse, initOpenAIClient, overrideConfig } from '../utils'; +import { createHeaders } from './createHeaders'; +import { Uploadable } from 'openai/uploads'; export interface UploadCompleteParams { part_ids: Array; diff --git a/src/apis/vectorStores.ts b/src/apis/vectorStores.ts index f6be176..05d0485 100644 --- a/src/apis/vectorStores.ts +++ b/src/apis/vectorStores.ts @@ -534,21 +534,21 @@ export interface CursorPageParams { } export interface FileCreateParams { - file_id: string; - [key: string]: any; + file_id: string; + [key: string]: any; } export interface FileListParams extends CursorPageParams { - before?: string; - filter?: 'in_progress' | 'completed' | 'failed' | 'cancelled'; - order?: 'asc' | 'desc'; - [key: string]: any; - } + before?: string; + filter?: 'in_progress' | 'completed' | 'failed' | 'cancelled'; + order?: 'asc' | 'desc'; + [key: string]: any; +} - export interface FileBatchCreateParams { - file_ids: Array; - [key: string]: any; - } +export interface FileBatchCreateParams { + file_ids: Array; + [key: string]: any; +} export interface FileBatchListFilesParams extends CursorPageParams { before?: string; diff --git a/src/apis/virtualKeys.ts b/src/apis/virtualKeys.ts index 9af0437..4ad3dd3 100644 --- a/src/apis/virtualKeys.ts +++ b/src/apis/virtualKeys.ts @@ -1,135 +1,163 @@ -import { ApiResource } from "../apiResource"; -import { APIResponseType, ApiClientInterface } from "../_types/generalTypes"; -import { APIPromise, RequestOptions } from "../baseClient"; -import { createHeaders } from "./createHeaders"; -import { toQueryParams } from "../utils"; +import { ApiResource } from '../apiResource'; +import { APIResponseType, ApiClientInterface } from '../_types/generalTypes'; +import { APIPromise, RequestOptions } from '../baseClient'; +import { createHeaders } from './createHeaders'; +import { toQueryParams } from '../utils'; export interface VirtualKeysAddParams { - name?: string; - provider?: string; - key?: string; - note?: string | null; - apiVersion?: string | null; - resourceName?: string | null; - deploymentName?: string | null; - workspace_id?: string; - usage_limits?: Record; - [key: string]: any; + name?: string; + provider?: string; + key?: string; + note?: string | null; + apiVersion?: string | null; + resourceName?: string | null; + deploymentName?: string | null; + workspace_id?: string; + usage_limits?: Record; + [key: string]: any; } export interface VirtualKeysAddResponse extends APIResponseType { - id?: string; - slug?:string; - object?: string; + id?: string; + slug?: string; + object?: string; } export interface VirtualKeysGetParams { - slug?: string; + slug?: string; } export interface VirtualKeysGetResponse extends APIResponseType { - id?: string, - ai_provider_name?: string, - model_config?: Record, - masked_api_key?: string, - slug?: string, - name?: string, - usage_limits?: Record, - status?: string, - note?: null|string, - created_at?: Date, - rate_limits?: Record[], - object?: string, + id?: string; + ai_provider_name?: string; + model_config?: Record; + masked_api_key?: string; + slug?: string; + name?: string; + usage_limits?: Record; + status?: string; + note?: null | string; + created_at?: Date; + rate_limits?: Record[]; + object?: string; } export interface VirtualKeysListParams { - workspace_id?: string; + workspace_id?: string; } export interface VirtualKeysListResponse extends APIResponseType { - object?:string, - total?:number, - data?: VirtualKeysGetResponse[]; + object?: string; + total?: number; + data?: VirtualKeysGetResponse[]; } export interface VirtualKeysUpdateParams { - slug?: string; - name?: string; - key?: string; - note?: string | null; - usage_limits?: Record; - rate_limits?: Record[]; - [key: string]: any; + slug?: string; + name?: string; + key?: string; + note?: string | null; + usage_limits?: Record; + rate_limits?: Record[]; + [key: string]: any; } export interface VirtualKeysUpdateResponse extends APIResponseType { - id?:string; - slug?:string; - object?: string; + id?: string; + slug?: string; + object?: string; } export interface VirtualKeysDeleteParams { - slug?: string; + slug?: string; } - export class VirtualKeys extends ApiResource { - create( - body: VirtualKeysAddParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise { - if (params) { - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params }) } - } - const response = this.post('/virtual-keys', { body, ...opts }); - return response; + create( + body: VirtualKeysAddParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise { + if (params) { + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params }), + }; } + const response = this.post('/virtual-keys', { + body, + ...opts, + }); + return response; + } - list( - _body?: VirtualKeysListParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise { - const body=_body; - if (params) { - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params }) } - } - const query = toQueryParams(body); - const response = this.getMethod(`/virtual-keys${query}`, { ...opts }); - return response; + list( + _body?: VirtualKeysListParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise { + const body = _body; + if (params) { + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params }), + }; } + const query = toQueryParams(body); + const response = this.getMethod( + `/virtual-keys${query}`, + { ...opts } + ); + return response; + } - retrieve( - body: VirtualKeysGetParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise { - const { slug } = body; - if (params) { - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params }) } - } - const response = this.getMethod(`/virtual-keys/${slug}`, { ...opts }); - return response; + retrieve( + body: VirtualKeysGetParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise { + const { slug } = body; + if (params) { + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params }), + }; } + const response = this.getMethod( + `/virtual-keys/${slug}`, + { ...opts } + ); + return response; + } - update( - body: VirtualKeysUpdateParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise { - const { slug, ...restBody } = body; - if (params) { - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params }) } - } - const response = this.put(`/virtual-keys/${slug}`, { body: restBody, ...opts }); - return response; + update( + body: VirtualKeysUpdateParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise { + const { slug, ...restBody } = body; + if (params) { + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params }), + }; } + const response = this.put( + `/virtual-keys/${slug}`, + { body: restBody, ...opts } + ); + return response; + } - delete( - body: VirtualKeysDeleteParams, - params?: ApiClientInterface, - opts?: RequestOptions - ): APIPromise { - const { slug } = body; - if (params) { - this.client.customHeaders = { ...this.client.customHeaders, ...createHeaders({ ...params }) } - } - const response = this.deleteMethod(`/virtual-keys/${slug}`, { ...opts }); - return response; + delete( + body: VirtualKeysDeleteParams, + params?: ApiClientInterface, + opts?: RequestOptions + ): APIPromise { + const { slug } = body; + if (params) { + this.client.customHeaders = { + ...this.client.customHeaders, + ...createHeaders({ ...params }), + }; } -} \ No newline at end of file + const response = this.deleteMethod(`/virtual-keys/${slug}`, { + ...opts, + }); + return response; + } +} diff --git a/src/baseClient.ts b/src/baseClient.ts index 9b3b384..2ad0aa7 100644 --- a/src/baseClient.ts +++ b/src/baseClient.ts @@ -161,15 +161,16 @@ export abstract class ApiClient { azureResourceName, azureDeploymentId, azureApiVersion, - azureEndpointName, + azureEndpointName, huggingfaceBaseUrl, forwardHeaders, cacheNamespace, requestTimeout, strictOpenAiCompliance, - anthropicBeta, - anthropicVersion, - mistralFimCompletion }: ApiClientInterface) { + anthropicBeta, + anthropicVersion, + mistralFimCompletion, + }: ApiClientInterface) { this.apiKey = apiKey ?? ''; this.baseURL = baseURL ?? ''; this.customHeaders = createHeaders({ @@ -196,10 +197,13 @@ export abstract class ApiClient { azureResourceName, azureDeploymentId, azureApiVersion, - azureEndpointName, huggingfaceBaseUrl, + azureEndpointName, + huggingfaceBaseUrl, forwardHeaders, requestTimeout, - strictOpenAiCompliance, anthropicVersion, mistralFimCompletion, + strictOpenAiCompliance, + anthropicVersion, + mistralFimCompletion, anthropicBeta, }); this.portkeyHeaders = this.defaultHeaders(); @@ -229,13 +233,19 @@ export abstract class ApiClient { return this.methodRequest('put', path, opts); } - _get(path:string, opts?: RequestOptions): APIPromise { - return this.methodRequest("get", path, opts); - } + _get( + path: string, + opts?: RequestOptions + ): APIPromise { + return this.methodRequest('get', path, opts); + } - _delete(path: string, opts?: RequestOptions): APIPromise { - return this.methodRequest("delete", path, opts); - } + _delete( + path: string, + opts?: RequestOptions + ): APIPromise { + return this.methodRequest('delete', path, opts); + } protected generateError( status: number | undefined, @@ -274,30 +284,31 @@ export abstract class ApiClient { return { response, options: opts, responseHeaders: response.headers }; } - buildRequest(opts: FinalRequestOptions): { req: RequestInit, url: string } { - const url = new URL(this.baseURL + opts.path!) - const { method, body } = opts; - const reqHeaders: Record = { - ...this.defaultHeaders(), ...this.customHeaders, - }; - const httpAgent: Agent | undefined = defaultHttpAgent - let req: RequestInit; - if (method === "get"){ - req = { - method, - headers: reqHeaders, - ...(httpAgent && { agent: httpAgent }) - } - } else { - req = { - method, - body: JSON.stringify(parseBody(body)), - headers: reqHeaders, - ...(httpAgent && { agent: httpAgent }) - } - } - return { req: req, url: url.toString() } + buildRequest(opts: FinalRequestOptions): { req: RequestInit; url: string } { + const url = new URL(this.baseURL + opts.path!); + const { method, body } = opts; + const reqHeaders: Record = { + ...this.defaultHeaders(), + ...this.customHeaders, + }; + const httpAgent: Agent | undefined = defaultHttpAgent; + let req: RequestInit; + if (method === 'get') { + req = { + method, + headers: reqHeaders, + ...(httpAgent && { agent: httpAgent }), + }; + } else { + req = { + method, + body: JSON.stringify(parseBody(body)), + headers: reqHeaders, + ...(httpAgent && { agent: httpAgent }), + }; } + return { req: req, url: url.toString() }; + } methodRequest( method: HTTPMethod, diff --git a/src/client.ts b/src/client.ts index 9bc3f5f..445607a 100644 --- a/src/client.ts +++ b/src/client.ts @@ -30,15 +30,15 @@ export class Portkey extends ApiClient { azureResourceName?: string | null | undefined; azureDeploymentId?: string | null | undefined; azureApiVersion?: string | null | undefined; - azureEndpointName?: string | null | undefined; + azureEndpointName?: string | null | undefined; huggingfaceBaseUrl?: string | null | undefined; forwardHeaders?: Array | null | undefined; requestTimeout?: number | null | undefined; cacheNamespace?: string | null | undefined; strictOpenAiCompliance?: boolean | null | undefined; anthropicBeta?: string | null | undefined; - anthropicVersion?: string | null | undefined; - mistralFimCompletion?: string | null | undefined; + anthropicVersion?: string | null | undefined; + mistralFimCompletion?: string | null | undefined; constructor({ apiKey = readEnv('PORTKEY_API_KEY') ?? null, baseURL = readEnv('PORTKEY_BASE_URL') ?? null, @@ -63,15 +63,15 @@ export class Portkey extends ApiClient { azureResourceName, azureDeploymentId, azureApiVersion, - azureEndpointName, + azureEndpointName, huggingfaceBaseUrl, forwardHeaders, cacheNamespace, requestTimeout, strictOpenAiCompliance, anthropicBeta, - anthropicVersion, - mistralFimCompletion + anthropicVersion, + mistralFimCompletion, }: ApiClientInterface) { super({ apiKey, @@ -98,14 +98,14 @@ export class Portkey extends ApiClient { azureResourceName, azureDeploymentId, azureApiVersion, - azureEndpointName, + azureEndpointName, huggingfaceBaseUrl, forwardHeaders, requestTimeout, strictOpenAiCompliance, anthropicBeta, - anthropicVersion, - mistralFimCompletion + anthropicVersion, + mistralFimCompletion, }); this.apiKey = apiKey; @@ -134,40 +134,40 @@ export class Portkey extends ApiClient { this.azureResourceName = azureResourceName; this.azureDeploymentId = azureDeploymentId; this.azureApiVersion = azureApiVersion; - this.azureEndpointName = azureEndpointName; + this.azureEndpointName = azureEndpointName; this.huggingfaceBaseUrl = huggingfaceBaseUrl; this.forwardHeaders = forwardHeaders; this.requestTimeout = requestTimeout; this.strictOpenAiCompliance = strictOpenAiCompliance; this.anthropicBeta = anthropicBeta; - this.anthropicVersion = anthropicVersion; - this.mistralFimCompletion = mistralFimCompletion; + this.anthropicVersion = anthropicVersion; + this.mistralFimCompletion = mistralFimCompletion; } - completions: API.Completions = new API.Completions(this); - chat = new API.Chat(this); - embeddings = new API.Embeddings(this); - files = new API.MainFiles(this); - images = new API.Images(this); - models = new API.Models(this); - generations = new API.Generations(this); - prompts = new API.Prompt(this); - feedback = new API.Feedback(this); - batches = new API.Batches(this); - fineTuning = new API.FineTuning(this); - moderations = new API.Moderations(this); - audio = new API.Audio(this); - uploads = new API.Uploads(this); - admin = new API.Admin(this); - virtualKeys = new API.VirtualKeys(this); - apiKeys = new API.ApiKeys(this); - configs = new API.Configs(this); - beta = { - assistants: new API.Assistants(this), - threads: new API.Threads(this), - vectorStores: new API.VectorStores(this), - chat: new API.BetaChat(this), - }; + completions: API.Completions = new API.Completions(this); + chat = new API.Chat(this); + embeddings = new API.Embeddings(this); + files = new API.MainFiles(this); + images = new API.Images(this); + models = new API.Models(this); + generations = new API.Generations(this); + prompts = new API.Prompt(this); + feedback = new API.Feedback(this); + batches = new API.Batches(this); + fineTuning = new API.FineTuning(this); + moderations = new API.Moderations(this); + audio = new API.Audio(this); + uploads = new API.Uploads(this); + admin = new API.Admin(this); + virtualKeys = new API.VirtualKeys(this); + apiKeys = new API.ApiKeys(this); + configs = new API.Configs(this); + beta = { + assistants: new API.Assistants(this), + threads: new API.Threads(this), + vectorStores: new API.VectorStores(this), + chat: new API.BetaChat(this), + }; post = ( url: string, diff --git a/src/utils.ts b/src/utils.ts index 2224257..5c38ca4 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -2,10 +2,15 @@ import { OPEN_AI_API_KEY, PORTKEY_HEADER_PREFIX } from './constants'; import { createResponseHeaders } from './streaming'; import OpenAI from 'openai'; import type { Portkey } from './index'; -import { UserInviteListParams, UsersListParams, WorkspaceMemberListParams, WorkspacesListParams } from "./apis/admin"; -import { VirtualKeysListParams } from "./apis/virtualKeys"; -import { ApiKeysListParams } from "./apis/apiKeys"; -import { CongfigsListParams } from "./apis/configs"; +import { + UserInviteListParams, + UsersListParams, + WorkspaceMemberListParams, + WorkspacesListParams, +} from './apis/admin'; +import { VirtualKeysListParams } from './apis/virtualKeys'; +import { ApiKeysListParams } from './apis/apiKeys'; +import { CongfigsListParams } from './apis/configs'; type PlatformProperties = { 'x-portkey-runtime'?: string; @@ -142,14 +147,23 @@ export function initOpenAIClient(client: Portkey) { maxRetries: 0, }); } -export function toQueryParams(params?: (UsersListParams | UserInviteListParams | WorkspacesListParams | WorkspaceMemberListParams |VirtualKeysListParams | ApiKeysListParams | CongfigsListParams)): string { - if (!params) { - return ''; - } - const queryParams = Object.entries(params) - .filter(([, value]) => value !== undefined && value !== null) - .map(([key, value]) => `${key}=${value}`) - .join('&'); - - return queryParams ? `?${queryParams}` : ''; +export function toQueryParams( + params?: + | UsersListParams + | UserInviteListParams + | WorkspacesListParams + | WorkspaceMemberListParams + | VirtualKeysListParams + | ApiKeysListParams + | CongfigsListParams +): string { + if (!params) { + return ''; + } + const queryParams = Object.entries(params) + .filter(([, value]) => value !== undefined && value !== null) + .map(([key, value]) => `${key}=${value}`) + .join('&'); + + return queryParams ? `?${queryParams}` : ''; } diff --git a/src/version.ts b/src/version.ts index 24d5ef7..071d772 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1 +1 @@ -export const VERSION = "1.5.0"; \ No newline at end of file +export const VERSION = '1.5.0';