feat(api): 添加 token 过期自动刷新和 count_tokens 端点支持
在 API 服务器中添加对 count_tokens 请求的处理,返回不支持的提示。 在 Kiro 客户端的内容生成方法中增加 token 过期检查,在即将过期时 自动刷新认证凭证,避免请求失败。
This commit is contained in:
parent
db3c63ffe4
commit
06eacb0419
2 changed files with 24 additions and 0 deletions
|
|
@ -628,6 +628,16 @@ function createRequestHandler(config) {
|
|||
}));
|
||||
}
|
||||
|
||||
// Ignore count_tokens requests
|
||||
if (path.includes('/count_tokens')) {
|
||||
console.log(`[Server] Ignoring count_tokens request: ${path}`);
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' });
|
||||
return res.end(JSON.stringify({
|
||||
tokens: 0,
|
||||
message: 'Token counting is not supported'
|
||||
}));
|
||||
}
|
||||
|
||||
if (!isAuthorized(req, requestUrl, currentConfig.REQUIRED_API_KEY)) {
|
||||
res.writeHead(401, { 'Content-Type': 'application/json' });
|
||||
return res.end(JSON.stringify({ error: { message: 'Unauthorized: API key is invalid or missing.' } }));
|
||||
|
|
|
|||
|
|
@ -859,6 +859,13 @@ async initializeAuth(forceRefresh = false) {
|
|||
|
||||
async generateContent(model, requestBody) {
|
||||
if (!this.isInitialized) await this.initialize();
|
||||
|
||||
// 检查 token 是否即将过期,如果是则先刷新
|
||||
if (this.isExpiryDateNear()) {
|
||||
console.log('[Kiro] Token is near expiry, refreshing before generateContent request...');
|
||||
await this.initializeAuth(true);
|
||||
}
|
||||
|
||||
const finalModel = MODEL_MAPPING[model] ? model : this.modelName;
|
||||
console.log(`[Kiro] Calling generateContent with model: ${finalModel}`);
|
||||
const response = await this.callApi('', finalModel, requestBody);
|
||||
|
|
@ -886,6 +893,13 @@ async initializeAuth(forceRefresh = false) {
|
|||
// 重构2: generateContentStream 调用新的普通async函数
|
||||
async * generateContentStream(model, requestBody) {
|
||||
if (!this.isInitialized) await this.initialize();
|
||||
|
||||
// 检查 token 是否即将过期,如果是则先刷新
|
||||
if (this.isExpiryDateNear()) {
|
||||
console.log('[Kiro] Token is near expiry, refreshing before generateContentStream request...');
|
||||
await this.initializeAuth(true);
|
||||
}
|
||||
|
||||
const finalModel = MODEL_MAPPING[model] ? model : this.modelName;
|
||||
console.log(`[Kiro] Calling generateContentStream with model: ${finalModel}`);
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue