clarity-ai 6.5.0 → 6.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,21 @@
2
2
 
3
3
  ---
4
4
 
5
+ ## 6.5.2 (2026-06-06)
6
+
7
+ ### CoT + MoE Space Architecture
8
+ - Dataset repos now hold LoRA weights (flash pushed to `Universal-618/Clarity-flash-weights` dataset)
9
+ - Space app downloads weights from dataset repo on startup, loads base model + LoRA in 4-bit, serves `/v1/chat/completions`
10
+ - CLI routes by model: Flash 14B → Clarity-2 (CoT), Heavy 20B → Clarity-3 (MoE)
11
+ - Multiple fallback Spaces for each model
12
+ - All 6 Spaces connected via shared bucket to Clarity-main
13
+
14
+ ## 6.5.1 (2026-06-06)
15
+
16
+ ### 6-Space Fallback
17
+ - All 6 Spaces tried in sequence for redundancy
18
+ - Lowercase HF Space URL fix
19
+
5
20
  ## 6.5.0 (2026-06-06)
6
21
 
7
22
  ### Closed Source + Space Proxy
package/README.md CHANGED
@@ -103,16 +103,10 @@ clarity /bash ls -la
103
103
  | Gemini 2.0 Flash | Google | 32K (fast) |
104
104
  | DeepSeek R1 Free | OpenRouter | 128K |
105
105
 
106
- ## Provider Comparison
106
+ ## Architecture
107
107
 
108
- | Provider | Free Tier | Streaming | Priority |
109
- |---|---|---|---|
110
- | Groq | ✓ | ✓ | 1 (fastest) |
111
- | Google Gemini | ✓ | ✓ | 2 |
112
- | HuggingFace (Clarity Flash) | Needs HF_TOKEN | ✓ | 3 |
113
- | DeepSeek | Cheap | ✓ | 4 |
114
- | OpenRouter | ✓ | ✓ | 5 |
108
+ Clarity Flash 14B is served via `Clarity-main` HF Space — a streaming inference proxy at `*.hf.space/v1/chat/completions`. No API keys needed.
115
109
 
116
110
  ## License
117
111
 
118
- MIT
112
+ Proprietary — all rights reserved. See [LICENSE](LICENSE).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clarity-ai",
3
- "version": "6.5.0",
3
+ "version": "6.5.2",
4
4
  "description": "CLARITY — terminal AI agent with Clarity Flash 14B",
5
5
  "type": "module",
6
6
  "bin": {
package/requirements.txt CHANGED
@@ -1,4 +1,9 @@
1
- gradio>=4
2
- requests>=2
3
- uvicorn>=0.20
4
1
  fastapi>=0.100
2
+ uvicorn>=0.20
3
+ transformers>=4.38
4
+ torch>=2.1
5
+ accelerate>=0.27
6
+ bitsandbytes>=0.42
7
+ peft>=0.8
8
+ huggingface-hub>=0.20
9
+ sentencepiece>=0.1.99
package/space_app.py CHANGED
@@ -1,28 +1,69 @@
1
- import os, json, requests
2
- import gradio as gr
1
+ import os, json, time, asyncio
2
+ from threading import Thread
3
3
  from fastapi import FastAPI, Request
4
4
  from fastapi.responses import StreamingResponse, JSONResponse
5
- import uvicorn
5
+ from contextlib import asynccontextmanager
6
6
 
7
7
  HF_TOKEN = os.environ.get('HF_TOKEN', '')
8
- MODEL = 'Universal-618/Clarity-flash-weights'
9
- API = f'https://api-inference.huggingface.co/models/{MODEL}/v1/chat/completions'
10
- HEADERS = {'Authorization': f'Bearer {HF_TOKEN}', 'Content-Type': 'application/json'}
8
+ MODEL_NAME = os.environ.get('HF_MODEL', 'Clarity-flash-weights')
9
+ BASE_MODEL = os.environ.get('BASE_MODEL_ID', '')
10
+ DS = f'Universal-618/{MODEL_NAME}'
11
+
12
+ print(f'[startup] model={MODEL_NAME} base={BASE_MODEL}', flush=True)
13
+
14
+ model = None
15
+ tokenizer = None
16
+
17
+ def load_model():
18
+ global model, tokenizer
19
+ print('[startup] downloading weights...', flush=True)
20
+ from huggingface_hub import snapshot_download
21
+ path = snapshot_download(repo_id=DS, repo_type='dataset', token=HF_TOKEN)
22
+ print(f'[startup] weights at {path}', flush=True)
23
+ from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig, TextIteratorStreamer
24
+ from peft import PeftModel
25
+ bnb = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_compute_dtype='float16', bnb_4bit_use_double_quant=True)
26
+ print('[startup] loading base model...', flush=True)
27
+ base = AutoModelForCausalLM.from_pretrained(
28
+ BASE_MODEL, quantization_config=bnb, device_map='auto',
29
+ trust_remote_code=True, low_cpu_mem_usage=True, token=HF_TOKEN)
30
+ print('[startup] loading LoRA...', flush=True)
31
+ model = PeftModel.from_pretrained(base, path, token=HF_TOKEN)
32
+ tokenizer = AutoTokenizer.from_pretrained(path, token=HF_TOKEN)
33
+ if tokenizer.pad_token is None:
34
+ tokenizer.pad_token = tokenizer.eos_token
35
+ print('[startup] ready', flush=True)
36
+
37
+ load_model()
11
38
 
