@open-dy/ai_coding_sdk 1.0.11 → 1.0.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +37 -0
- package/dist/ai_platform_llm/client.d.ts +29 -0
- package/dist/ai_platform_llm/client.js +107 -0
- package/dist/ai_platform_llm/core.d.ts +22 -0
- package/dist/ai_platform_llm/core.js +229 -0
- package/dist/ai_platform_llm/index.d.ts +4 -0
- package/dist/ai_platform_llm/index.js +25 -0
- package/dist/ai_platform_llm/permission.d.ts +15 -0
- package/dist/ai_platform_llm/permission.js +44 -0
- package/dist/ai_platform_llm/types.d.ts +312 -0
- package/dist/ai_platform_llm/types.js +2 -0
- package/dist/auth/access-token.d.ts +139 -0
- package/dist/auth/access-token.js +99 -0
- package/dist/auth/core.d.ts +15 -0
- package/dist/auth/core.js +76 -0
- package/dist/auth/index.d.ts +4 -0
- package/dist/auth/index.js +9 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +3 -1
- package/package.json +17 -1
package/README.md
CHANGED
|
@@ -24,6 +24,43 @@ const result = await searchVideo(
|
|
|
24
24
|
);
|
|
25
25
|
```
|
|
26
26
|
|
|
27
|
+
## Auth
|
|
28
|
+
|
|
29
|
+
```ts
|
|
30
|
+
import { getUserAccessToken, refreshUserAccessToken, refreshUserToken } from '@open-dy/ai_coding_sdk/auth';
|
|
31
|
+
|
|
32
|
+
const token = await getUserAccessToken({
|
|
33
|
+
client_key: process.env.CLIENT_KEY!,
|
|
34
|
+
client_secret: process.env.CLIENT_SECRET!,
|
|
35
|
+
code,
|
|
36
|
+
});
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## AI Platform LLM
|
|
40
|
+
|
|
41
|
+
```ts
|
|
42
|
+
import {
|
|
43
|
+
AIPlatformLLMClient,
|
|
44
|
+
checkMiniProgramModelPermission,
|
|
45
|
+
} from '@open-dy/ai_coding_sdk/ai_platform_llm';
|
|
46
|
+
|
|
47
|
+
const permission = await checkMiniProgramModelPermission({
|
|
48
|
+
micro_appid: process.env.CLIENT_KEY!,
|
|
49
|
+
model_tenant: 'douyin',
|
|
50
|
+
model_key: 'Doubao-Seed-1.6-back',
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
const client = new AIPlatformLLMClient({
|
|
54
|
+
accessToken: process.env.DELEGATE_TOKEN,
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
const result = await client.generate({
|
|
58
|
+
Messages: [{ Role: 'user', Content: '你好' }],
|
|
59
|
+
ModelTenant: 'douyin',
|
|
60
|
+
ModelKey: 'Doubao-Seed-1.6-back',
|
|
61
|
+
});
|
|
62
|
+
```
|
|
63
|
+
|
|
27
64
|
## License
|
|
28
65
|
|
|
29
66
|
Apache-2.0
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { AIPlatformCallOptions, AIPlatformEvent, AIPlatformLLMClientOptions, AIPlatformOpenAPIResponse, GenerateImageRequest, GenerateImageResponseData, GenerateRequest, GenerateResponseData, GenerateVideoRequest, GenerateVideoResponseData, QueryVideoTaskRequest, QueryVideoTaskResponseData, StreamGenerateRequest } from './types';
|
|
2
|
+
export declare class AIPlatformLLMClient {
|
|
3
|
+
private readonly accessToken?;
|
|
4
|
+
private readonly appEnv;
|
|
5
|
+
private readonly timeoutMs;
|
|
6
|
+
private readonly imageTimeoutMs;
|
|
7
|
+
private readonly streamTimeoutMs;
|
|
8
|
+
private readonly defaultHeaders;
|
|
9
|
+
private readonly gatewayOrigin;
|
|
10
|
+
constructor(options?: AIPlatformLLMClientOptions);
|
|
11
|
+
generate(req: GenerateRequest): Promise<AIPlatformOpenAPIResponse<GenerateResponseData>>;
|
|
12
|
+
generateImage(req: GenerateImageRequest): Promise<AIPlatformOpenAPIResponse<GenerateImageResponseData>>;
|
|
13
|
+
generateVideo(req: GenerateVideoRequest): Promise<AIPlatformOpenAPIResponse<GenerateVideoResponseData>>;
|
|
14
|
+
queryVideoTask(req: QueryVideoTaskRequest): Promise<AIPlatformOpenAPIResponse<QueryVideoTaskResponseData>>;
|
|
15
|
+
waitVideoTask(req: QueryVideoTaskRequest, options?: {
|
|
16
|
+
intervalMs?: number;
|
|
17
|
+
timeoutMs?: number;
|
|
18
|
+
}): Promise<AIPlatformOpenAPIResponse<QueryVideoTaskResponseData>>;
|
|
19
|
+
streamGenerate(req: StreamGenerateRequest): AsyncGenerator<AIPlatformEvent>;
|
|
20
|
+
}
|
|
21
|
+
export declare function generate(req: GenerateRequest, options?: AIPlatformCallOptions): Promise<AIPlatformOpenAPIResponse<GenerateResponseData>>;
|
|
22
|
+
export declare function generateImage(req: GenerateImageRequest, options?: AIPlatformCallOptions): Promise<AIPlatformOpenAPIResponse<GenerateImageResponseData>>;
|
|
23
|
+
export declare function generateVideo(req: GenerateVideoRequest, options?: AIPlatformCallOptions): Promise<AIPlatformOpenAPIResponse<GenerateVideoResponseData>>;
|
|
24
|
+
export declare function queryVideoTask(req: QueryVideoTaskRequest, options?: AIPlatformCallOptions): Promise<AIPlatformOpenAPIResponse<QueryVideoTaskResponseData>>;
|
|
25
|
+
export declare function waitVideoTask(req: QueryVideoTaskRequest, waitOptions?: {
|
|
26
|
+
intervalMs?: number;
|
|
27
|
+
timeoutMs?: number;
|
|
28
|
+
}, callOptions?: AIPlatformCallOptions): Promise<AIPlatformOpenAPIResponse<QueryVideoTaskResponseData>>;
|
|
29
|
+
export declare function streamGenerate(req: StreamGenerateRequest, options?: AIPlatformCallOptions): AsyncGenerator<AIPlatformEvent>;
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.AIPlatformLLMClient = void 0;
|
|
4
|
+
exports.generate = generate;
|
|
5
|
+
exports.generateImage = generateImage;
|
|
6
|
+
exports.generateVideo = generateVideo;
|
|
7
|
+
exports.queryVideoTask = queryVideoTask;
|
|
8
|
+
exports.waitVideoTask = waitVideoTask;
|
|
9
|
+
exports.streamGenerate = streamGenerate;
|
|
10
|
+
const core_1 = require("./core");
|
|
11
|
+
function sleep(ms) {
|
|
12
|
+
return new Promise(resolve => setTimeout(resolve, ms));
|
|
13
|
+
}
|
|
14
|
+
class AIPlatformLLMClient {
|
|
15
|
+
constructor(options = {}) {
|
|
16
|
+
this.appEnv = (0, core_1.getAIPlatformAppEnv)();
|
|
17
|
+
this.accessToken = options.accessToken;
|
|
18
|
+
this.timeoutMs = options.timeoutMs ?? core_1.AI_PLATFORM_DEFAULT_REQUEST_TIMEOUT_MS;
|
|
19
|
+
this.imageTimeoutMs = options.imageTimeoutMs ?? core_1.AI_PLATFORM_DEFAULT_IMAGE_TIMEOUT_MS;
|
|
20
|
+
this.streamTimeoutMs = options.streamTimeoutMs ?? core_1.AI_PLATFORM_DEFAULT_STREAM_TIMEOUT_MS;
|
|
21
|
+
this.defaultHeaders = options.defaultHeaders ?? {};
|
|
22
|
+
this.gatewayOrigin = options.gatewayOrigin ?? (0, core_1.getAIPlatformGatewayOrigin)(this.appEnv);
|
|
23
|
+
}
|
|
24
|
+
async generate(req) {
|
|
25
|
+
return (0, core_1.postAIPlatformJSON)(this.gatewayOrigin, '/dy_open_api/ai_platform/llm_gen/generate/', req, {
|
|
26
|
+
accessToken: this.accessToken,
|
|
27
|
+
defaultHeaders: this.defaultHeaders,
|
|
28
|
+
appEnv: this.appEnv,
|
|
29
|
+
timeoutMs: this.timeoutMs,
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
async generateImage(req) {
|
|
33
|
+
return (0, core_1.postAIPlatformJSON)(this.gatewayOrigin, '/dy_open_api/ai_platform/llm_gen/image_generate/', req, {
|
|
34
|
+
accessToken: this.accessToken,
|
|
35
|
+
defaultHeaders: this.defaultHeaders,
|
|
36
|
+
appEnv: this.appEnv,
|
|
37
|
+
timeoutMs: this.imageTimeoutMs,
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
async generateVideo(req) {
|
|
41
|
+
return (0, core_1.postAIPlatformJSON)(this.gatewayOrigin, '/dy_open_api/ai_platform/llm_gen/video_generate/', req, {
|
|
42
|
+
accessToken: this.accessToken,
|
|
43
|
+
defaultHeaders: this.defaultHeaders,
|
|
44
|
+
appEnv: this.appEnv,
|
|
45
|
+
timeoutMs: this.timeoutMs,
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
async queryVideoTask(req) {
|
|
49
|
+
return (0, core_1.postAIPlatformJSON)(this.gatewayOrigin, '/dy_open_api/ai_platform/llm_gen/query_video_task/', req, {
|
|
50
|
+
accessToken: this.accessToken,
|
|
51
|
+
defaultHeaders: this.defaultHeaders,
|
|
52
|
+
appEnv: this.appEnv,
|
|
53
|
+
timeoutMs: this.timeoutMs,
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
async waitVideoTask(req, options) {
|
|
57
|
+
const intervalMs = options?.intervalMs ?? 2000;
|
|
58
|
+
const timeoutMs = options?.timeoutMs ?? 120000;
|
|
59
|
+
const startedAt = Date.now();
|
|
60
|
+
while (true) {
|
|
61
|
+
const result = await this.queryVideoTask(req);
|
|
62
|
+
const status = result?.data?.Status;
|
|
63
|
+
if (status === 'succeeded' || status === 'failed' || status === 'cancelled') {
|
|
64
|
+
return result;
|
|
65
|
+
}
|
|
66
|
+
if (Date.now() - startedAt > timeoutMs) {
|
|
67
|
+
throw new Error('video_task_poll_timeout');
|
|
68
|
+
}
|
|
69
|
+
await sleep(intervalMs);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
async *streamGenerate(req) {
|
|
73
|
+
for await (const event of (0, core_1.streamAIPlatform)(this.gatewayOrigin, '/dy_open_api/ai_platform/llm_gen/stream_generate/', req, {
|
|
74
|
+
accessToken: this.accessToken,
|
|
75
|
+
defaultHeaders: this.defaultHeaders,
|
|
76
|
+
appEnv: this.appEnv,
|
|
77
|
+
timeoutMs: this.streamTimeoutMs,
|
|
78
|
+
})) {
|
|
79
|
+
yield event;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
exports.AIPlatformLLMClient = AIPlatformLLMClient;
|
|
84
|
+
async function generate(req, options) {
|
|
85
|
+
return new AIPlatformLLMClient((0, core_1.createAIPlatformClientOptions)(options)).generate(req);
|
|
86
|
+
}
|
|
87
|
+
async function generateImage(req, options) {
|
|
88
|
+
const clientOptions = (0, core_1.createAIPlatformClientOptions)(options);
|
|
89
|
+
clientOptions.imageTimeoutMs = options?.timeoutMs;
|
|
90
|
+
return new AIPlatformLLMClient(clientOptions).generateImage(req);
|
|
91
|
+
}
|
|
92
|
+
async function generateVideo(req, options) {
|
|
93
|
+
return new AIPlatformLLMClient((0, core_1.createAIPlatformClientOptions)(options)).generateVideo(req);
|
|
94
|
+
}
|
|
95
|
+
async function queryVideoTask(req, options) {
|
|
96
|
+
return new AIPlatformLLMClient((0, core_1.createAIPlatformClientOptions)(options)).queryVideoTask(req);
|
|
97
|
+
}
|
|
98
|
+
async function waitVideoTask(req, waitOptions, callOptions) {
|
|
99
|
+
return new AIPlatformLLMClient((0, core_1.createAIPlatformClientOptions)(callOptions)).waitVideoTask(req, waitOptions);
|
|
100
|
+
}
|
|
101
|
+
async function* streamGenerate(req, options) {
|
|
102
|
+
const clientOptions = (0, core_1.createAIPlatformClientOptions)(options);
|
|
103
|
+
clientOptions.streamTimeoutMs = options?.timeoutMs;
|
|
104
|
+
for await (const event of new AIPlatformLLMClient(clientOptions).streamGenerate(req)) {
|
|
105
|
+
yield event;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { AIPlatformCallOptions, AIPlatformEvent, AIPlatformLLMClientOptions, AIPlatformOpenAPIResponse, CheckMiniProgramModelPermissionRequest, CheckMiniProgramModelPermissionResponse } from './types';
|
|
2
|
+
export type AIPlatformAppEnv = 'DEV' | 'PROD';
|
|
3
|
+
export declare function getAIPlatformAppEnv(): AIPlatformAppEnv;
|
|
4
|
+
export declare function getAIPlatformGatewayOrigin(appEnv?: AIPlatformAppEnv): string;
|
|
5
|
+
export declare function createAIPlatformClientOptions(options?: AIPlatformCallOptions): AIPlatformLLMClientOptions;
|
|
6
|
+
export declare function postAIPlatformJSON<T>(gatewayOrigin: string, path: string, body: unknown, options?: {
|
|
7
|
+
accessToken?: string;
|
|
8
|
+
defaultHeaders?: Record<string, string>;
|
|
9
|
+
appEnv?: AIPlatformAppEnv;
|
|
10
|
+
timeoutMs?: number;
|
|
11
|
+
}): Promise<T>;
|
|
12
|
+
export declare function postMiniProgramModelPermission(body: CheckMiniProgramModelPermissionRequest, options?: AIPlatformCallOptions): Promise<CheckMiniProgramModelPermissionResponse>;
|
|
13
|
+
export declare function parseSSEStream(stream: ReadableStream<Uint8Array>): AsyncGenerator<AIPlatformEvent>;
|
|
14
|
+
export declare function streamAIPlatform<T extends AIPlatformOpenAPIResponse<unknown> = AIPlatformOpenAPIResponse<unknown>>(gatewayOrigin: string, path: string, body: unknown, options?: {
|
|
15
|
+
accessToken?: string;
|
|
16
|
+
defaultHeaders?: Record<string, string>;
|
|
17
|
+
appEnv?: AIPlatformAppEnv;
|
|
18
|
+
timeoutMs?: number;
|
|
19
|
+
}): AsyncGenerator<AIPlatformEvent>;
|
|
20
|
+
export declare const AI_PLATFORM_DEFAULT_REQUEST_TIMEOUT_MS = 60000;
|
|
21
|
+
export declare const AI_PLATFORM_DEFAULT_IMAGE_TIMEOUT_MS = 120000;
|
|
22
|
+
export declare const AI_PLATFORM_DEFAULT_STREAM_TIMEOUT_MS = 120000;
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.AI_PLATFORM_DEFAULT_STREAM_TIMEOUT_MS = exports.AI_PLATFORM_DEFAULT_IMAGE_TIMEOUT_MS = exports.AI_PLATFORM_DEFAULT_REQUEST_TIMEOUT_MS = void 0;
|
|
4
|
+
exports.getAIPlatformAppEnv = getAIPlatformAppEnv;
|
|
5
|
+
exports.getAIPlatformGatewayOrigin = getAIPlatformGatewayOrigin;
|
|
6
|
+
exports.createAIPlatformClientOptions = createAIPlatformClientOptions;
|
|
7
|
+
exports.postAIPlatformJSON = postAIPlatformJSON;
|
|
8
|
+
exports.postMiniProgramModelPermission = postMiniProgramModelPermission;
|
|
9
|
+
exports.parseSSEStream = parseSSEStream;
|
|
10
|
+
exports.streamAIPlatform = streamAIPlatform;
|
|
11
|
+
const OPENAPI_ORIGIN = 'open.douyin.com';
|
|
12
|
+
const PERMISSION_ORIGIN = 'https://douyin-ai.bytedance.net';
|
|
13
|
+
const CLOUD_CALL_DOMAIN_MAP = {
|
|
14
|
+
'open.douyin.com': 'open-douyin-com.openapi.dyc.ivolces.com',
|
|
15
|
+
};
|
|
16
|
+
const DEFAULT_REQUEST_TIMEOUT_MS = 60000;
|
|
17
|
+
const DEFAULT_IMAGE_TIMEOUT_MS = 120000;
|
|
18
|
+
const DEFAULT_STREAM_TIMEOUT_MS = 120000;
|
|
19
|
+
function isDevEnvironment() {
|
|
20
|
+
return process.env.APP_ENV === 'DEV';
|
|
21
|
+
}
|
|
22
|
+
function getAIPlatformAppEnv() {
|
|
23
|
+
return isDevEnvironment() ? 'DEV' : 'PROD';
|
|
24
|
+
}
|
|
25
|
+
function getAIPlatformGatewayOrigin(appEnv = getAIPlatformAppEnv()) {
|
|
26
|
+
if (appEnv === 'DEV') {
|
|
27
|
+
return `https://${OPENAPI_ORIGIN}`;
|
|
28
|
+
}
|
|
29
|
+
const mappedDomain = CLOUD_CALL_DOMAIN_MAP[OPENAPI_ORIGIN] ?? OPENAPI_ORIGIN;
|
|
30
|
+
return `http://${mappedDomain}`;
|
|
31
|
+
}
|
|
32
|
+
function createAIPlatformClientOptions(options) {
|
|
33
|
+
const defaultHeaders = {
|
|
34
|
+
...(options?.defaultHeaders ?? {}),
|
|
35
|
+
...(options?.logid ? { 'x-tt-logid': options.logid } : {}),
|
|
36
|
+
};
|
|
37
|
+
return {
|
|
38
|
+
accessToken: options?.accessToken,
|
|
39
|
+
timeoutMs: options?.timeoutMs,
|
|
40
|
+
defaultHeaders,
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
function buildJSONHeaders(accessToken, defaultHeaders, appEnv) {
|
|
44
|
+
return {
|
|
45
|
+
'content-type': 'application/json',
|
|
46
|
+
...(appEnv === 'DEV' && accessToken ? { 'access-token': accessToken } : {}),
|
|
47
|
+
...defaultHeaders,
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
function buildStreamHeaders(accessToken, defaultHeaders, appEnv) {
|
|
51
|
+
return {
|
|
52
|
+
accept: 'text/event-stream',
|
|
53
|
+
...buildJSONHeaders(accessToken, defaultHeaders, appEnv),
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
function maskHeaders(headers) {
|
|
57
|
+
return {
|
|
58
|
+
...headers,
|
|
59
|
+
...(headers['access-token'] ? { 'access-token': '***' } : {}),
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
async function postAIPlatformJSON(gatewayOrigin, path, body, options = {}) {
|
|
63
|
+
const controller = new AbortController();
|
|
64
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
|
65
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
66
|
+
const appEnv = options.appEnv ?? getAIPlatformAppEnv();
|
|
67
|
+
const headers = buildJSONHeaders(options.accessToken, options.defaultHeaders ?? {}, appEnv);
|
|
68
|
+
const url = `${gatewayOrigin}${path}`;
|
|
69
|
+
console.log(`[AI Platform] POST ${url}`);
|
|
70
|
+
console.log('[AI Platform] Headers:', maskHeaders(headers));
|
|
71
|
+
console.log('[AI Platform] Body:', JSON.stringify(body).slice(0, 500));
|
|
72
|
+
try {
|
|
73
|
+
const response = await fetch(url, {
|
|
74
|
+
method: 'POST',
|
|
75
|
+
headers,
|
|
76
|
+
body: JSON.stringify(body),
|
|
77
|
+
signal: controller.signal,
|
|
78
|
+
});
|
|
79
|
+
const text = await response.text();
|
|
80
|
+
if (!response.ok) {
|
|
81
|
+
throw new Error(`HTTP Error: ${response.status} ${response.statusText}, x-tt-logid: ${response.headers.get('x-tt-logid') || 'N/A'}`);
|
|
82
|
+
}
|
|
83
|
+
return (text ? JSON.parse(text) : null);
|
|
84
|
+
}
|
|
85
|
+
catch (error) {
|
|
86
|
+
console.error('[AI Platform Error]', error);
|
|
87
|
+
throw error;
|
|
88
|
+
}
|
|
89
|
+
finally {
|
|
90
|
+
clearTimeout(timer);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
async function postMiniProgramModelPermission(body, options) {
|
|
94
|
+
const controller = new AbortController();
|
|
95
|
+
const timeoutMs = options?.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
|
96
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
97
|
+
const headers = {
|
|
98
|
+
'content-type': 'application/json',
|
|
99
|
+
...(options?.logid ? { 'x-tt-logid': options.logid } : {}),
|
|
100
|
+
...(options?.defaultHeaders ?? {}),
|
|
101
|
+
};
|
|
102
|
+
const url = `${PERMISSION_ORIGIN}/api/ai_platform_permission/mini_program/check_model_permission`;
|
|
103
|
+
console.log(`[AI Platform Permission] POST ${url}`);
|
|
104
|
+
console.log('[AI Platform Permission] Headers:', headers);
|
|
105
|
+
console.log('[AI Platform Permission] Body:', JSON.stringify(body));
|
|
106
|
+
try {
|
|
107
|
+
const response = await fetch(url, {
|
|
108
|
+
method: 'POST',
|
|
109
|
+
headers,
|
|
110
|
+
body: JSON.stringify(body),
|
|
111
|
+
signal: controller.signal,
|
|
112
|
+
});
|
|
113
|
+
const text = await response.text();
|
|
114
|
+
if (!response.ok) {
|
|
115
|
+
throw new Error(`HTTP Error: ${response.status} ${response.statusText}, x-tt-logid: ${response.headers.get('x-tt-logid') || 'N/A'}`);
|
|
116
|
+
}
|
|
117
|
+
return (text ? JSON.parse(text) : {});
|
|
118
|
+
}
|
|
119
|
+
catch (error) {
|
|
120
|
+
console.error('[AI Platform Permission Error]', error);
|
|
121
|
+
throw error;
|
|
122
|
+
}
|
|
123
|
+
finally {
|
|
124
|
+
clearTimeout(timer);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
async function* parseSSEStream(stream) {
|
|
128
|
+
const reader = stream.getReader();
|
|
129
|
+
const decoder = new TextDecoder();
|
|
130
|
+
let buffer = '';
|
|
131
|
+
while (true) {
|
|
132
|
+
const { done, value } = await reader.read();
|
|
133
|
+
if (done) {
|
|
134
|
+
break;
|
|
135
|
+
}
|
|
136
|
+
buffer += decoder.decode(value, { stream: true });
|
|
137
|
+
const frames = splitSSEChunks(buffer);
|
|
138
|
+
buffer = frames.rest;
|
|
139
|
+
for (const frame of frames.items) {
|
|
140
|
+
const event = toSSEEvent(frame);
|
|
141
|
+
if (event) {
|
|
142
|
+
yield event;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
if (buffer.trim()) {
|
|
147
|
+
const event = toSSEEvent(buffer);
|
|
148
|
+
if (event) {
|
|
149
|
+
yield event;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
async function* streamAIPlatform(gatewayOrigin, path, body, options = {}) {
|
|
154
|
+
const controller = new AbortController();
|
|
155
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_STREAM_TIMEOUT_MS;
|
|
156
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
157
|
+
const appEnv = options.appEnv ?? getAIPlatformAppEnv();
|
|
158
|
+
const headers = buildStreamHeaders(options.accessToken, options.defaultHeaders ?? {}, appEnv);
|
|
159
|
+
const url = `${gatewayOrigin}${path}`;
|
|
160
|
+
console.log(`[AI Platform Stream] POST ${url}`);
|
|
161
|
+
console.log('[AI Platform Stream] Headers:', maskHeaders(headers));
|
|
162
|
+
console.log('[AI Platform Stream] Body:', JSON.stringify(body).slice(0, 500));
|
|
163
|
+
try {
|
|
164
|
+
const response = await fetch(url, {
|
|
165
|
+
method: 'POST',
|
|
166
|
+
headers,
|
|
167
|
+
body: JSON.stringify(body),
|
|
168
|
+
signal: controller.signal,
|
|
169
|
+
});
|
|
170
|
+
if (!response.ok || !response.body) {
|
|
171
|
+
throw new Error(`HTTP Error: ${response.status} ${response.statusText}, x-tt-logid: ${response.headers.get('x-tt-logid') || 'N/A'}`);
|
|
172
|
+
}
|
|
173
|
+
for await (const event of parseSSEStream(response.body)) {
|
|
174
|
+
yield event;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
catch (error) {
|
|
178
|
+
console.error('[AI Platform Stream Error]', error);
|
|
179
|
+
throw error;
|
|
180
|
+
}
|
|
181
|
+
finally {
|
|
182
|
+
clearTimeout(timer);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
function splitSSEChunks(buffer) {
|
|
186
|
+
const items = [];
|
|
187
|
+
let rest = buffer;
|
|
188
|
+
while (true) {
|
|
189
|
+
const match = rest.match(/\r?\n\r?\n/);
|
|
190
|
+
if (!match || match.index === undefined) {
|
|
191
|
+
break;
|
|
192
|
+
}
|
|
193
|
+
items.push(rest.slice(0, match.index));
|
|
194
|
+
rest = rest.slice(match.index + match[0].length);
|
|
195
|
+
}
|
|
196
|
+
return { items, rest };
|
|
197
|
+
}
|
|
198
|
+
function toSSEEvent(frame) {
|
|
199
|
+
const event = { event: 'message', data: '' };
|
|
200
|
+
for (const line of frame.replace(/\r\n/g, '\n').split('\n')) {
|
|
201
|
+
if (line.startsWith('id:')) {
|
|
202
|
+
event.id = line.slice(3).trim();
|
|
203
|
+
}
|
|
204
|
+
else if (line.startsWith('event:')) {
|
|
205
|
+
event.event = line.slice(6).trim();
|
|
206
|
+
}
|
|
207
|
+
else if (line.startsWith('data:')) {
|
|
208
|
+
event.data += `${line.slice(5).trim()}\n`;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
event.data = event.data.trimEnd();
|
|
212
|
+
if (!event.data && !event.id) {
|
|
213
|
+
return null;
|
|
214
|
+
}
|
|
215
|
+
if (event.data === '[DONE]') {
|
|
216
|
+
event.payload = null;
|
|
217
|
+
return event;
|
|
218
|
+
}
|
|
219
|
+
try {
|
|
220
|
+
event.payload = JSON.parse(event.data);
|
|
221
|
+
}
|
|
222
|
+
catch {
|
|
223
|
+
event.payload = null;
|
|
224
|
+
}
|
|
225
|
+
return event;
|
|
226
|
+
}
|
|
227
|
+
exports.AI_PLATFORM_DEFAULT_REQUEST_TIMEOUT_MS = DEFAULT_REQUEST_TIMEOUT_MS;
|
|
228
|
+
exports.AI_PLATFORM_DEFAULT_IMAGE_TIMEOUT_MS = DEFAULT_IMAGE_TIMEOUT_MS;
|
|
229
|
+
exports.AI_PLATFORM_DEFAULT_STREAM_TIMEOUT_MS = DEFAULT_STREAM_TIMEOUT_MS;
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { AIPlatformLLMClient, generate, generateImage, generateVideo, queryVideoTask, waitVideoTask, streamGenerate, } from './client';
|
|
2
|
+
export { AI_PLATFORM_DEFAULT_REQUEST_TIMEOUT_MS, AI_PLATFORM_DEFAULT_IMAGE_TIMEOUT_MS, AI_PLATFORM_DEFAULT_STREAM_TIMEOUT_MS, createAIPlatformClientOptions, getAIPlatformAppEnv, getAIPlatformGatewayOrigin, parseSSEStream, postAIPlatformJSON, streamAIPlatform, } from './core';
|
|
3
|
+
export { assertMiniProgramModelPermission, checkMiniProgramModelPermission, getMiniProgramModelPermissionStatus, } from './permission';
|
|
4
|
+
export type { Role, ContentPart, ToolCall, Message, ModelParams, StreamGenerateRequest, GenerateMessage, GenerateModelParams, GenerateRequest, GenerateImageRequest, GenerateVideoRequest, QueryVideoTaskRequest, AIPlatformUsage, AIPlatformMessageEventPayload, AIPlatformEvent, AIPlatformOpenAPIResponse, GenerateResponseData, GenerateImageResponseData, GenerateVideoResponseData, QueryVideoTaskResponseData, CheckMiniProgramModelPermissionRequest, CheckMiniProgramModelPermissionData, CheckMiniProgramModelPermissionResponse, AIPlatformLLMClientOptions, AIPlatformCallOptions, } from './types';
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getMiniProgramModelPermissionStatus = exports.checkMiniProgramModelPermission = exports.assertMiniProgramModelPermission = exports.streamAIPlatform = exports.postAIPlatformJSON = exports.parseSSEStream = exports.getAIPlatformGatewayOrigin = exports.getAIPlatformAppEnv = exports.createAIPlatformClientOptions = exports.AI_PLATFORM_DEFAULT_STREAM_TIMEOUT_MS = exports.AI_PLATFORM_DEFAULT_IMAGE_TIMEOUT_MS = exports.AI_PLATFORM_DEFAULT_REQUEST_TIMEOUT_MS = exports.streamGenerate = exports.waitVideoTask = exports.queryVideoTask = exports.generateVideo = exports.generateImage = exports.generate = exports.AIPlatformLLMClient = void 0;
|
|
4
|
+
var client_1 = require("./client");
|
|
5
|
+
Object.defineProperty(exports, "AIPlatformLLMClient", { enumerable: true, get: function () { return client_1.AIPlatformLLMClient; } });
|
|
6
|
+
Object.defineProperty(exports, "generate", { enumerable: true, get: function () { return client_1.generate; } });
|
|
7
|
+
Object.defineProperty(exports, "generateImage", { enumerable: true, get: function () { return client_1.generateImage; } });
|
|
8
|
+
Object.defineProperty(exports, "generateVideo", { enumerable: true, get: function () { return client_1.generateVideo; } });
|
|
9
|
+
Object.defineProperty(exports, "queryVideoTask", { enumerable: true, get: function () { return client_1.queryVideoTask; } });
|
|
10
|
+
Object.defineProperty(exports, "waitVideoTask", { enumerable: true, get: function () { return client_1.waitVideoTask; } });
|
|
11
|
+
Object.defineProperty(exports, "streamGenerate", { enumerable: true, get: function () { return client_1.streamGenerate; } });
|
|
12
|
+
var core_1 = require("./core");
|
|
13
|
+
Object.defineProperty(exports, "AI_PLATFORM_DEFAULT_REQUEST_TIMEOUT_MS", { enumerable: true, get: function () { return core_1.AI_PLATFORM_DEFAULT_REQUEST_TIMEOUT_MS; } });
|
|
14
|
+
Object.defineProperty(exports, "AI_PLATFORM_DEFAULT_IMAGE_TIMEOUT_MS", { enumerable: true, get: function () { return core_1.AI_PLATFORM_DEFAULT_IMAGE_TIMEOUT_MS; } });
|
|
15
|
+
Object.defineProperty(exports, "AI_PLATFORM_DEFAULT_STREAM_TIMEOUT_MS", { enumerable: true, get: function () { return core_1.AI_PLATFORM_DEFAULT_STREAM_TIMEOUT_MS; } });
|
|
16
|
+
Object.defineProperty(exports, "createAIPlatformClientOptions", { enumerable: true, get: function () { return core_1.createAIPlatformClientOptions; } });
|
|
17
|
+
Object.defineProperty(exports, "getAIPlatformAppEnv", { enumerable: true, get: function () { return core_1.getAIPlatformAppEnv; } });
|
|
18
|
+
Object.defineProperty(exports, "getAIPlatformGatewayOrigin", { enumerable: true, get: function () { return core_1.getAIPlatformGatewayOrigin; } });
|
|
19
|
+
Object.defineProperty(exports, "parseSSEStream", { enumerable: true, get: function () { return core_1.parseSSEStream; } });
|
|
20
|
+
Object.defineProperty(exports, "postAIPlatformJSON", { enumerable: true, get: function () { return core_1.postAIPlatformJSON; } });
|
|
21
|
+
Object.defineProperty(exports, "streamAIPlatform", { enumerable: true, get: function () { return core_1.streamAIPlatform; } });
|
|
22
|
+
var permission_1 = require("./permission");
|
|
23
|
+
Object.defineProperty(exports, "assertMiniProgramModelPermission", { enumerable: true, get: function () { return permission_1.assertMiniProgramModelPermission; } });
|
|
24
|
+
Object.defineProperty(exports, "checkMiniProgramModelPermission", { enumerable: true, get: function () { return permission_1.checkMiniProgramModelPermission; } });
|
|
25
|
+
Object.defineProperty(exports, "getMiniProgramModelPermissionStatus", { enumerable: true, get: function () { return permission_1.getMiniProgramModelPermissionStatus; } });
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { AIPlatformCallOptions, CheckMiniProgramModelPermissionRequest, CheckMiniProgramModelPermissionResponse } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* 判断小程序是否有目标模型权限。
|
|
4
|
+
* 这里保留原始响应,避免在未知响应结构上做过度假设。
|
|
5
|
+
*/
|
|
6
|
+
export declare function checkMiniProgramModelPermission(req: CheckMiniProgramModelPermissionRequest, options?: AIPlatformCallOptions): Promise<CheckMiniProgramModelPermissionResponse>;
|
|
7
|
+
/**
|
|
8
|
+
* 基于常见布尔字段做轻量归一化。
|
|
9
|
+
* 如果接口未返回这些字段,则返回 null,让上层自行读取原始响应。
|
|
10
|
+
*/
|
|
11
|
+
export declare function getMiniProgramModelPermissionStatus(response: CheckMiniProgramModelPermissionResponse): boolean | null;
|
|
12
|
+
/**
|
|
13
|
+
* 权限明确为 false 时抛错;响应里没有标准布尔字段时,只返回原始响应。
|
|
14
|
+
*/
|
|
15
|
+
export declare function assertMiniProgramModelPermission(req: CheckMiniProgramModelPermissionRequest, options?: AIPlatformCallOptions): Promise<CheckMiniProgramModelPermissionResponse>;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.checkMiniProgramModelPermission = checkMiniProgramModelPermission;
|
|
4
|
+
exports.getMiniProgramModelPermissionStatus = getMiniProgramModelPermissionStatus;
|
|
5
|
+
exports.assertMiniProgramModelPermission = assertMiniProgramModelPermission;
|
|
6
|
+
const core_1 = require("./core");
|
|
7
|
+
/**
|
|
8
|
+
* 判断小程序是否有目标模型权限。
|
|
9
|
+
* 这里保留原始响应,避免在未知响应结构上做过度假设。
|
|
10
|
+
*/
|
|
11
|
+
async function checkMiniProgramModelPermission(req, options) {
|
|
12
|
+
return (0, core_1.postMiniProgramModelPermission)(req, options);
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* 基于常见布尔字段做轻量归一化。
|
|
16
|
+
* 如果接口未返回这些字段,则返回 null,让上层自行读取原始响应。
|
|
17
|
+
*/
|
|
18
|
+
function getMiniProgramModelPermissionStatus(response) {
|
|
19
|
+
const candidates = [
|
|
20
|
+
response.data?.allowed,
|
|
21
|
+
response.data?.allow,
|
|
22
|
+
response.data?.has_permission,
|
|
23
|
+
response.data?.can_use,
|
|
24
|
+
];
|
|
25
|
+
for (const candidate of candidates) {
|
|
26
|
+
if (typeof candidate === 'boolean') {
|
|
27
|
+
return candidate;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* 权限明确为 false 时抛错;响应里没有标准布尔字段时,只返回原始响应。
|
|
34
|
+
*/
|
|
35
|
+
async function assertMiniProgramModelPermission(req, options) {
|
|
36
|
+
const response = await checkMiniProgramModelPermission(req, options);
|
|
37
|
+
const granted = getMiniProgramModelPermissionStatus(response);
|
|
38
|
+
if (granted === false) {
|
|
39
|
+
throw new Error(response.message ||
|
|
40
|
+
response.err_msg ||
|
|
41
|
+
'mini_program_model_permission_denied');
|
|
42
|
+
}
|
|
43
|
+
return response;
|
|
44
|
+
}
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
export type Role = 'system' | 'user' | 'assistant' | 'tool';
|
|
2
|
+
export interface ContentPart {
|
|
3
|
+
type: number;
|
|
4
|
+
text?: string;
|
|
5
|
+
url?: string;
|
|
6
|
+
data?: string;
|
|
7
|
+
mime_type?: string;
|
|
8
|
+
}
|
|
9
|
+
export interface ToolCall {
|
|
10
|
+
id: string;
|
|
11
|
+
name: string;
|
|
12
|
+
arguments: string;
|
|
13
|
+
}
|
|
14
|
+
export interface Message {
|
|
15
|
+
role: Role;
|
|
16
|
+
content?: string;
|
|
17
|
+
parts?: ContentPart[];
|
|
18
|
+
tool_calls?: ToolCall[];
|
|
19
|
+
tool_call_id?: string;
|
|
20
|
+
tool_name?: string;
|
|
21
|
+
reasoning?: string;
|
|
22
|
+
}
|
|
23
|
+
export interface ModelParams {
|
|
24
|
+
/**
|
|
25
|
+
* 文本模型常见建议范围为 `0-1`。
|
|
26
|
+
* 对 Doubao Seed 1.6 这类偏思考任务,通常更适合 `0-0.4`。
|
|
27
|
+
*/
|
|
28
|
+
temperature?: number;
|
|
29
|
+
/**
|
|
30
|
+
* 常见回答长度预算字段。
|
|
31
|
+
* 以 Doubao Seed 1.6 系列为例,常见预算可到 `32K`。
|
|
32
|
+
* 如果后续引入 `max_completion_tokens` 之类的思考型预算字段,不要和它同时传。
|
|
33
|
+
*/
|
|
34
|
+
max_tokens?: number;
|
|
35
|
+
top_p?: number;
|
|
36
|
+
stop?: string[];
|
|
37
|
+
frequency_penalty?: number;
|
|
38
|
+
presence_penalty?: number;
|
|
39
|
+
thinking_type?: string;
|
|
40
|
+
reasoning_effort?: string;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* 流式文本生成请求。
|
|
44
|
+
*
|
|
45
|
+
* 说明:
|
|
46
|
+
* - 当前联调文本模型示例主要是 `Doubao-Seed-1.6-back` 一类 Seed 1.6 系列。
|
|
47
|
+
* - 常见核心字段是 `messages`、`model_tenant`、`model_key`、`params`。
|
|
48
|
+
* - `messages[].role` 常见值为 `system`、`user`、`assistant`。
|
|
49
|
+
* - 旧 `messages` 结构更适合纯文本,不适合承载复杂多模态输入。
|
|
50
|
+
* - 参数限制和默认值应按 `model_key` 决定,不要把统一字段当成所有模型通用能力。
|
|
51
|
+
*/
|
|
52
|
+
export interface StreamGenerateRequest {
|
|
53
|
+
messages: Message[];
|
|
54
|
+
model_tenant: string;
|
|
55
|
+
model_key: string;
|
|
56
|
+
params?: ModelParams;
|
|
57
|
+
tools?: Array<{
|
|
58
|
+
name: string;
|
|
59
|
+
description: string;
|
|
60
|
+
parameters: string;
|
|
61
|
+
}>;
|
|
62
|
+
extra?: Record<string, string>;
|
|
63
|
+
}
|
|
64
|
+
export interface GenerateMessage {
|
|
65
|
+
Role: Role;
|
|
66
|
+
Content?: string;
|
|
67
|
+
Parts?: Array<{
|
|
68
|
+
Type: number;
|
|
69
|
+
Text?: string;
|
|
70
|
+
Url?: string;
|
|
71
|
+
Data?: string;
|
|
72
|
+
MimeType?: string;
|
|
73
|
+
}>;
|
|
74
|
+
ToolCalls?: Array<{
|
|
75
|
+
ID: string;
|
|
76
|
+
Name: string;
|
|
77
|
+
Arguments: string;
|
|
78
|
+
}>;
|
|
79
|
+
ToolCallID?: string;
|
|
80
|
+
ToolName?: string;
|
|
81
|
+
Reasoning?: string;
|
|
82
|
+
}
|
|
83
|
+
export interface GenerateModelParams {
|
|
84
|
+
Temperature?: number;
|
|
85
|
+
MaxTokens?: number;
|
|
86
|
+
TopP?: number;
|
|
87
|
+
Stop?: string[];
|
|
88
|
+
FrequencyPenalty?: number;
|
|
89
|
+
PresencePenalty?: number;
|
|
90
|
+
ThinkingType?: string;
|
|
91
|
+
ReasoningEffort?: string;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* 非流式文本生成请求。
|
|
95
|
+
*
|
|
96
|
+
* 说明:
|
|
97
|
+
* - 当前网关字段仍保持 PascalCase,例如 `Messages`、`ModelTenant`、`ModelKey`、`Params`。
|
|
98
|
+
* - 不同 `ModelKey` 的可用参数范围不同,业务侧应按模型选择默认值和校验策略。
|
|
99
|
+
*/
|
|
100
|
+
export interface GenerateRequest {
|
|
101
|
+
Messages: GenerateMessage[];
|
|
102
|
+
ModelTenant: string;
|
|
103
|
+
ModelKey: string;
|
|
104
|
+
Params?: GenerateModelParams;
|
|
105
|
+
Tools?: Array<{
|
|
106
|
+
Name: string;
|
|
107
|
+
Description: string;
|
|
108
|
+
Parameters: string;
|
|
109
|
+
}>;
|
|
110
|
+
Extra?: Record<string, string>;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* 图片生成请求。
|
|
114
|
+
*
|
|
115
|
+
* 注意:
|
|
116
|
+
* - 不要假设每个图片模型都支持这里的所有字段。
|
|
117
|
+
* - 参数校验和默认值应按 `ModelKey` 决定。
|
|
118
|
+
* - 统一的请求类型只表示网关接受这些字段名,不表示每个模型都支持这些字段。
|
|
119
|
+
*
|
|
120
|
+
* 当前已知模型约束摘要:
|
|
121
|
+
* - `glm-image`
|
|
122
|
+
* - `Prompt` 和 `ReferenceImages` 至少一个非空
|
|
123
|
+
* - `Size` 优先 `1k` / `2k` / `4k`
|
|
124
|
+
* - `ImageNum` 建议先按 `1` 使用
|
|
125
|
+
* - 不要依赖 `FastMode` / `KeepRatio` 一定生效
|
|
126
|
+
* - `doubao-seedream-4-0-*`
|
|
127
|
+
* - `Prompt` 必填
|
|
128
|
+
* - 参考图最多 10 张,JPG/PNG,单图不超过 10 MB
|
|
129
|
+
* - `Size` 使用 `1K` / `2K` / `4K` 或 `widthxheight`,不要混用
|
|
130
|
+
* - `ImageNum` 不是简单平铺 `n`,多图能力要按模型侧顺序生图语义理解
|
|
131
|
+
* - `gpt-image-1`
|
|
132
|
+
* - 不要套用 Seedream 或 GLM 的限制
|
|
133
|
+
* - prompt 长度不超过 `32000`
|
|
134
|
+
* - 图片数量 `1-10`
|
|
135
|
+
* - size 常见值为 `1024x1024` / `1536x1024` / `1024x1536` / `auto`
|
|
136
|
+
*/
|
|
137
|
+
export interface GenerateImageRequest {
|
|
138
|
+
/**
|
|
139
|
+
* 图片模型通常需要该字段。
|
|
140
|
+
* `glm-image` 场景下可与 `ReferenceImages` 二选一,但二者不能同时为空。
|
|
141
|
+
*/
|
|
142
|
+
Prompt: string;
|
|
143
|
+
ModelTenant: string;
|
|
144
|
+
ModelKey: string;
|
|
145
|
+
Source: number;
|
|
146
|
+
/**
|
|
147
|
+
* 字段语义依模型而变:
|
|
148
|
+
* - `glm-image`:可选图片输入
|
|
149
|
+
* - Seedream 4.0:最多 10 张参考图
|
|
150
|
+
* - 视频模型不属于这个请求类型
|
|
151
|
+
*/
|
|
152
|
+
ReferenceImages?: string[];
|
|
153
|
+
/**
|
|
154
|
+
* 不是所有模型共用的一套枚举。
|
|
155
|
+
* 示例:
|
|
156
|
+
* - `glm-image`:`1k` / `2k` / `4k`
|
|
157
|
+
* - Seedream 4.0:`1K` / `2K` / `4K` 或 `widthxheight`
|
|
158
|
+
*/
|
|
159
|
+
Size?: string;
|
|
160
|
+
Ratio?: string;
|
|
161
|
+
/**
|
|
162
|
+
* 不要假设所有图片模型都支持多图输出。
|
|
163
|
+
* Seedream 4.0 的多图能力也不是简单的平铺 `n`。
|
|
164
|
+
*/
|
|
165
|
+
ImageNum?: number;
|
|
166
|
+
/** `false` 通常表示不加 AI 水印,但最终语义仍取决于具体模型。 */
|
|
167
|
+
Watermark?: boolean;
|
|
168
|
+
/** 不要把它当成所有模型都稳定支持的能力。 */
|
|
169
|
+
FastMode?: boolean;
|
|
170
|
+
/** 不要把它当成所有模型都稳定支持的能力。 */
|
|
171
|
+
KeepRatio?: boolean;
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* 视频生成请求。
|
|
175
|
+
*
|
|
176
|
+
* 注意:
|
|
177
|
+
* - `ReferenceImages` 是强场景相关字段,在不同 `ModelKey` 下可能表示首帧、尾帧或参考图。
|
|
178
|
+
* - 参数校验应按 `ModelKey` 决定,不要只按字段名做统一判断。
|
|
179
|
+
* - 统一请求类型不表示所有视频模型都支持同一组图生视频能力。
|
|
180
|
+
*
|
|
181
|
+
* 当前已知模型约束摘要:
|
|
182
|
+
* - `doubao-seedance-1-0-pro-250528`
|
|
183
|
+
* - 支持 T2V、首帧 I2V、首尾帧 I2V、参考图模式
|
|
184
|
+
* - `Prompt` 不超过 `500` 字符
|
|
185
|
+
* - `Duration` 常见范围 `2-12`
|
|
186
|
+
* - `Resolution` 常见值 `480p` / `720p` / `1080p`
|
|
187
|
+
* - 首帧、首尾帧、参考图模式不要混用
|
|
188
|
+
* - `seedance-1-0-pro-fast-*`
|
|
189
|
+
* - 仅支持 T2V 和首帧 I2V
|
|
190
|
+
* - 最多 1 张首帧图
|
|
191
|
+
* - 不支持首尾帧和通用参考图模式
|
|
192
|
+
* - `seedance-1-0-lite-t2v-*`
|
|
193
|
+
* - 仅支持 T2V,不要传图片输入
|
|
194
|
+
* - `seedance-1-0-lite-i2v-*`
|
|
195
|
+
* - 支持首帧、首尾帧、参考图模式,但图片 role 需要严格按场景校验
|
|
196
|
+
*/
|
|
197
|
+
export interface GenerateVideoRequest {
|
|
198
|
+
/** 通常必填,且往往受模型侧 prompt 长度限制。 */
|
|
199
|
+
Prompt: string;
|
|
200
|
+
ModelTenant: string;
|
|
201
|
+
ModelKey: string;
|
|
202
|
+
Source: number;
|
|
203
|
+
/**
|
|
204
|
+
* 示例:
|
|
205
|
+
* - Seedance Pro:首帧、首尾帧或参考图
|
|
206
|
+
* - Seedance Pro Fast:最多 1 张首帧图
|
|
207
|
+
* - Lite T2V:不应传图片输入
|
|
208
|
+
*/
|
|
209
|
+
ReferenceImages?: string[];
|
|
210
|
+
/** 常见值为 `480p`、`720p`、`1080p`;网关示例里也可能出现大写写法。 */
|
|
211
|
+
Resolution?: string;
|
|
212
|
+
Ratio?: string;
|
|
213
|
+
/** Seedance 系列常见约束为 `2-12` 秒整数。 */
|
|
214
|
+
Duration?: number;
|
|
215
|
+
/** Seedance 系列常见值为 `24`;部分场景建议严格校验。 */
|
|
216
|
+
FPS?: number;
|
|
217
|
+
Watermark?: boolean;
|
|
218
|
+
Style?: string;
|
|
219
|
+
}
|
|
220
|
+
export interface QueryVideoTaskRequest {
|
|
221
|
+
ModelTenant: string;
|
|
222
|
+
ModelKey: string;
|
|
223
|
+
TaskId: string;
|
|
224
|
+
}
|
|
225
|
+
export interface AIPlatformUsage {
|
|
226
|
+
prompt_tokens: number;
|
|
227
|
+
completion_tokens: number;
|
|
228
|
+
total_tokens: number;
|
|
229
|
+
reasoning_tokens?: number;
|
|
230
|
+
cached_prompt_tokens?: number;
|
|
231
|
+
}
|
|
232
|
+
export interface AIPlatformMessageEventPayload {
|
|
233
|
+
event?: Message;
|
|
234
|
+
usage?: AIPlatformUsage;
|
|
235
|
+
finish_reason?: string;
|
|
236
|
+
error?: string;
|
|
237
|
+
index?: number;
|
|
238
|
+
}
|
|
239
|
+
export interface AIPlatformEvent {
|
|
240
|
+
id?: string;
|
|
241
|
+
event: string;
|
|
242
|
+
data: string;
|
|
243
|
+
payload?: AIPlatformMessageEventPayload | null;
|
|
244
|
+
}
|
|
245
|
+
export interface AIPlatformOpenAPIResponse<T> {
|
|
246
|
+
err_no: number;
|
|
247
|
+
err_msg: string;
|
|
248
|
+
log_id?: string;
|
|
249
|
+
data: T;
|
|
250
|
+
}
|
|
251
|
+
export interface GenerateResponseData {
|
|
252
|
+
Message?: GenerateMessage;
|
|
253
|
+
Usage?: {
|
|
254
|
+
PromptTokens?: number;
|
|
255
|
+
CompletionTokens?: number;
|
|
256
|
+
TotalTokens?: number;
|
|
257
|
+
ReasoningTokens?: number;
|
|
258
|
+
CachedPromptTokens?: number;
|
|
259
|
+
};
|
|
260
|
+
FinishReason?: string;
|
|
261
|
+
[key: string]: unknown;
|
|
262
|
+
}
|
|
263
|
+
export interface GenerateImageResponseData {
|
|
264
|
+
ImageUrls?: string[];
|
|
265
|
+
[key: string]: unknown;
|
|
266
|
+
}
|
|
267
|
+
export interface GenerateVideoResponseData {
|
|
268
|
+
TaskId?: string;
|
|
269
|
+
[key: string]: unknown;
|
|
270
|
+
}
|
|
271
|
+
export interface QueryVideoTaskResponseData {
|
|
272
|
+
Status?: string;
|
|
273
|
+
TaskId?: string;
|
|
274
|
+
ErrorMessage?: string;
|
|
275
|
+
VideoUrls?: string[];
|
|
276
|
+
LastFrameUrl?: string;
|
|
277
|
+
[key: string]: unknown;
|
|
278
|
+
}
|
|
279
|
+
export interface CheckMiniProgramModelPermissionRequest {
|
|
280
|
+
micro_appid: string;
|
|
281
|
+
model_tenant: string;
|
|
282
|
+
model_key: string;
|
|
283
|
+
}
|
|
284
|
+
export interface CheckMiniProgramModelPermissionData {
|
|
285
|
+
allowed?: boolean;
|
|
286
|
+
allow?: boolean;
|
|
287
|
+
has_permission?: boolean;
|
|
288
|
+
can_use?: boolean;
|
|
289
|
+
[key: string]: unknown;
|
|
290
|
+
}
|
|
291
|
+
export interface CheckMiniProgramModelPermissionResponse {
|
|
292
|
+
code?: number | string;
|
|
293
|
+
message?: string;
|
|
294
|
+
err_no?: number;
|
|
295
|
+
err_msg?: string;
|
|
296
|
+
data?: CheckMiniProgramModelPermissionData;
|
|
297
|
+
[key: string]: unknown;
|
|
298
|
+
}
|
|
299
|
+
export interface AIPlatformLLMClientOptions {
|
|
300
|
+
accessToken?: string;
|
|
301
|
+
timeoutMs?: number;
|
|
302
|
+
imageTimeoutMs?: number;
|
|
303
|
+
streamTimeoutMs?: number;
|
|
304
|
+
defaultHeaders?: Record<string, string>;
|
|
305
|
+
gatewayOrigin?: string;
|
|
306
|
+
}
|
|
307
|
+
export interface AIPlatformCallOptions {
|
|
308
|
+
accessToken?: string;
|
|
309
|
+
logid?: string;
|
|
310
|
+
timeoutMs?: number;
|
|
311
|
+
defaultHeaders?: Record<string, string>;
|
|
312
|
+
}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import type { AuthCallOptions, AuthResponse } from './core';
|
|
2
|
+
export interface GetUserAccessTokenParams {
|
|
3
|
+
/** 应用唯一标识,即开放平台应用的 client_key。 */
|
|
4
|
+
client_key: string;
|
|
5
|
+
/** 应用密钥,即 client_key 对应的 client_secret。 */
|
|
6
|
+
client_secret: string;
|
|
7
|
+
/**
|
|
8
|
+
* 用户授权码。
|
|
9
|
+
* 授权码有效期 10 分钟,且只能使用一次。
|
|
10
|
+
*/
|
|
11
|
+
code: string;
|
|
12
|
+
}
|
|
13
|
+
export interface UserAccessTokenData {
|
|
14
|
+
/** 用户授权调用凭证 access_token。 */
|
|
15
|
+
access_token: string;
|
|
16
|
+
/** 人机校验信息,正常情况下通常为空字符串。 */
|
|
17
|
+
captcha?: string;
|
|
18
|
+
/** 错误详情页跳转地址,正常情况下通常为空字符串。 */
|
|
19
|
+
desc_url?: string;
|
|
20
|
+
/** 错误描述;成功时通常为空字符串。 */
|
|
21
|
+
description?: string;
|
|
22
|
+
/** 业务错误码,0 表示成功。 */
|
|
23
|
+
error_code: number;
|
|
24
|
+
/** access_token 有效期,单位秒。文档说明默认 15 天。 */
|
|
25
|
+
expires_in: number;
|
|
26
|
+
/** 抖音开放平台侧日志 ID,可用于排查问题。 */
|
|
27
|
+
log_id?: string;
|
|
28
|
+
/** 用户在当前应用下的唯一标识 open_id。 */
|
|
29
|
+
open_id: string;
|
|
30
|
+
/** refresh_token 剩余有效期,单位秒。文档说明默认 30 天。 */
|
|
31
|
+
refresh_expires_in: number;
|
|
32
|
+
/** 用于刷新 access_token 的 refresh_token。 */
|
|
33
|
+
refresh_token: string;
|
|
34
|
+
/** 已授予权限范围,例如 user_info。 */
|
|
35
|
+
scope?: string;
|
|
36
|
+
}
|
|
37
|
+
export interface RefreshUserAccessTokenParams {
|
|
38
|
+
/** 应用唯一标识,即开放平台应用的 client_key。 */
|
|
39
|
+
client_key: string;
|
|
40
|
+
/** 通过 /oauth/access_token/ 获取到的 refresh_token。 */
|
|
41
|
+
refresh_token: string;
|
|
42
|
+
}
|
|
43
|
+
export interface RefreshUserAccessTokenData {
|
|
44
|
+
/** 刷新后的 access_token。 */
|
|
45
|
+
access_token: string;
|
|
46
|
+
/** 错误描述;成功时通常为空字符串。 */
|
|
47
|
+
description?: string;
|
|
48
|
+
/** 业务错误码,0 表示成功。 */
|
|
49
|
+
error_code: number;
|
|
50
|
+
/** access_token 有效期,单位秒;文档示例里该字段是字符串。 */
|
|
51
|
+
expires_in: number | string;
|
|
52
|
+
/** 用户在当前应用下的唯一标识 open_id。 */
|
|
53
|
+
open_id: string;
|
|
54
|
+
/** refresh_token 剩余有效期,单位秒;文档示例里该字段是字符串。 */
|
|
55
|
+
refresh_expires_in: number | string;
|
|
56
|
+
/** 刷新后返回的 refresh_token;其有效期保持不变。 */
|
|
57
|
+
refresh_token: string;
|
|
58
|
+
/** 已授予权限范围,例如 user_info。 */
|
|
59
|
+
scope?: string;
|
|
60
|
+
}
|
|
61
|
+
export interface RefreshUserTokenParams {
|
|
62
|
+
/** 应用唯一标识,即开放平台应用的 client_key。 */
|
|
63
|
+
client_key: string;
|
|
64
|
+
/** 通过 /oauth/access_token/ 获取到的 refresh_token。 */
|
|
65
|
+
refresh_token: string;
|
|
66
|
+
}
|
|
67
|
+
export interface RefreshUserTokenData {
|
|
68
|
+
/** 错误描述;成功时通常为空字符串。 */
|
|
69
|
+
description?: string;
|
|
70
|
+
/** 业务错误码,0 表示成功。 */
|
|
71
|
+
error_code: number;
|
|
72
|
+
/** 新 refresh_token 的有效期,单位秒;文档示例里该字段是字符串。 */
|
|
73
|
+
expires_in: number | string;
|
|
74
|
+
/** 新的 refresh_token。旧 refresh_token 会立即失效。 */
|
|
75
|
+
refresh_token: string;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* 获取用户授权调用凭证。
|
|
79
|
+
* 对应 POST /oauth/access_token/
|
|
80
|
+
*
|
|
81
|
+
* 文档:
|
|
82
|
+
* https://developer.open-douyin.com/docs/resource/zh-CN/mini-app/develop/server/basic-abilities/interface-request-credential/user-authorization/get-user-access-token
|
|
83
|
+
*
|
|
84
|
+
* 请求说明:
|
|
85
|
+
* - content-type 固定为 application/x-www-form-urlencoded,由 core.ts 自动注入
|
|
86
|
+
* - grant_type 固定为 authorization_code,由 SDK 自动填充
|
|
87
|
+
*
|
|
88
|
+
* 返回错误码:
|
|
89
|
+
* - 0: 成功
|
|
90
|
+
* - 10001: 系统异常
|
|
91
|
+
* - 10002: 参数错误,通常是参数漏传或请求格式不正确
|
|
92
|
+
* - 10003: 密钥错误,请确认 client_secret 是否正确
|
|
93
|
+
* - 10007: 授权码过期,code 只有 10 分钟有效期且只能使用一次
|
|
94
|
+
* - 10013: client_key 或 client_secret 错误
|
|
95
|
+
* - 10014: client_key 不匹配,获取授权码和换 token 使用的 client_key 不一致
|
|
96
|
+
*/
|
|
97
|
+
export declare function getUserAccessToken(params: GetUserAccessTokenParams, options?: AuthCallOptions): Promise<AuthResponse<UserAccessTokenData>>;
|
|
98
|
+
/**
|
|
99
|
+
* 刷新 access_token。
|
|
100
|
+
* 对应 POST /oauth/refresh_token/
|
|
101
|
+
*
|
|
102
|
+
* 文档:
|
|
103
|
+
* https://developer.open-douyin.com/docs/resource/zh-CN/mini-app/develop/server/basic-abilities/interface-request-credential/user-authorization/refresh-user-access-token
|
|
104
|
+
*
|
|
105
|
+
* 请求说明:
|
|
106
|
+
* - content-type 固定为 application/x-www-form-urlencoded,由 core.ts 自动注入
|
|
107
|
+
* - grant_type 固定为 refresh_token,由 SDK 自动填充
|
|
108
|
+
* - access_token 默认有效期 15 天;refresh_token 默认有效期 30 天
|
|
109
|
+
* - refresh_token 过期后,需要重新引导用户授权
|
|
110
|
+
*
|
|
111
|
+
* 返回错误码:
|
|
112
|
+
* - 0: 成功
|
|
113
|
+
* - 10001: 系统错误
|
|
114
|
+
* - 10002: 参数错误
|
|
115
|
+
* - 10005: 参数缺失
|
|
116
|
+
* - 10010: refresh_token 已过期,需要用户重新授权
|
|
117
|
+
*/
|
|
118
|
+
export declare function refreshUserAccessToken(params: RefreshUserAccessTokenParams, options?: AuthCallOptions): Promise<AuthResponse<RefreshUserAccessTokenData>>;
|
|
119
|
+
/**
|
|
120
|
+
* 轮换 / 续期 refresh_token。
|
|
121
|
+
* 对应 POST /oauth/renew_refresh_token/
|
|
122
|
+
*
|
|
123
|
+
* 文档:
|
|
124
|
+
* https://developer.open-douyin.com/docs/resource/zh-CN/mini-app/develop/server/basic-abilities/interface-request-credential/user-authorization/refresh-user-token
|
|
125
|
+
*
|
|
126
|
+
* 请求说明:
|
|
127
|
+
* - content-type 固定为 application/x-www-form-urlencoded,由 core.ts 自动注入
|
|
128
|
+
* - 调用成功后旧 refresh_token 失效,并返回新的 refresh_token
|
|
129
|
+
* - 新 refresh_token 有效期 30 天
|
|
130
|
+
* - 最多只能刷新 5 次;超过后需要用户重新授权
|
|
131
|
+
*
|
|
132
|
+
* 返回错误码:
|
|
133
|
+
* - 0: 成功
|
|
134
|
+
* - 10004: 权限不足,请申请 renew_refresh_token 权限
|
|
135
|
+
* - 10005: 缺少参数,请检查 client_key 和 refresh_token
|
|
136
|
+
* - 10010: refresh_token 过期,需要用户重新授权
|
|
137
|
+
* - 10020: 超过刷新次数限制,需要用户重新授权
|
|
138
|
+
*/
|
|
139
|
+
export declare function refreshUserToken(params: RefreshUserTokenParams, options?: AuthCallOptions): Promise<AuthResponse<RefreshUserTokenData>>;
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getUserAccessToken = getUserAccessToken;
|
|
4
|
+
exports.refreshUserAccessToken = refreshUserAccessToken;
|
|
5
|
+
exports.refreshUserToken = refreshUserToken;
|
|
6
|
+
const core_1 = require("./core");
|
|
7
|
+
/**
|
|
8
|
+
* 获取用户授权调用凭证。
|
|
9
|
+
* 对应 POST /oauth/access_token/
|
|
10
|
+
*
|
|
11
|
+
* 文档:
|
|
12
|
+
* https://developer.open-douyin.com/docs/resource/zh-CN/mini-app/develop/server/basic-abilities/interface-request-credential/user-authorization/get-user-access-token
|
|
13
|
+
*
|
|
14
|
+
* 请求说明:
|
|
15
|
+
* - content-type 固定为 application/x-www-form-urlencoded,由 core.ts 自动注入
|
|
16
|
+
* - grant_type 固定为 authorization_code,由 SDK 自动填充
|
|
17
|
+
*
|
|
18
|
+
* 返回错误码:
|
|
19
|
+
* - 0: 成功
|
|
20
|
+
* - 10001: 系统异常
|
|
21
|
+
* - 10002: 参数错误,通常是参数漏传或请求格式不正确
|
|
22
|
+
* - 10003: 密钥错误,请确认 client_secret 是否正确
|
|
23
|
+
* - 10007: 授权码过期,code 只有 10 分钟有效期且只能使用一次
|
|
24
|
+
* - 10013: client_key 或 client_secret 错误
|
|
25
|
+
* - 10014: client_key 不匹配,获取授权码和换 token 使用的 client_key 不一致
|
|
26
|
+
*/
|
|
27
|
+
async function getUserAccessToken(params, options) {
|
|
28
|
+
return (0, core_1.callAuthAPI)({
|
|
29
|
+
path: '/oauth/access_token/',
|
|
30
|
+
method: 'POST',
|
|
31
|
+
body: {
|
|
32
|
+
client_key: params.client_key,
|
|
33
|
+
client_secret: params.client_secret,
|
|
34
|
+
code: params.code,
|
|
35
|
+
grant_type: 'authorization_code',
|
|
36
|
+
},
|
|
37
|
+
}, options);
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* 刷新 access_token。
|
|
41
|
+
* 对应 POST /oauth/refresh_token/
|
|
42
|
+
*
|
|
43
|
+
* 文档:
|
|
44
|
+
* https://developer.open-douyin.com/docs/resource/zh-CN/mini-app/develop/server/basic-abilities/interface-request-credential/user-authorization/refresh-user-access-token
|
|
45
|
+
*
|
|
46
|
+
* 请求说明:
|
|
47
|
+
* - content-type 固定为 application/x-www-form-urlencoded,由 core.ts 自动注入
|
|
48
|
+
* - grant_type 固定为 refresh_token,由 SDK 自动填充
|
|
49
|
+
* - access_token 默认有效期 15 天;refresh_token 默认有效期 30 天
|
|
50
|
+
* - refresh_token 过期后,需要重新引导用户授权
|
|
51
|
+
*
|
|
52
|
+
* 返回错误码:
|
|
53
|
+
* - 0: 成功
|
|
54
|
+
* - 10001: 系统错误
|
|
55
|
+
* - 10002: 参数错误
|
|
56
|
+
* - 10005: 参数缺失
|
|
57
|
+
* - 10010: refresh_token 已过期,需要用户重新授权
|
|
58
|
+
*/
|
|
59
|
+
async function refreshUserAccessToken(params, options) {
|
|
60
|
+
return (0, core_1.callAuthAPI)({
|
|
61
|
+
path: '/oauth/refresh_token/',
|
|
62
|
+
method: 'POST',
|
|
63
|
+
body: {
|
|
64
|
+
client_key: params.client_key,
|
|
65
|
+
refresh_token: params.refresh_token,
|
|
66
|
+
grant_type: 'refresh_token',
|
|
67
|
+
},
|
|
68
|
+
}, options);
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* 轮换 / 续期 refresh_token。
|
|
72
|
+
* 对应 POST /oauth/renew_refresh_token/
|
|
73
|
+
*
|
|
74
|
+
* 文档:
|
|
75
|
+
* https://developer.open-douyin.com/docs/resource/zh-CN/mini-app/develop/server/basic-abilities/interface-request-credential/user-authorization/refresh-user-token
|
|
76
|
+
*
|
|
77
|
+
* 请求说明:
|
|
78
|
+
* - content-type 固定为 application/x-www-form-urlencoded,由 core.ts 自动注入
|
|
79
|
+
* - 调用成功后旧 refresh_token 失效,并返回新的 refresh_token
|
|
80
|
+
* - 新 refresh_token 有效期 30 天
|
|
81
|
+
* - 最多只能刷新 5 次;超过后需要用户重新授权
|
|
82
|
+
*
|
|
83
|
+
* 返回错误码:
|
|
84
|
+
* - 0: 成功
|
|
85
|
+
* - 10004: 权限不足,请申请 renew_refresh_token 权限
|
|
86
|
+
* - 10005: 缺少参数,请检查 client_key 和 refresh_token
|
|
87
|
+
* - 10010: refresh_token 过期,需要用户重新授权
|
|
88
|
+
* - 10020: 超过刷新次数限制,需要用户重新授权
|
|
89
|
+
*/
|
|
90
|
+
async function refreshUserToken(params, options) {
|
|
91
|
+
return (0, core_1.callAuthAPI)({
|
|
92
|
+
path: '/oauth/renew_refresh_token/',
|
|
93
|
+
method: 'POST',
|
|
94
|
+
body: {
|
|
95
|
+
client_key: params.client_key,
|
|
96
|
+
refresh_token: params.refresh_token,
|
|
97
|
+
},
|
|
98
|
+
}, options);
|
|
99
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export interface AuthCallParams {
|
|
2
|
+
path: string;
|
|
3
|
+
method?: 'POST';
|
|
4
|
+
body: URLSearchParams | Record<string, string | number | boolean | undefined>;
|
|
5
|
+
domain?: string;
|
|
6
|
+
}
|
|
7
|
+
export interface AuthCallOptions {
|
|
8
|
+
logid?: string;
|
|
9
|
+
timeoutMs?: number;
|
|
10
|
+
}
|
|
11
|
+
export interface AuthResponse<T> {
|
|
12
|
+
message: string;
|
|
13
|
+
data: T;
|
|
14
|
+
}
|
|
15
|
+
export declare function callAuthAPI<T>(params: AuthCallParams, options?: AuthCallOptions): Promise<AuthResponse<T>>;
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.callAuthAPI = callAuthAPI;
|
|
4
|
+
function buildUrl(path, domain = 'open.douyin.com') {
|
|
5
|
+
return new URL(`https://${domain}${path}`).toString();
|
|
6
|
+
}
|
|
7
|
+
function toFormBody(body) {
|
|
8
|
+
if (body instanceof URLSearchParams) {
|
|
9
|
+
return body;
|
|
10
|
+
}
|
|
11
|
+
const params = new URLSearchParams();
|
|
12
|
+
Object.entries(body).forEach(([key, value]) => {
|
|
13
|
+
if (value !== undefined) {
|
|
14
|
+
params.set(key, String(value));
|
|
15
|
+
}
|
|
16
|
+
});
|
|
17
|
+
return params;
|
|
18
|
+
}
|
|
19
|
+
function maskBody(body) {
|
|
20
|
+
const clone = new URLSearchParams(body);
|
|
21
|
+
if (clone.has('client_secret')) {
|
|
22
|
+
clone.set('client_secret', '***');
|
|
23
|
+
}
|
|
24
|
+
return clone.toString();
|
|
25
|
+
}
|
|
26
|
+
function buildHeaders(options) {
|
|
27
|
+
const headers = {
|
|
28
|
+
'Content-Type': 'application/x-www-form-urlencoded',
|
|
29
|
+
};
|
|
30
|
+
if (options?.logid) {
|
|
31
|
+
headers['x-tt-logid'] = options.logid;
|
|
32
|
+
}
|
|
33
|
+
return headers;
|
|
34
|
+
}
|
|
35
|
+
async function callAuthAPI(params, options) {
|
|
36
|
+
const { path, method = 'POST', body, domain = 'open.douyin.com' } = params;
|
|
37
|
+
const requestBody = toFormBody(body);
|
|
38
|
+
const url = buildUrl(path, domain);
|
|
39
|
+
const headers = buildHeaders(options);
|
|
40
|
+
const controller = new AbortController();
|
|
41
|
+
const timeoutMs = options?.timeoutMs ?? 60000;
|
|
42
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
43
|
+
console.log(`[Auth] ${method} ${url}`);
|
|
44
|
+
console.log('[Auth] Headers:', headers);
|
|
45
|
+
console.log('[Auth] Body:', maskBody(requestBody));
|
|
46
|
+
try {
|
|
47
|
+
const response = await fetch(url, {
|
|
48
|
+
method,
|
|
49
|
+
headers,
|
|
50
|
+
body: requestBody.toString(),
|
|
51
|
+
signal: controller.signal,
|
|
52
|
+
});
|
|
53
|
+
const rawData = await response.json();
|
|
54
|
+
if (!response.ok) {
|
|
55
|
+
throw new Error(`HTTP Error: ${response.status} ${response.statusText}, x-tt-logid: ${response.headers.get('x-tt-logid') || 'N/A'}`);
|
|
56
|
+
}
|
|
57
|
+
if (!rawData || typeof rawData !== 'object' || !('data' in rawData) || !('message' in rawData)) {
|
|
58
|
+
throw new Error(`Invalid auth response, x-tt-logid: ${response.headers.get('x-tt-logid') || 'N/A'}`);
|
|
59
|
+
}
|
|
60
|
+
const result = rawData;
|
|
61
|
+
const resultData = result.data;
|
|
62
|
+
const errorCode = typeof resultData?.error_code === 'number' ? resultData.error_code : 0;
|
|
63
|
+
if (errorCode !== 0) {
|
|
64
|
+
throw new Error(`Auth Error: ${String(resultData?.description || result.message)} (${String(errorCode)}), x-tt-logid: ${response.headers.get('x-tt-logid') || resultData?.log_id || 'N/A'}`);
|
|
65
|
+
}
|
|
66
|
+
console.log('[Auth] Response:', JSON.stringify(result).slice(0, 500));
|
|
67
|
+
return result;
|
|
68
|
+
}
|
|
69
|
+
catch (error) {
|
|
70
|
+
console.error('[Auth Error]', error);
|
|
71
|
+
throw error;
|
|
72
|
+
}
|
|
73
|
+
finally {
|
|
74
|
+
clearTimeout(timer);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { callAuthAPI } from './core';
|
|
2
|
+
export type { AuthCallParams, AuthCallOptions, AuthResponse } from './core';
|
|
3
|
+
export { getUserAccessToken, refreshUserAccessToken, refreshUserToken, } from './access-token';
|
|
4
|
+
export type { GetUserAccessTokenParams, UserAccessTokenData, RefreshUserAccessTokenParams, RefreshUserAccessTokenData, RefreshUserTokenParams, RefreshUserTokenData, } from './access-token';
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.refreshUserToken = exports.refreshUserAccessToken = exports.getUserAccessToken = exports.callAuthAPI = void 0;
|
|
4
|
+
var core_1 = require("./core");
|
|
5
|
+
Object.defineProperty(exports, "callAuthAPI", { enumerable: true, get: function () { return core_1.callAuthAPI; } });
|
|
6
|
+
var access_token_1 = require("./access-token");
|
|
7
|
+
Object.defineProperty(exports, "getUserAccessToken", { enumerable: true, get: function () { return access_token_1.getUserAccessToken; } });
|
|
8
|
+
Object.defineProperty(exports, "refreshUserAccessToken", { enumerable: true, get: function () { return access_token_1.refreshUserAccessToken; } });
|
|
9
|
+
Object.defineProperty(exports, "refreshUserToken", { enumerable: true, get: function () { return access_token_1.refreshUserToken; } });
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -33,7 +33,9 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
33
33
|
};
|
|
34
34
|
})();
|
|
35
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
-
exports.openapi = void 0;
|
|
36
|
+
exports.ai_platform_llm = exports.auth = exports.openapi = void 0;
|
|
37
37
|
// AI Coding SDK — 聚合入口
|
|
38
38
|
// 按模块导入:import { callOpenAPI } from '@open-dy/ai_coding_sdk/openapi'
|
|
39
39
|
exports.openapi = __importStar(require("./openapi"));
|
|
40
|
+
exports.auth = __importStar(require("./auth"));
|
|
41
|
+
exports.ai_platform_llm = __importStar(require("./ai_platform_llm"));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-dy/ai_coding_sdk",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.12",
|
|
4
4
|
"description": "AI Coding SDK — 抖音开放平台 OpenAPI 客户端与工具集",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -85,6 +85,22 @@
|
|
|
85
85
|
"./openapi/platform/*": {
|
|
86
86
|
"types": "./dist/openapi/platform/*.d.ts",
|
|
87
87
|
"default": "./dist/openapi/platform/*.js"
|
|
88
|
+
},
|
|
89
|
+
"./auth": {
|
|
90
|
+
"types": "./dist/auth/index.d.ts",
|
|
91
|
+
"default": "./dist/auth/index.js"
|
|
92
|
+
},
|
|
93
|
+
"./auth/*": {
|
|
94
|
+
"types": "./dist/auth/*.d.ts",
|
|
95
|
+
"default": "./dist/auth/*.js"
|
|
96
|
+
},
|
|
97
|
+
"./ai_platform_llm": {
|
|
98
|
+
"types": "./dist/ai_platform_llm/index.d.ts",
|
|
99
|
+
"default": "./dist/ai_platform_llm/index.js"
|
|
100
|
+
},
|
|
101
|
+
"./ai_platform_llm/*": {
|
|
102
|
+
"types": "./dist/ai_platform_llm/*.d.ts",
|
|
103
|
+
"default": "./dist/ai_platform_llm/*.js"
|
|
88
104
|
}
|
|
89
105
|
}
|
|
90
106
|
}
|