mindcraft/src/models/qwen.js

124 lines
4.9 KiB
JavaScript
Raw Normal View History

2024-10-29 02:51:04 +08:00
// This code uses Dashscope and HTTP to ensure the latest support for the Qwen model.
// Qwen is also compatible with the OpenAI API format, and the base URL to be configured is: "https://dashscope.aliyuncs.com/compatible-mode/v1".
https://dashscope.aliyuncs.com/compatible-mode/v1
2024-10-29 02:51:04 +08:00
2024-10-28 13:41:20 +08:00
import { getKey } from '../utils/keys.js';
2024-10-28 13:29:16 +08:00
export class Qwen {
2024-10-29 02:51:04 +08:00
constructor(modelName, url) {
// Initialize model name and API URL
this.modelName = modelName;
2024-10-28 19:06:51 +08:00
this.url = url || 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation';
2024-10-29 02:51:04 +08:00
this.apiKey = getKey('QWEN_API_KEY'); // Get API key from utility function
2024-10-28 13:29:16 +08:00
}
2024-10-29 02:51:04 +08:00
async sendRequest(turns, systemMessage, stopSeq = '***', retryCount = 0) {
// Limit retry attempts to avoid infinite recursion
if (retryCount > 5) {
console.error('Maximum retry attempts reached.');
return 'Error: Too many retry attempts.';
}
// Build request data
2024-10-28 19:06:51 +08:00
const data = {
2024-10-29 02:51:04 +08:00
model: this.modelName || 'qwen-plus',
2024-10-28 19:06:51 +08:00
input: { messages: [{ role: 'system', content: systemMessage }, ...turns] },
2024-10-29 02:51:04 +08:00
parameters: { result_format: 'message', stop: stopSeq },
2024-10-28 19:06:51 +08:00
};
2024-10-29 02:51:04 +08:00
// Add default user message if all messages are 'system' role
if (turns.every((msg) => msg.role === 'system')) {
data.input.messages.push({ role: 'user', content: 'hello' });
}
2024-10-28 13:29:16 +08:00
2024-10-29 02:51:04 +08:00
// Validate data format before sending request
if (!data.model || !data.input || !data.input.messages || !data.parameters) {
console.error('Invalid request data format:', data);
throw new Error('Invalid request data format.');
}
2024-10-28 19:06:51 +08:00
2024-10-29 02:51:04 +08:00
try {
// Send request to API
const response = await this._makeHttpRequest(this.url, data);
const choice = response?.output?.choices?.[0];
2024-10-28 13:50:39 +08:00
2024-10-29 02:51:04 +08:00
// Retry request if response is incomplete due to length limit
if (choice?.finish_reason === 'length' && turns.length > 0) {
return this.sendRequest(turns.slice(1), systemMessage, stopSeq, retryCount + 1);
2024-10-28 13:29:16 +08:00
}
2024-10-28 19:06:51 +08:00
2024-10-29 02:51:04 +08:00
// Return response content or default message
2024-10-28 19:06:51 +08:00
return choice?.message?.content || 'No content received.';
2024-10-28 13:50:39 +08:00
} catch (err) {
2024-10-29 02:51:04 +08:00
// Error handling, log error and return error message
2024-10-28 13:50:39 +08:00
console.error('Error occurred:', err);
2024-10-29 02:51:04 +08:00
return 'An error occurred, please try again.';
2024-10-28 13:29:16 +08:00
}
}
async embed(text) {
2024-10-29 02:51:04 +08:00
// Validate embedding input
2024-10-28 13:29:16 +08:00
if (!text || typeof text !== 'string') {
2024-10-29 02:51:04 +08:00
console.error('Invalid embedding input: text must be a non-empty string.');
return 'Invalid embedding input: text must be a non-empty string.';
2024-10-28 13:29:16 +08:00
}
2024-10-28 13:50:39 +08:00
2024-10-29 02:51:04 +08:00
// Build embedding request data
2024-10-28 13:29:16 +08:00
const data = {
model: 'text-embedding-v2',
2024-10-28 13:50:39 +08:00
input: { texts: [text] },
2024-10-28 19:06:51 +08:00
parameters: { text_type: 'query' },
};
2024-10-29 02:51:04 +08:00
// Validate data format before sending request
if (!data.model || !data.input || !data.input.texts || !data.parameters) {
console.error('Invalid embedding request data format:', data);
throw new Error('Invalid embedding request data format.');
}
try {
// Send embedding request to API
const response = await this._makeHttpRequest(this.url, data);
const embedding = response?.output?.embeddings?.[0]?.embedding;
return embedding || 'No embedding result received.';
} catch (err) {
// Error handling, log error and return error message
console.error('Error occurred:', err);
return 'An error occurred, please try again.';
}
}
async _makeHttpRequest(url, data) {
// Set request headers, including authorization and content type
2024-10-28 19:06:51 +08:00
const headers = {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json',
2024-10-28 13:29:16 +08:00
};
2024-10-29 02:51:04 +08:00
// Send HTTP POST request to API
const response = await fetch(url, {
method: 'POST',
headers,
body: JSON.stringify(data),
});
2024-10-28 19:06:51 +08:00
2024-10-29 02:51:04 +08:00
// Check response status code, throw error if not successful
if (!response.ok) {
const errorText = await response.text();
console.error(`Request failed, status code ${response.status}: ${response.statusText}`);
console.error('Error response content:', errorText);
throw new Error(`Request failed, status code ${response.status}: ${response.statusText}`);
}
2024-10-28 19:06:51 +08:00
2024-10-29 02:51:04 +08:00
// Parse and return response JSON
const responseText = await response.text();
try {
return JSON.parse(responseText);
2024-10-28 13:29:16 +08:00
} catch (err) {
2024-10-29 02:51:04 +08:00
console.error('Failed to parse response JSON:', err);
throw new Error('Invalid response JSON format.');
2024-10-28 13:29:16 +08:00
}
}
}