@zhengxs/erniebot
Version:
非官方 JS-SDK,可以调用文心大模型的能力,包含文本创作、通用对话、语义向量、AI作图等
741 lines (659 loc) • 24.4 kB
TypeScript
declare namespace API {
export {
CompletionUsage,
CreateEmbeddingResponse,
Embedding,
EmbeddingCreateParams,
Embeddings,
Chat,
ChatCompletion,
ChatCompletionChunk,
ChatCompletionMessage,
ChatCompletionMessageParam,
ChatCompletionRole,
ChatCompletionCreateParams,
ChatCompletionCreateParamsNonStreaming,
ChatCompletionCreateParamsStreaming,
Completions
}
}
declare abstract class APIBackend {
client: ERNIEBot;
abstract apiType: string;
abstract baseURL: string;
abstract resources: APIBackendResources;
setup(client: ERNIEBot): void;
/**
* 覆盖当前请求路径
*
* @param path - 当前路径
* @param model - 请求模型
* @returns 返回空值将使用预设的路径
*/
overrideResourcePath(path: string, model: string): string | undefined;
/**
* 返回默认请求参数
*/
defaultQuery(): MaybePromise<HTTPSearchParams>;
/**
* 添加授权请求头
*/
authHeaders(options: APIRequestOptions): APIHeaders;
/**
* 预处理请求
*/
prepareRequest(req: APIRequestInit, init: {
url: string;
options: APIRequestOptions;
}): MaybePromise<void>;
transformResponse(type: 'json', data: any): any;
parseResponse({ response, options, controller }: APIResponseProps): Promise<any>;
protected makeStatusError(ecode: number | undefined, error: Error, message: string, headers: Headers): APIError_2;
}
declare type APIBackendModuleInfo = {
moduleId: string;
};
declare type APIBackendResourceInfo = {
resourceId: string;
models: {
[model: string]: APIBackendModuleInfo;
};
};
declare type APIBackendResources = {
[resource: string]: APIBackendResourceInfo;
};
declare type APIBody = Record<string, any>;
declare class APIClient {
baseURL: string;
headers: APIHeaders;
timeout: number;
maxRetries: number;
fetch: Fetch;
constructor(options?: APIClientOptions);
get<Rsp>(path: string, opts?: Omit<APIRequestConfig, 'method'>): APIPromise<Rsp>;
post<Rsp>(path: string, opts?: Omit<APIRequestConfig, 'method'>): APIPromise<Rsp>;
patch<Rsp>(path: string, opts?: Omit<APIRequestConfig, 'method'>): APIPromise<Rsp>;
put<Rsp>(path: string, opts?: Omit<APIRequestConfig, 'method'>): APIPromise<Rsp>;
delete<Rsp>(path: string, opts?: Omit<APIRequestConfig, 'method'>): APIPromise<Rsp>;
private methodRequest;
request<Rsp = any>(options: APIRequestOptions, remainingRetries?: number | null): APIPromise<Rsp>;
protected defaultQuery(): Promise<HTTPSearchParams>;
/**
* Override this to add your own default headers, for example:
*
* ```js
* {
* ...super.defaultHeaders(),
* Authorization: 'Bearer 123',
* }
* ```
*/
protected defaultHeaders(options: APIRequestOptions): APIHeaders;
protected parseResponse<T>({ response, options, controller }: APIResponseProps): Promise<T>;
protected authHeaders(options: APIRequestOptions): APIHeaders;
protected getUserAgent(): string;
protected validateHeaders(headers: APIHeaders, customHeaders: APIHeaders): void;
/**
* Used as a callback for mutating the given `RequestInit` object.
*
* This is useful for cases where you want to add certain headers based off of
* the request properties, e.g. `method` or `url`.
*/
protected prepareRequest(request: APIRequestInit, { url, options }: {
url: string;
options: APIRequestOptions;
}): MaybePromise<any>;
protected getRequestClient(): HTTPClient;
fetchWithTimeout(url: RequestInfo, init: RequestInit | undefined, ms: number, controller: AbortController): Promise<Response>;
protected buildURL({ path, query }: APIRequestOptions): Promise<string>;
private makeRequest;
protected makeStatusError(status: number | undefined, error: unknown | undefined, message: string | undefined, headers: Headers | undefined): APIError_2;
private buildRequest;
}
declare interface APIClientOptions {
/**
* Override the default base URL for the API, e.g., "https://api.example.com/v2/"
*/
baseURL?: string;
/**
* 请求头
*/
headers?: APIHeaders;
/**
* The maximum amount of time (in milliseconds) that the client should wait for a response
* from the server before timing out a single request.
*
* Note that request timeouts are retried by default, so in a worst-case scenario you may wait
* much longer than this timeout before the promise succeeds or fails.
*
* @defaultValue 10 minutes
*/
timeout?: number;
/**
* TODO 待实现
*
* @defaultValue 2
*/
maxRetries?: number;
/**
* 网络请求
*/
fetch?: Fetch;
[key: string]: any;
}
export declare const APIConnectionError: typeof Errors.APIConnectionError;
declare class APIConnectionError_2 extends APIError_2 {
readonly status: undefined;
constructor({ message, cause }: {
message?: string;
cause?: Error | undefined;
});
}
export declare const APIConnectionTimeoutError: typeof Errors.APIConnectionTimeoutError;
declare class APIConnectionTimeoutError_2 extends APIConnectionError_2 {
constructor({ message }?: {
message?: string;
});
}
export declare const APIError: typeof Errors.APIError;
declare class APIError_2 extends EBError_2 {
readonly status: number | undefined;
readonly headers: Headers | undefined;
readonly error: unknown | undefined;
readonly code: string | null | undefined;
readonly param: string | null | undefined;
readonly type: string | undefined;
constructor(status: number | undefined, error: unknown | undefined, message: string | undefined, headers: Headers | undefined);
private static makeMessage;
static generate(status: number | undefined, errorResponse: unknown | undefined, message: string | undefined, headers: Headers | undefined): APIError_2;
}
declare type APIHeaders = Record<string, string>;
declare type APIMultipartBody = {
body?: BodyInit | null;
};
/**
* A subclass of `Promise` providing additional helper methods
* for interacting with the SDK.
*/
declare class APIPromise<T> extends Promise<T> {
private responsePromise;
private parseResponse;
private parsedPromise;
constructor(responsePromise: Promise<APIResponseProps>, parseResponse: (props: APIResponseProps) => MaybePromise<T>);
_thenUnwrap<U>(transform: (data: T) => U): APIPromise<U>;
asResponse(): Promise<Response>;
withResponse(): Promise<{
data: T;
response: Response;
}>;
private parse;
then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>;
catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<T | TResult>;
finally(onfinally?: (() => void) | undefined | null): Promise<T>;
}
declare type APIRequestConfig = Omit<APIRequestOptions, 'path'>;
declare interface APIRequestInit extends RequestInit {
method: string;
headers: Record<string, string>;
}
declare interface APIRequestOptions extends Omit<RequestInit, 'body' | 'headers'> {
path: string;
query?: HTTPSearchParams;
body?: APIBody | APIMultipartBody | null | undefined;
headers?: APIHeaders;
timeout?: number;
stream?: boolean;
maxRetries?: number;
}
declare class APIResource {
protected client: ERNIEBot;
protected get: ERNIEBot['get'];
protected post: ERNIEBot['post'];
protected patch: ERNIEBot['patch'];
protected put: ERNIEBot['put'];
protected delete: ERNIEBot['delete'];
constructor(client: ERNIEBot);
}
declare type APIResponseProps = {
response: Response;
options: APIRequestOptions;
controller: AbortController;
};
declare class APIStream<Item> implements AsyncIterable<Item> {
private iterator;
controller: AbortController;
constructor(iterator: () => AsyncIterator<Item>, controller: AbortController);
static fromSSEResponse<Item>(response: Response, controller: AbortController): APIStream<Item>;
static fromReadableStream<Item>(readableStream: ReadableStream, controller: AbortController): APIStream<Item>;
[Symbol.asyncIterator](): AsyncIterator<Item>;
tee(): [APIStream<Item>, APIStream<Item>];
toReadableStream(): ReadableStream;
}
declare type APIType = (string & NonNullable<unknown>) | 'aistudio' | 'qianfan';
export declare const APIUserAbortError: typeof Errors.APIUserAbortError;
declare class APIUserAbortError_2 extends APIError_2 {
readonly status: undefined;
constructor({ message }?: {
message?: string;
});
}
export declare const AuthenticationError: typeof Errors.AuthenticationError;
declare class AuthenticationError_2 extends APIError_2 {
readonly status = 401;
}
export declare const BadRequestError: typeof Errors.BadRequestError;
declare class BadRequestError_2 extends APIError_2 {
readonly status = 400;
}
declare function calculateContentLength(body: BodyInit | null): string | null;
declare class Chat extends APIResource {
completions: Completions;
}
/**
* Represents a chat completion response returned by model, based on the provided
* input.
*/
declare interface ChatCompletion {
/**
* A unique identifier for the chat completion.
*/
id: string;
/**
* The object type, which is always `chat.completion`.
*/
object: string;
result: string;
need_clear_history: boolean;
is_truncated: boolean;
/**
* Usage statistics for the completion request.
*/
usage: CompletionUsage;
/**
* The Unix timestamp (in seconds) of when the chat completion was created.
*/
created: number;
/**
* The name and arguments of a function that should be called, as generated by the
* model.
*/
function_call?: ChatCompletion.FunctionCall;
}
declare namespace ChatCompletion {
/**
* The name and arguments of a function that should be called, as generated by the
* model.
*/
interface FunctionCall {
/**
* The name of the function to call.
*/
name?: string;
/**
* The arguments to call the function with, as generated by the model in JSON
* format. Note that the model does not always generate valid JSON, and may
* hallucinate parameters not defined by your function schema. Validate the
* arguments in your code before calling your function.
*/
arguments?: string;
thoughts?: string;
}
}
/**
* Represents a streamed chunk of a chat completion response returned by model,
* based on the provided input.
*/
declare interface ChatCompletionChunk {
/**
* A unique identifier for the chat completion. Each chunk has the same ID.
*/
id: string;
result: string;
/**
* Usage statistics for the completion request.
*/
usage: CompletionUsage;
sentence_id: string;
is_end: boolean;
is_truncated: boolean;
need_clear_history: boolean;
/**
* The Unix timestamp (in seconds) of when the chat completion was created. Each
* chunk has the same timestamp.
*/
created: number;
/**
* The object type, which is always `chat.completion.chunk`.
*/
object: string;
/**
* The name and arguments of a function that should be called, as generated by the
* model.
*/
function_call?: ChatCompletion.FunctionCall;
}
declare type ChatCompletionCreateParams = ChatCompletionCreateParamsNonStreaming | ChatCompletionCreateParamsStreaming;
declare namespace ChatCompletionCreateParams {
interface FunctionCallOption {
name: string;
}
interface Function {
name: string;
parameters: Record<string, unknown>;
description?: string;
responses?: Record<string, unknown>;
}
interface ChatCompletionCreateParamsNonStreaming extends ChatCompletionCreateParamsBase {
stream?: false | null;
}
interface ChatCompletionCreateParamsStreaming extends ChatCompletionCreateParamsBase {
stream: true;
}
}
declare interface ChatCompletionCreateParamsBase {
messages: Array<ChatCompletionMessageParam>;
model: (string & NonNullable<unknown>) | 'ernie-bot' | 'ernie-bot-turbo' | 'ernie-bot-4';
frequency_penalty?: number | null;
function_call?: 'none' | 'auto' | ChatCompletionCreateParams.FunctionCallOption;
functions?: Array<ChatCompletionCreateParams.Function>;
max_tokens?: number | null;
n?: number | null;
presence_penalty?: number | null;
stop?: string | null | Array<string>;
stream?: boolean | null;
temperature?: number | null;
top_p?: number | null;
user?: string;
}
declare type ChatCompletionCreateParamsNonStreaming = ChatCompletionCreateParams.ChatCompletionCreateParamsNonStreaming;
declare type ChatCompletionCreateParamsStreaming = ChatCompletionCreateParams.ChatCompletionCreateParamsStreaming;
/**
* A chat completion message generated by the model.
*/
declare interface ChatCompletionMessage {
/**
* The contents of the message.
*/
content: string | null;
/**
* The role of the author of this message.
*/
role: ChatCompletionRole;
/**
* The name and arguments of a function that should be called, as generated by the
* model.
*/
function_call?: ChatCompletionMessage.FunctionCall;
}
declare namespace ChatCompletionMessage {
/**
* The name and arguments of a function that should be called, as generated by the
* model.
*/
interface FunctionCall {
arguments: string;
name: string;
}
}
declare interface ChatCompletionMessageParam {
/**
* The contents of the message. `content` is required for all messages, and may be
* null for assistant messages with function calls.
*/
content: string | null;
/**
* The role of the messages author. One of `system`, `user`, `assistant`, or
* `function`.
*/
role: 'system' | 'user' | 'assistant' | 'function';
/**
* The name and arguments of a function that should be called, as generated by the
* model.
*/
function_call?: ChatCompletionMessageParam.FunctionCall;
/**
* The name of the author of this message. `name` is required if role is
* `function`, and it should be the name of the function whose response is in the
* `content`. May contain a-z, A-Z, 0-9, and underscores, with a maximum length of
* 64 characters.
*/
name?: string;
}
declare namespace ChatCompletionMessageParam {
/**
* The name and arguments of a function that should be called, as generated by the
* model.
*/
interface FunctionCall {
/**
* The arguments to call the function with, as generated by the model in JSON
* format. Note that the model does not always generate valid JSON, and may
* hallucinate parameters not defined by your function schema. Validate the
* arguments in your code before calling your function.
*/
arguments: string;
/**
* The name of the function to call.
*/
name: string;
}
}
/**
* The role of the author of this message.
*/
declare type ChatCompletionRole = 'system' | 'user' | 'assistant' | 'function';
declare class Completions extends APIResource {
/**
* Creates a model response for the given chat conversation.
*/
create(body: ChatCompletionCreateParamsNonStreaming, options?: APIRequestOptions): APIPromise<ChatCompletion>;
create(body: ChatCompletionCreateParamsStreaming, options?: APIRequestOptions): APIPromise<APIStream<ChatCompletionChunk>>;
create(body: ChatCompletionCreateParamsBase, options?: APIRequestOptions): APIPromise<APIStream<ChatCompletionChunk> | ChatCompletion>;
}
/**
* Usage statistics for the completion request.
*/
declare interface CompletionUsage {
/**
* Number of tokens in the generated completion.
*/
completion_tokens: number;
/**
* Number of tokens in the prompt.
*/
prompt_tokens: number;
/**
* Total number of tokens used in the request (prompt + completion).
*/
total_tokens: number;
}
export declare const ConflictError: typeof Errors.ConflictError;
declare class ConflictError_2 extends APIError_2 {
readonly status = 409;
}
declare namespace Core {
export {
isMultipartBody,
calculateContentLength,
mergeHTTPSearchParams,
createResponseHeaders,
MultipartBody,
APIClientOptions,
APIClient,
APIPromise,
APIStream
}
}
declare interface CreateEmbeddingResponse {
data: Array<Embedding>;
model: (string & NonNullable<unknown>) | 'ernie-text-embedding';
object: string;
usage: CreateEmbeddingResponse.Usage;
}
declare namespace CreateEmbeddingResponse {
interface Usage {
prompt_tokens: number;
total_tokens: number;
}
}
declare function createResponseHeaders(headers: Awaited<ReturnType<Fetch>>['headers']): Record<string, string>;
export declare const EBError: typeof Errors.EBError;
declare class EBError_2 extends Error {
}
export declare interface EBOptions extends Core.APIClientOptions {
/**
* Defaults to process.env['EB_API_TYPE'].
*
* @defaultValue aistudio
*/
apiType?: APIType;
/**
* Defaults to process.env['EB_ACCESS_TOKEN'].
*
* @defaultValue aistudio
*/
token?: string;
/**
* Defaults to process.env['EB_SK'].
*
* @defaultValue aistudio
*/
sk?: string;
/**
* Defaults to process.env['EB_AK'].
*
* @defaultValue aistudio
*/
ak?: string;
/**
* By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.
* Only set this option to `true` if you understand the risks and have appropriate mitigations in place.
*/
dangerouslyAllowBrowser?: boolean;
}
declare interface Embedding {
embedding: Array<number>;
index: number;
object: string;
}
declare interface EmbeddingCreateParams {
input: string | Array<string> | Array<number> | Array<Array<number>>;
model: string;
}
declare class Embeddings extends APIResource {
create(body: EmbeddingCreateParams, options?: APIRequestOptions): APIPromise<CreateEmbeddingResponse>;
}
declare class ERNIEBot extends Core.APIClient {
#private;
options?: EBOptions | undefined;
token?: string;
sk?: string;
ak?: string;
/**
* API Client for interfacing with the ERNIE Bot API.
*/
constructor(options?: EBOptions | undefined);
get apiType(): APIType;
set apiType(apiType: APIType);
get backend(): APIBackend;
set backend(backend: APIBackend);
chat: API.Chat;
embeddings: API.Embeddings;
protected getUserAgent(): string;
protected defaultQuery(): Promise<HTTPSearchParams>;
protected authHeaders(options: APIRequestOptions): APIHeaders;
protected prepareRequest(req: APIRequestInit, init: {
url: string;
options: APIRequestOptions;
}): MaybePromise<void>;
protected parseResponse<T>(props: APIResponseProps): Promise<T>;
protected buildURL(options: APIRequestOptions): Promise<string>;
static ERNIEBot: typeof ERNIEBot;
static version: string;
static EBError: typeof Errors.EBError;
static APIError: typeof Errors.APIError;
static APIConnectionError: typeof Errors.APIConnectionError;
static APIConnectionTimeoutError: typeof Errors.APIConnectionTimeoutError;
static APIUserAbortError: typeof Errors.APIUserAbortError;
static NotFoundError: typeof Errors.NotFoundError;
static ConflictError: typeof Errors.ConflictError;
static RateLimitError: typeof Errors.RateLimitError;
static BadRequestError: typeof Errors.BadRequestError;
static AuthenticationError: typeof Errors.AuthenticationError;
static InternalServerError: typeof Errors.InternalServerError;
static PermissionDeniedError: typeof Errors.PermissionDeniedError;
static UnprocessableEntityError: typeof Errors.UnprocessableEntityError;
}
declare namespace ERNIEBot {
type Chat = API.Chat;
type ChatCompletion = API.ChatCompletion;
type ChatCompletionChunk = API.ChatCompletionChunk;
type ChatCompletionMessage = API.ChatCompletionMessage;
type ChatCompletionMessageParam = API.ChatCompletionMessageParam;
type ChatCompletionRole = API.ChatCompletionRole;
type ChatCompletionCreateParams = API.ChatCompletionCreateParams;
type ChatCompletionCreateParamsNonStreaming = API.ChatCompletionCreateParamsNonStreaming;
type ChatCompletionCreateParamsStreaming = API.ChatCompletionCreateParamsStreaming;
type Embeddings = API.Embeddings;
type CreateEmbeddingResponse = API.CreateEmbeddingResponse;
type Embedding = API.Embedding;
type EmbeddingCreateParams = API.EmbeddingCreateParams;
}
export { ERNIEBot }
export default ERNIEBot;
declare namespace Errors {
export {
EBError_2 as EBError,
InvalidArgumentError,
UnsupportedAPITypeError,
APIError_2 as APIError,
APIUserAbortError_2 as APIUserAbortError,
APIConnectionError_2 as APIConnectionError,
APIConnectionTimeoutError_2 as APIConnectionTimeoutError,
BadRequestError_2 as BadRequestError,
AuthenticationError_2 as AuthenticationError,
PermissionDeniedError_2 as PermissionDeniedError,
NotFoundError_2 as NotFoundError,
ConflictError_2 as ConflictError,
UnprocessableEntityError_2 as UnprocessableEntityError,
RateLimitError_2 as RateLimitError,
InternalServerError_2 as InternalServerError
}
}
declare type Fetch = (url: RequestInfo, init?: RequestInit) => Promise<Response>;
declare type HTTPClient = {
fetch: Fetch;
};
declare type HTTPSearchParams = URLSearchParams | Record<string, string>;
export declare const InternalServerError: typeof Errors.InternalServerError;
declare class InternalServerError_2 extends APIError_2 {
}
declare class InvalidArgumentError extends EBError_2 {
}
declare function isMultipartBody(body: any): body is MultipartBody;
declare type MaybePromise<T> = T | Promise<T>;
declare function mergeHTTPSearchParams(target: HTTPSearchParams | undefined, source?: HTTPSearchParams): URLSearchParams;
declare class MultipartBody {
body: any;
constructor(body: any);
get [Symbol.toStringTag](): string;
}
export declare const NotFoundError: typeof Errors.NotFoundError;
declare class NotFoundError_2 extends APIError_2 {
readonly status = 404;
}
export declare const PermissionDeniedError: typeof Errors.PermissionDeniedError;
declare class PermissionDeniedError_2 extends APIError_2 {
readonly status = 403;
}
export declare const RateLimitError: typeof Errors.RateLimitError;
declare class RateLimitError_2 extends APIError_2 {
readonly status = 429;
}
export declare const UnprocessableEntityError: typeof Errors.UnprocessableEntityError;
declare class UnprocessableEntityError_2 extends APIError_2 {
readonly status = 422;
}
declare class UnsupportedAPITypeError extends EBError_2 {
}
export { }