Spaces:
Running

File size: 4,879 Bytes
30247fe
64378fa
 
30247fe
 
 
 
64378fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30247fe
 
 
64378fa
 
 
 
 
 
 
 
 
 
 
 
30247fe
64378fa
 
 
30247fe
64378fa
 
 
 
 
 
 
 
 
 
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
import { createContext, useCallback, useContext, useMemo, useState, html } from "./runtime.js";
import { useCloud } from "./cloud.js";

// Chat runs against the user's own OpenAI-compatible endpoint, or against a
// hosted model included in a plan. The Paragraph models are 2.5–61 GB
// checkpoints: they are downloaded for the Mac/iOS app or any GGUF runner, not
// executed inside a browser tab.

const EngineContext = createContext(null);

function readEndpoint(key) {
  try {
    return localStorage.getItem(key) || "";
  } catch {
    return "";
  }
}

export function EngineProvider({ children }) {
  const cloud = useCloud();

  // The developer's hosted models (paid for with the plan's budget), chosen here.
  const [hostedId, setHostedId] = useState(() => readEndpoint("explication.hosted.model"));
  const setHostedModel = useCallback((id) => {
    try {
      localStorage.setItem("explication.hosted.model", id || "");
    } catch {
      // ignore
    }
    setHostedId(id || "");
  }, []);
  const hosted = useMemo(
    () => cloud.models.find((m) => m.id === hostedId && m.enabled !== false) || null,
    [cloud.models, hostedId]
  );
  const hostedReady = !!hosted && !!hosted.endpoint_url && cloud.canHost(hosted);

  const [endpoint, setEndpointState] = useState(() => ({
    baseUrl: readEndpoint("explication.endpoint.baseUrl").trim(),
    model: readEndpoint("explication.endpoint.model").trim(),
    key: readEndpoint("explication.endpoint.key").trim()
  }));

  const setEndpoint = useCallback((next) => {
    const clean = {
      baseUrl: (next.baseUrl || "").trim(),
      model: (next.model || "").trim(),
      key: (next.key || "").trim()
    };
    try {
      localStorage.setItem("explication.endpoint.baseUrl", clean.baseUrl);
      localStorage.setItem("explication.endpoint.model", clean.model);
      localStorage.setItem("explication.endpoint.key", clean.key);
    } catch {
      // ignore quota errors
    }
    setEndpointState(clean);
  }, []);

  const hasEndpoint = !!endpoint.baseUrl && !!endpoint.model;

  /**
   * Streams a reply. Returns the full text.
   */
  const chat = useCallback(
    async (messages, onToken) => {
      if (hasEndpoint) {
        const base = endpoint.baseUrl.replace(/\/+$/, "");
        const res = await fetch(`${base}/chat/completions`, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            ...(endpoint.key ? { Authorization: `Bearer ${endpoint.key}` } : {})
          },
          body: JSON.stringify({ model: endpoint.model, messages, stream: true, temperature: 0.4 })
        });
        if (!res.ok) throw new Error(`The endpoint returned ${res.status}. Check the URL, model and key in Settings.`);
        if (!res.body) {
          const data = await res.json();
          const text = data?.choices?.[0]?.message?.content || "";
          if (onToken) onToken(text);
          return text;
        }
        const reader = res.body.getReader();
        const decoder = new TextDecoder();
        let buffer = "";
        let full = "";
        while (true) {
          const { value, done } = await reader.read();
          if (done) break;
          buffer += decoder.decode(value, { stream: true });
          const lines = buffer.split("\n");
          buffer = lines.pop() || "";
          for (const line of lines) {
            const trimmed = line.trim();
            if (!trimmed.startsWith("data:")) continue;
            const payload = trimmed.slice(5).trim();
            if (payload === "[DONE]") continue;
            try {
              const json = JSON.parse(payload);
              const delta = json?.choices?.[0]?.delta?.content || "";
              if (delta) {
                full += delta;
                onToken && onToken(full);
              }
            } catch {
              // A partial SSE line; wait for the next chunk.
            }
          }
        }
        return full;
      }

      if (hostedReady) {
        return cloud.hostedChat(hosted, messages, onToken);
      }

      throw new Error(
        "No model is connected. Add an OpenAI-compatible endpoint in Settings, or download a Paragraph model and run it on your own machine."
      );
    },
    [hasEndpoint, endpoint, hostedReady, hosted, cloud]
  );

  const value = useMemo(
    () => ({
      endpoint,
      hasEndpoint,
      hosted,
      hostedId,
      hostedReady,
      setHostedModel,
      canGenerate: hasEndpoint || hostedReady,
      chat,
      setEndpoint
    }),
    [endpoint, hasEndpoint, hosted, hostedId, hostedReady, setHostedModel, chat, setEndpoint]
  );

  return html`<${EngineContext.Provider} value=${value}>${children}<//>`;
}

export function useEngine() {
  const value = useContext(EngineContext);
  if (!value) throw new Error("useEngine must be used inside EngineProvider");
  return value;
}