Spaces:
Sleeping

File size: 2,104 Bytes
fd20436
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import axios from 'axios';

export const OPENCODE_BASE_URL = 'https://opencode.ai/zen/v1';

export const OPENCODE_MODELS = [
  'deepseek-v4-flash-free',
  'mimo-v2.5-free',
  'north-mini-code-free',
  'nemotron-3-ultra-free',
  'big-pickle',
  'hy3-free',
];

export const DEFAULT_OPENCODE_MODEL = OPENCODE_MODELS[0];

export class OpenCodeError extends Error {
  constructor(message, code = 'opencode_error', details = null) {
    super(message);
    this.name = 'OpenCodeError';
    this.code = code;
    this.details = details;
  }
}

export function isOpenCodeModel(model) {
  return OPENCODE_MODELS.includes(model);
}

export function openCodeModelObjects() {
  const created = Math.floor(Date.now() / 1000);
  return OPENCODE_MODELS.map((id) => ({
    id,
    object: 'model',
    created,
    owned_by: 'opencode',
  }));
}

export function openCodeAnthropicModelObjects() {
  return OPENCODE_MODELS.map((id) => ({
    type: 'model',
    id,
    display_name: id,
    created_at: new Date().toISOString(),
  }));
}

export async function opencodeChat({
  model = DEFAULT_OPENCODE_MODEL,
  messages,
  maxTokens = 200,
  timeout = 120000,
}) {
  if (!isOpenCodeModel(model)) {
    throw new OpenCodeError(`Model ${model} is not supported`, 'model_not_found');
  }

  const body = {
    model,
    messages,
    max_tokens: maxTokens,
  };

  try {
    const res = await axios.post(`${OPENCODE_BASE_URL}/chat/completions`, body, {
      headers: { 'Content-Type': 'application/json' },
      timeout,
    });
    return res.data;
  } catch (err) {
    const status = err.response?.status;
    const data = err.response?.data;
    const message = data?.error?.message || err.message;
    throw new OpenCodeError(message, status === 401 ? 'auth_error' : 'api_error', {
      status,
      data,
    });
  }
}

export function openCodeContent(response) {
  const choice = response?.choices?.[0];
  const content = choice?.message?.content;
  if (typeof content === 'string') return content;
  if (Array.isArray(content)) {
    return content.map((item) => item.text || '').join('');
  }
  return '';
}