12
39
  app = FastAPI()
13
40
 
14
41
  @app.post('/v1/chat/completions')
15
- async def chat_completions(request: Request):
42
+ async def generate(request: Request):
16
43
  body = await request.json()
17
- body['model'] = MODEL
44
+ prompt = tokenizer.apply_chat_template(body['messages'], tokenize=False, add_generation_prompt=True)
45
+ inputs = tokenizer(prompt, return_tensors='pt')
18
46
  stream = body.get('stream', True)
19
- body['stream'] = stream
20
- resp = requests.post(API, headers=HEADERS, json=body, stream=True)
21
- if resp.status_code != 200:
22
- return JSONResponse({'error': resp.text}, status_code=resp.status_code)
47
+ max_tokens = body.get('max_tokens', 4096)
48
+ gen_kwargs = dict(input_ids=inputs.input_ids, attention_mask=inputs.attention_mask,
49
+ max_new_tokens=max_tokens, temperature=body.get('temperature', 0.7),
50
+ do_sample=True, pad_token_id=tokenizer.pad_token_id)
23
51
  if stream:
24
- return StreamingResponse(resp.iter_lines(), media_type='text/event-stream', headers={'Cache-Control': 'no-cache', 'Connection': 'keep-alive', 'X-Accel-Buffering': 'no'})
25
- return resp.json()
52
+ from transformers import TextIteratorStreamer
53
+ streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
54
+ t = Thread(target=model.generate, kwargs={**gen_kwargs, 'streamer': streamer})
55
+ t.start()
56
+ async def gen():
57
+ yield 'data: {"choices":[{"delta":{"role":"assistant"},"index":0}]}\n\n'
58
+ for text in streamer:
59
+ if text:
60
+ yield f'data: {json.dumps({"choices":[{"delta":{"content":text},"index":0}]})}\n\n'
61
+ yield 'data: [DONE]\n\n'
62
+ return StreamingResponse(gen(), media_type='text/event-stream', headers={
63
+ 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', 'X-Accel-Buffering': 'no'})
64
+ out = model.generate(**gen_kwargs)
65
+ text = tokenizer.decode(out[0][inputs.input_ids.shape[1]:], skip_special_tokens=True)
66
+ return {'choices': [{'message': {'role': 'assistant', 'content': text}, 'index': 0}]}
26
67
 
27
68
  @app.get('/main-data/{path:path}')
28
69
  async def main_data(path: str):
@@ -33,20 +74,10 @@ async def main_data(path: str):
33
74
  with open(fp) as f:
34
75
  return JSONResponse(json.load(f))
35
76
 
36
- def chat_ui(message, history):
37
- history = history or []
38
- msgs = [{'role': 'user' if i % 2 == 0 else 'assistant', 'content': m} for i, m in enumerate(history + [message])]
39
- body = {'model': MODEL, 'messages': msgs, 'stream': False, 'max_tokens': 4096}
40
- resp = requests.post(API, headers=HEADERS, json=body)
41
- if resp.status_code == 200:
42
- return resp.json()['choices'][0]['message']['content']
43
- return f'Error: {resp.status_code}'
44
-
45
- with gr.Blocks(title='CLARITY Flash', css='footer{display:none!important}') as ui:
46
- gr.Markdown('# CLARITY Flash 14B')
47
- gr.ChatInterface(chat_ui, title='Chat')
48
-
49
- app = gr.mount_gradio_app(app, ui, path='/')
77
+ @app.get('/')
78
+ async def root():
79
+ return {'status': 'ok', 'model': MODEL_NAME}
50
80
 
51
81
  if __name__ == '__main__':
82
+ import uvicorn
52
83
  uvicorn.run(app, host='0.0.0.0', port=7860)
@@ -1,5 +1,6 @@
1
1
  export const ALL_MODELS = [
2
2
  { id: 'huggingface/Universal-618/Clarity-flash-weights', provider: 'huggingface', label: 'Clarity Flash 14B', badge: '128K' },
3
+ { id: 'huggingface/Universal-618/Clarity-heavy-weights', provider: 'huggingface', label: 'Clarity Heavy 20B', badge: 'MoE' },
3
4
  { id: 'groq/llama-3.3-70b-versatile', provider: 'groq', label: 'Llama 3.3 70B Versatile', badge: null },
4
5
  { id: 'groq/llama-3.1-8b-instant', provider: 'groq', label: 'Llama 3.1 8B Instant', badge: 'Fast' },
5
6
  { id: 'groq/llama-4-scout-17b-16e-instruct', provider: 'groq', label: 'Llama 4 Scout 17B', badge: null },
@@ -1,26 +1,25 @@
1
1
  import { getKey } from '../config/keys.js';
2
2
  import { streamResponse } from './streaming.js';
3
- import { parseErrorResponse } from './errors.js';
4
-
5
- const PROVIDERS = {
6
- huggingface: {
7
- endpoint: 'https://Universal-618-Clarity-main.hf.space/v1/chat/completions',
8
- name: 'huggingface',
9
- },
10
- groq: {
11
- endpoint: 'https://api.groq.com/openai/v1/chat/completions',
12
- name: 'groq',
13
- },
14
- openrouter: {
15
- endpoint: 'https://openrouter.ai/api/v1/chat/completions',
16
- name: 'openrouter',
17
- },
3
+
4
+ const MODEL_ROUTES = {
5
+ 'Universal-618/Clarity-flash-weights': [
6
+ 'https://universal-618-clarity-2.hf.space/v1/chat/completions',
7
+ 'https://universal-618-clarity-4.hf.space/v1/chat/completions',
8
+ 'https://universal-618-clarity-5.hf.space/v1/chat/completions',
9
+ ],
10
+ 'Universal-618/Clarity-heavy-weights': [
11
+ 'https://universal-618-clarity-3.hf.space/v1/chat/completions',
12
+ 'https://universal-618-clarity-5.hf.space/v1/chat/completions',
13
+ 'https://universal-618-clarity-6.hf.space/v1/chat/completions',
14
+ ],
18
15
  };
19
16
 
20
- export async function* callAI(providerName, model, messages, options = {}) {
21
- const provider = PROVIDERS[providerName];
22
- if (!provider) throw { type: 'config_error', message: 'Unknown provider: ' + providerName };
17
+ const STATIC_ENDPOINTS = {
18
+ groq: ['https://api.groq.com/openai/v1/chat/completions'],
19
+ openrouter: ['https://openrouter.ai/api/v1/chat/completions'],
20
+ };
23
21
 
22
+ export async function* callAI(providerName, model, messages, options = {}) {
24
23
  const key = getKey(providerName);
25
24
  if (!key && providerName !== 'huggingface') {
26
25
  throw { type: 'auth_error', provider: providerName, message: 'No API key set for ' + providerName, hint: '/keys ' + providerName + ' <your-key>' };
@@ -40,17 +39,31 @@ export async function* callAI(providerName, model, messages, options = {}) {
40
39
  body.tool_choice = 'auto';
41
40
  }
42
41
 
43
- let endpoint = provider.endpoint;
44
42
  const extraHeaders = {};
45
43
  if (providerName === 'openrouter') {
46
44
  extraHeaders['HTTP-Referer'] = 'https://clarity-ai.local';
47
45
  extraHeaders['X-Title'] = 'CLARITY AI';
48
46
  }
49
47
 
50
- const stream = streamResponse(endpoint, body, key || 'none', extraHeaders, options.signal);
51
- for await (const event of stream) {
52
- yield event;
48
+ const endpoints = MODEL_ROUTES[modelName] || STATIC_ENDPOINTS[providerName] || [];
49
+ if (!endpoints.length) {
50
+ throw { type: 'config_error', message: 'No endpoints for ' + providerName + '/' + modelName };
51
+ }
52
+
53
+ let lastErr;
54
+ for (const endpoint of endpoints) {
55
+ try {
56
+ const stream = streamResponse(endpoint, body, key || 'none', extraHeaders, options.signal);
57
+ for await (const event of stream) {
58
+ yield event;
59
+ }
60
+ return;
61
+ } catch (err) {
62
+ lastErr = err;
63
+ continue;
64
+ }
53
65
  }
66
+ throw lastErr;
54
67
  }
55
68
 
56
69
  export async function callAISync(providerName, model, messages, options = {}) {