aquanet-bot-lib
Version:
A library for building aquaculture chatbots with LLM integration
99 lines (98 loc) • 4.07 kB
JavaScript
import axios from 'axios';
export class DeepSeekProvider {
constructor(config) {
Object.defineProperty(this, "apiKey", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "model", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "defaultParams", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
this.apiKey = config.apiKey;
this.model = config.model;
this.defaultParams = config.defaultParams || {};
}
async generateResponse(input) {
try {
const response = await axios.post('https://api.deepseek.com/v1/chat/completions', {
model: this.model,
messages: [
...(input.systemPrompt ? [{ role: 'system', content: input.systemPrompt }] : []),
{ role: 'user', content: input.prompt }
],
temperature: input.temperature ?? this.defaultParams?.temperature ?? 0.7,
max_tokens: input.maxTokens ?? this.defaultParams?.maxTokens ?? 2000,
top_p: input.topP ?? this.defaultParams?.topP ?? 1,
frequency_penalty: input.frequencyPenalty ?? this.defaultParams?.frequencyPenalty ?? 0,
presence_penalty: input.presencePenalty ?? this.defaultParams?.presencePenalty ?? 0
}, {
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
}
});
return {
content: response.data.choices[0].message.content,
usage: response.data.usage
};
}
catch (error) {
if (axios.isAxiosError(error)) {
throw new Error(`DeepSeek API error: ${error.response?.data?.error?.message || error.message}`);
}
throw error;
}
}
async *generateStreamResponse(input) {
try {
const response = await axios.post('https://api.deepseek.com/v1/chat/completions', {
model: this.model,
messages: [
...(input.systemPrompt ? [{ role: 'system', content: input.systemPrompt }] : []),
{ role: 'user', content: input.prompt }
],
temperature: input.temperature ?? this.defaultParams?.temperature ?? 0.7,
max_tokens: input.maxTokens ?? this.defaultParams?.maxTokens ?? 2000,
top_p: input.topP ?? this.defaultParams?.topP ?? 1,
frequency_penalty: input.frequencyPenalty ?? this.defaultParams?.frequencyPenalty ?? 0,
presence_penalty: input.presencePenalty ?? this.defaultParams?.presencePenalty ?? 0,
stream: true
}, {
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
},
responseType: 'stream'
});
for await (const chunk of response.data) {
const lines = chunk
.toString()
.split('\n')
.filter((line) => line.trim() !== '' && line.startsWith('data: '));
for (const line of lines) {
const data = JSON.parse(line.replace('data: ', ''));
if (data.choices[0].delta?.content) {
yield data.choices[0].delta.content;
}
}
}
}
catch (error) {
if (axios.isAxiosError(error)) {
throw new Error(`DeepSeek API error: ${error.response?.data?.error?.message || error.message}`);
}
throw error;
}
}
}