一键导入
deepseek-proxy
DeepSeek API expert - specialized AI models for coding, reasoning, and chat with competitive pricing.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
DeepSeek API expert - specialized AI models for coding, reasoning, and chat with competitive pricing.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
基于 SOC 职业分类
WCAG 2.2 accessibility audit and remediation guidance for frontend code, UI reviews, keyboard/focus testing, ARIA usage, contrast, forms, and regression checks.
Local-first personal AI agent gateway architecture for Windows with messaging integrations, tool execution, and real-time streaming.
Anthropic Claude API expert - master Messages API requests, responses, streaming, tool use, prompt caching, and current Claude 4-family model practices.
REST and HTTP API design with OpenAPI 3.1, resource modeling, versioning, pagination, idempotency, errors, validation, auth boundaries, and production compatibility.
Expert in converting between AI provider APIs - Anthropic, Gemini, OpenRouter, Groq, Mistral, DeepSeek, and NVIDIA NIM.
Comprehensive authentication system for AI agent gateway with JWT tokens, session management, and multi-factor authentication.
| name | deepseek-proxy |
| type | skill |
| version | 1.0.0 |
| description | DeepSeek API expert - specialized AI models for coding, reasoning, and chat with competitive pricing. |
| author | skillregistry |
| license | MIT |
| agents | ["cursor","claude-code","copilot","gemini-cli","codex"] |
| categories | ["backend","ai-ml","architecture"] |
| tags | ["ai","api","deepseek","coding","reasoning","llm","proxy"] |
Master the DeepSeek API for specialized AI models focused on coding, reasoning, and chat applications. DeepSeek offers competitive pricing with high-quality outputs, particularly for code generation tasks.
import fetch from 'node-fetch';
const response = await fetch('https://api.deepseek.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.DEEPSEEK_KEY}`
},
body: JSON.stringify({
model: 'deepseek-chat',
messages: [{ role: 'user', content: 'Hello!' }]
})
});
const data = await response.json();
console.log(data.choices[0].message.content);
curl https://api.deepseek.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $DEEPSEEK_KEY" \
-d '{
"model": "deepseek-v4-flash",
"messages": [{"role": "user", "content": "Write a Python function to sort a list"}]
}'
DeepSeek's official API docs announced that the legacy deepseek-chat and deepseek-reasoner aliases are scheduled for removal on 2026-07-24. New gateway integrations should target the current V4 model IDs and keep model discovery or configuration outside code.
| Model | Context Window | Use Case | Price (Input) | Price (Output) | Notes |
|---|---|---|---|---|---|
| deepseek-chat | 32,768 | General chat | $0.0000014/tok | $0.0000028/tok | Latest chat model |
| deepseek-v4-flash | 32,768 | Code generation | $0.0000014/tok | $0.0000028/tok | Current non-thinking V4-compatible model; migrate before legacy aliases are removed |
https://api.deepseek.com/v1/chat/completionshttps://api.deepseek.com/v1/modelshttps://api.deepseek.com/v1/models/{model_id}{
"model": "deepseek-chat",
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello!"}
],
"max_tokens": 1024,
"temperature": 0.7,
"top_p": 0.9,
"stream": false
}
| Parameter | Type | Default | Description |
|---|---|---|---|
| model | string | required | Model ID |
| messages | array | required | Message history |
| max_tokens | number | inf | Max output tokens (max: 32768) |
| temperature | number | 1.0 | Randomness (0-2) |
| top_p | number | 1.0 | Nucleus sampling |
| top_k | number | null | Top-k sampling |
| stream | boolean | false | Enable streaming |
| stop | string/array | null | Stop sequences |
| presence_penalty | number | 0 | Repetition penalty |
| frequency_penalty | number | 0 | Frequency penalty |
| user | string | null | User identifier |
{
"id": "chatcmpl-123",
"object": "chat.completion",
"created": 1717000000,
"model": "deepseek-chat",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Hello! How can I help you today?"
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 25,
"completion_tokens": 10,
"total_tokens": 35
}
}
{
"id": "chatcmpl-123",
"object": "chat.completion.chunk",
"created": 1717000000,
"model": "deepseek-chat",
"choices": [
{
"index": 0,
"delta": {"content": "Hello"},
"finish_reason": null
}
]
}
stop - Normal completionlength - Hit max tokenscontent_filter - Blocked by content filterDeepSeek V4 Flash is specifically fine-tuned for:
DeepSeek Chat excels at:
DeepSeek offers some of the most competitive pricing:
import express from 'express';
import fetch from 'node-fetch';
const app = express();
app.use(express.json());
const DEEPSEEK_KEY = process.env.DEEPSEEK_KEY;
const DEEPSEEK_URL = 'https://api.deepseek.com/v1';
app.post('/v1/chat/completions', async (req, res) => {
try {
const response = await fetch(`${DEEPSEEK_URL}/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${DEEPSEEK_KEY}`
},
body: JSON.stringify(req.body)
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.message || 'DeepSeek error');
}
const data = await response.json();
res.json(data);
} catch (error: any) {
res.status(error.statusCode || 500).json({ error: error.message });
}
});
app.listen(3000);
const MODEL_ALIASES: Record<string, string> = {
'chat': 'deepseek-chat',
'coder': 'deepseek-v4-flash',
'code': 'deepseek-v4-flash',
'default': 'deepseek-chat'
};
app.post('/deepseek/:model/chat', async (req, res) => {
const { model } = req.params;
const actualModel = MODEL_ALIASES[model] || model;
const response = await fetch(`${DEEPSEEK_URL}/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${DEEPSEEK_KEY}`
},
body: JSON.stringify({
model: actualModel,
messages: req.body.messages,
max_tokens: req.body.max_tokens || 4096,
temperature: req.body.temperature || 0.7
})
});
const data = await response.json();
res.json({ ...data, model: actualModel });
});
app.post('/stream', async (req, res) => {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
const response = await fetch(`${DEEPSEEK_URL}/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${DEEPSEEK_KEY}`
},
body: JSON.stringify({
...req.body,
stream: true
})
});
const reader = response.body?.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader!.read();
if (done) break;
const chunk = decoder.decode(value);
if (chunk.includes('[DONE]')) break;
res.write(`data: ${chunk}\n\n`);
}
res.write('data: [DONE]\n\n');
res.end();
});
// Route to appropriate model based on task
app.post('/task/chat', async (req, res) => {
const { task, messages, ...rest } = req.body;
// Select model based on task
const modelMap: Record<string, string> = {
'code': 'deepseek-v4-flash',
'coding': 'deepseek-v4-flash',
'debug': 'deepseek-v4-flash',
'chat': 'deepseek-chat',
'general': 'deepseek-chat',
'reasoning': 'deepseek-chat',
'math': 'deepseek-chat'
};
const model = modelMap[task?.toLowerCase()] || 'deepseek-chat';
const response = await fetch(`${DEEPSEEK_URL}/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${DEEPSEEK_KEY}`
},
body: JSON.stringify({
model,
messages,
...rest
})
});
const data = await response.json();
res.json({ ...data, model_used: model });
});
{
"error": {
"message": "Invalid request format",
"type": "BadRequestError",
"param": null,
"code": null
}
}
{
"error": {
"message": "Invalid or expired API key",
"type": "AuthenticationError"
}
}
{
"error": {
"message": "Access denied",
"type": "PermissionError"
}
}
{
"error": {
"message": "Model not found",
"type": "NotFoundError"
}
}
{
"error": {
"message": "Rate limit exceeded",
"type": "RateLimitError"
}
}
{
"error": {
"message": "Internal server error",
"type": "InternalServerError"
}
}
function selectModel(task: string, quality: 'high' | 'standard' = 'standard'): string {
const modelMap: Record<string, Record<'high' | 'standard', string>> = {
code: {
high: 'deepseek-v4-flash',
standard: 'deepseek-v4-flash'
},
chat: {
high: 'deepseek-chat',
standard: 'deepseek-chat'
},
reasoning: {
high: 'deepseek-chat',
standard: 'deepseek-chat'
},
math: {
high: 'deepseek-chat',
standard: 'deepseek-chat'
}
};
return modelMap[task?.toLowerCase()]?.[quality] || 'deepseek-chat';
}
async function generateCode(prompt: string, language: string = 'python') {
const systemPrompt = `You are an expert ${language} developer. Write clean, well-commented, and efficient code.`;
const response = await fetch(`${DEEPSEEK_URL}/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${DEEPSEEK_KEY}`
},
body: JSON.stringify({
model: 'deepseek-v4-flash',
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: `Write ${language} code for: ${prompt}` }
],
temperature: 0.3 // Lower temperature for more deterministic code
})
});
const data = await response.json();
return data.choices[0].message.content;
}
async function reviewCode(code: string, language: string = 'python') {
const prompt = `Review the following ${language} code for:
1. Bugs and potential issues
2. Performance optimizations
3. Security vulnerabilities
4. Code quality improvements
5. Best practice violations
Code:
\`\`\`${language}
${code}
\`\`\``;
const response = await fetch(`${DEEPSEEK_URL}/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${DEEPSEEK_KEY}`
},
body: JSON.stringify({
model: 'deepseek-v4-flash',
messages: [
{ role: 'user', content: prompt }
],
temperature: 0.2
})
});
const data = await response.json();
return data.choices[0].message.content;
}
async function debugCode(code: string, error: string, language: string = 'python') {
const prompt = `The following ${language} code is producing an error:
Error:
${error}
Code:
\`\`\`${language}
${code}
\`\`\`
Please:
1. Identify the cause of the error
2. Explain why it's happening
3. Provide the fixed code
4. Suggest how to prevent this error in the future`;
const response = await fetch(`${DEEPSEEK_URL}/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${DEEPSEEK_KEY}`
},
body: JSON.stringify({
model: 'deepseek-v4-flash',
messages: [
{ role: 'user', content: prompt }
],
temperature: 0.2
})
});
const data = await response.json();
return data.choices[0].message.content;
}
async function withRetry(request: any, maxRetries = 3) {
let attempt = 0;
while (true) {
try {
const response = await fetch(`${DEEPSEEK_URL}/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${DEEPSEEK_KEY}`
},
body: JSON.stringify(request)
});
if (response.ok) {
return await response.json();
}
if (response.status !== 429 || attempt >= maxRetries) {
throw new Error(`DeepSeek error: ${response.status}`);
}
const retryAfter = Math.pow(2, attempt) * 1000;
await new Promise(resolve => setTimeout(resolve, retryAfter));
attempt++;
} catch (error) {
if (attempt >= maxRetries) {
throw error;
}
await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
attempt++;
}
}
}
import { Agent } from 'https';
const httpsAgent = new Agent({
keepAlive: true,
keepAliveMsecs: 60000,
maxSockets: 100,
maxFreeSockets: 50
});
const response = await fetch(`${DEEPSEEK_URL}/chat/completions`, {
agent: httpsAgent,
method: 'POST',
// ...
});
import NodeCache from 'node-cache';
const cache = new NodeCache({ stdTTL: 300 }); // 5 minute cache
async function cachedGenerate(request: any) {
const cacheKey = JSON.stringify(request);
const cached = cache.get(cacheKey);
if (cached) {
return cached;
}
const response = await fetch(`${DEEPSEEK_URL}/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${DEEPSEEK_KEY}`
},
body: JSON.stringify(request)
});
const data = await response.json();
cache.set(cacheKey, data);
return data;
}
class DeepSeekBatcher {
private queue: Array<{ request: any; resolve: Function; reject: Function }> = [];
private processing = false;
add(request: any) {
return new Promise((resolve, reject) => {
this.queue.push({ request, resolve, reject });
this.process();
});
}
async process() {
if (this.processing || this.queue.length < 3) return;
this.processing = true;
const batch = this.queue.splice(0, 3);
try {
const responses = await Promise.all(
batch.map(({ request }) =>
fetch(`${DEEPSEEK_URL}/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${DEEPSEEK_KEY}`
},
body: JSON.stringify(request)
}).then(r => r.json())
)
);
batch.forEach((item, i) => item.resolve(responses[i]));
} catch (error) {
batch.forEach(item => item.reject(error));
} finally {
this.processing = false;
}
}
}
import { describe, it, expect, vi } from 'vitest';
describe('DeepSeek Proxy', () => {
it('generates content', async () => {
global.fetch = vi.fn(() => Promise.resolve({
ok: true,
json: () => Promise.resolve({
id: 'chatcmpl-123',
object: 'chat.completion',
created: 1717000000,
model: 'deepseek-chat',
choices: [{
index: 0,
message: { role: 'assistant', content: 'Hello!' },
finish_reason: 'stop'
}],
usage: { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 }
})
}));
const response = await fetch(`${DEEPSEEK_URL}/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer test-key'
},
body: JSON.stringify({
model: 'deepseek-chat',
messages: [{ role: 'user', content: 'Hi' }]
})
});
const data = await response.json();
expect(data.choices[0].message.content).toBe('Hello!');
});
});
describe('Code Generation', () => {
it('generates valid Python code', async () => {
const response = await fetch(`${DEEPSEEK_URL}/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${DEEPSEEK_KEY}`
},
body: JSON.stringify({
model: 'deepseek-v4-flash',
messages: [
{
role: 'user',
content: 'Write a Python function to reverse a string'
}
],
temperature: 0.3
})
});
const data = await response.json();
const code = data.choices[0].message.content;
// Basic validation that it looks like code
expect(code).toContain('def');
expect(code).toContain('reverse');
expect(code).toContain(':');
expect(code).toContain('return');
});
});
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY dist ./dist
COPY .env ./
EXPOSE 3000
CMD ["node", "dist/index.js"]
version: '3.8'
services:
deepseek-proxy:
build: .
ports:
- "3000:3000"
environment:
- DEEPSEEK_KEY=${DEEPSEEK_KEY}
- PRIMARY_MODEL=deepseek-chat
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
interval: 30s
timeout: 10s
retries: 3
# Required
DEEPSEEK_KEY=...
# Optional
PRIMARY_MODEL=deepseek-chat
DEEPSEEK_URL=https://api.deepseek.com/v1
PORT=3000
LOG_LEVEL=info
MAX_TOKENS=4096
TIMEOUT=30000
import { createHistogram, createCounter, createGauge } from 'prom-client';
const requestLatency = createHistogram({
name: 'deepseek_request_latency_seconds',
help: 'Request latency in seconds',
labelNames: ['model'],
buckets: [0.1, 0.5, 1, 2, 5, 10]
});
const tokenUsage = createCounter({
name: 'deepseek_tokens_total',
help: 'Total tokens used',
labelNames: ['model', 'type']
});
const activeRequests = createGauge({
name: 'deepseek_active_requests',
help: 'Number of active requests',
labelNames: ['model']
});
app.use((req, res, next) => {
const start = process.hrtime.bigint();
const model = req.body.model || 'unknown';
activeRequests.labels(model).inc();
res.on('finish', () => {
const latency = Number(process.hrtime.bigint() - start) / 1e9;
requestLatency.labels(model).observe(latency);
activeRequests.labels(model).dec();
});
next();
});
app.post('/v1/chat/completions', async (req, res) => {
const response = await fetch(`${DEEPSEEK_URL}/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${DEEPSEEK_KEY}`
},
body: JSON.stringify(req.body)
});
const data = await response.json();
if (data.usage) {
tokenUsage.labels(req.body.model, 'input').inc(data.usage.prompt_tokens);
tokenUsage.labels(req.body.model, 'output').inc(data.usage.completion_tokens);
}
res.json(data);
});
import winston from 'winston';
const logger = winston.createLogger({
level: 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'deepseek-proxy.log' })
]
});
app.use((req, res, next) => {
const start = Date.now();
res.on('finish', () => {
logger.info({
timestamp: new Date().toISOString(),
method: req.method,
model: req.body.model,
status: res.statusCode,
latencyMs: Date.now() - start,
ip: req.ip
});
});
next();
});
Invalid API Key
Model Not Available
/v1/modelsRate Limit Exceeded
Context Window Exceeded
Code Generation Issues
# Enable verbose logging
DEBUG=deepseek:* node index.js
# Or log full requests
import fetch from 'node-fetch';
const originalFetch = global.fetch;
global.fetch = async (url: string, options: any) => {
if (url.includes('deepseek.com')) {
console.log('DeepSeek Request:', url, options);
}
const response = await originalFetch(url, options);
const cloned = response.clone();
const body = await cloned.json();
if (url.includes('deepseek.com')) {
console.log('DeepSeek Response:', body);
}
return response;
};
| Feature | DeepSeek | OpenAI | Anthropic | Groq | Mistral |
|---|---|---|---|---|---|
| Context Window | 32K | 16K-128K | 200K | 8K-123K | 8K-128K |
| Price (Input) | $0.0000014/tok | $0.00001-0.00003 | $0.000003-0.000015 | $0.0000008 | €0.00000025-0.000008 |
| Price (Output) | $0.0000028/tok | $0.00003-0.00006 | $0.000015 | $0.0000008 | €0.00000025-0.000024 |
| OpenAI Compatible | ✅ Yes | ✅ Yes | ❌ No | ✅ Yes | ✅ Yes |
| Function Calling | ❌ No | ✅ Yes | ✅ Beta | ❌ No | ✅ Yes |
| Embeddings | ❌ No | ✅ Yes | ❌ No | ❌ No | ✅ Yes |
| Multi-modal | ❌ No | ✅ Yes | ✅ Claude 3 | ❌ No | ❌ No |
| Coding Specialist | ✅ Yes | ❌ No | ❌ No | ❌ No | ❌ No |
| Reasoning | ✅ Good | ✅ Good | ✅ Excellent | ❌ Basic | ✅ Good |
| Strengths | Coding, Cost | Features, Ecosystem | Reasoning, Safety | Speed, Cost | Open-source |
async function complete(prompt: string, model: string = 'deepseek-chat') {
const response = await fetch('https://api.deepseek.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.DEEPSEEK_KEY}`
},
body: JSON.stringify({
model,
messages: [{ role: 'user', content: prompt }]
})
});
const data = await response.json();
return data.choices[0].message.content;
}
class DeepSeekCoder {
private model: string;
constructor(model: string = 'deepseek-v4-flash') {
this.model = model;
}
async generateCode(prompt: string, language: string = 'python') {
const systemPrompt = `You are an expert ${language} developer. Write clean, efficient, and well-documented code.`;
const response = await fetch('https://api.deepseek.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.DEEPSEEK_KEY}`
},
body: JSON.stringify({
model: this.model,
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: prompt }
],
temperature: 0.3,
max_tokens: 4096
})
});
const data = await response.json();
return data.choices[0].message.content;
}
async explainCode(code: string, language: string = 'python') {
const response = await fetch('https://api.deepseek.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.DEEPSEEK_KEY}`
},
body: JSON.stringify({
model: this.model,
messages: [
{ role: 'system', content: `You are an expert ${language} developer. Explain code clearly.` },
{ role: 'user', content: `Explain the following ${language} code:\n\`\`\`${language}\n${code}\n\`\`\`` }
],
temperature: 0.2
})
});
const data = await response.json();
return data.choices[0].message.content;
}
async optimizeCode(code: string, prompt: string, language: string = 'python') {
const response = await fetch('https://api.deepseek.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.DEEPSEEK_KEY}`
},
body: JSON.stringify({
model: this.model,
messages: [
{ role: 'system', content: `You are an expert ${language} developer. Optimize code for performance and readability.` },
{ role: 'user', content: `Optimize this ${language} code:\n\`\`\`${language}\n${code}\n\`\`\`\n\nPrompt: ${prompt}` }
],
temperature: 0.3
})
});
const data = await response.json();
return data.choices[0].message.content;
}
}
// Usage
const coder = new DeepSeekCoder();
const code = await coder.generateCode('Write a Python function to sort a list by length');
const explanation = await coder.explainCode(code);
const optimized = await coder.optimizeCode(code, 'Make it faster');
class DeepSeekConversation {
private messages: any[] = [];
private model: string;
constructor(model: string = 'deepseek-chat') {
this.model = model;
}
async send(prompt: string) {
this.messages.push({ role: 'user', content: prompt });
const response = await fetch('https://api.deepseek.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.DEEPSEEK_KEY}`
},
body: JSON.stringify({
model: this.model,
messages: this.messages,
max_tokens: 2048
})
});
const data = await response.json();
const content = data.choices[0].message.content;
this.messages.push({ role: 'assistant', content });
return content;
}
getHistory() {
return [...this.messages];
}
clear() {
this.messages = [];
}
setModel(model: string) {
this.model = model;
}
}
async function* streamComplete(prompt: string, model: string) {
const response = await fetch('https://api.deepseek.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.DEEPSEEK_KEY}`
},
body: JSON.stringify({
model,
messages: [{ role: 'user', content: prompt }],
stream: true
})
});
const reader = response.body?.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader!.read();
if (done) break;
const chunk = decoder.decode(value);
if (chunk.includes('[DONE]')) break;
try {
const data = JSON.parse(chunk.replace(/^data: /, ''));
if (data.choices?.[0]?.delta?.content) {
yield data.choices[0].delta.content;
}
} catch (error) {
// Ignore parse errors
}
}
}
// Usage
for await (const chunk of streamComplete('Tell me a story', 'deepseek-chat')) {
process.stdout.write(chunk);
}
async function parallelComplete(prompts: string[], model: string) {
const requests = prompts.map(prompt =>
fetch('https://api.deepseek.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.DEEPSEEK_KEY}`
},
body: JSON.stringify({
model,
messages: [{ role: 'user', content: prompt }]
})
}).then(r => r.json())
);
const responses = await Promise.all(requests);
return responses.map(r => r.choices[0].message.content);
}
async function calculateCost(prompt: string, model: string) {
const response = await fetch('https://api.deepseek.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.DEEPSEEK_KEY}`
},
body: JSON.stringify({
model,
messages: [{ role: 'user', content: prompt }],
max_tokens: 0 // Only count input tokens
})
});
const data = await response.json();
const inputTokens = data.usage?.prompt_tokens || 0;
const pricing: Record<string, { input: number; output: number }> = {
'deepseek-chat': { input: 0.0000014, output: 0.0000028 },
'deepseek-v4-flash': { input: 0.0000014, output: 0.0000028 }
};
const rates = pricing[model] || { input: 0.0000014, output: 0.0000028 };
return {
inputTokens,
inputCost: inputTokens * rates.input,
outputCostPerToken: rates.output
};
}