Spaces:
Sleeping
Sleeping
File size: 13,081 Bytes
f45a595 | 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 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 | ---
title: Upstage Solar for ZCode
emoji: ☀️
colorFrom: yellow
colorTo: blue
sdk: docker
app_port: 7860
pinned: false
---
# Upstage Solar for ZCode
A purpose-built **OpenAI Chat Completions provider** for **Z.ai ZCode**, packaged as a public Hugging Face Docker Space.
It is based on the async, pure-HTTP provider from:
```text
Adarshukumar/serv__/New Upstage Change Logs/upstage_provider.py
```
The transport discovers an anonymous Upstage Console session through Next.js server actions, uses `curl_cffi` with browser TLS impersonation, and talks to the Upstage demo Chat Completions stream. No browser, Selenium, API key, or upstream account is required.
> This is an independent compatibility gateway, not an official Upstage service. The anonymous Console transport can change or be rate-limited by Upstage. Review Upstage's terms before operating a public relay.
## Why this version works with ZCode
The source provider was an excellent async chat library, but it was not an OpenAI web server and did not implement function calls. This project adds:
- `GET /v1/models`
- `GET /v1/models/{model}`
- `POST /v1/chat/completions`
- non-streaming OpenAI responses
- realtime SSE for ordinary chat
- `[DONE]` and `stream_options.include_usage`
- separate `reasoning_content`
- optional Upstage/Tavily web search and returned sources
- OpenAI `system`, `developer`, `user`, `assistant`, and `tool` message handling
- OpenAI `tools`, `tool_choice`, `parallel_tool_calls`, assistant `tool_calls`, and tool-result loops
- JSON-Schema validation of generated function arguments
- one bounded corrective retry when Solar emits malformed or missing required calls
- OpenAI-shaped errors, body/input limits, concurrency control, optional rate limiting, and optional Bearer authentication
- a non-root UID 1000 Docker image for Hugging Face Spaces
## Important tool-calling design
Upstage's official API supports native function calling. However, the anonymous Console demo endpoint used here currently accepts but **ignores** native `tools` and `tool_choice` fields. Pretending otherwise would break ZCode.
This gateway therefore uses a constrained adapter:
1. ZCode's function catalog and tool choice are validated.
2. A bounded tool protocol is injected into Solar's system prompt.
3. Solar emits its learned internal call format.
4. The gateway parses the call, checks the function name, parses arguments as JSON, and validates them against the requested function's JSON Schema.
5. Valid calls are returned as standard OpenAI `tool_calls`.
6. On the next request, assistant calls and `role: tool` results are translated back into Solar's conversation format.
Tool-aware generations are buffered until validation completes, then emitted as valid OpenAI JSON or SSE. Ordinary chat without tools is streamed token by token directly from Upstage.
This is deliberate: ZCode receives a valid tool call or a clean error—never half of a malformed protocol block.
## Models
The API exposes the four canonical models present in the source provider:
| Model ID | Reasoning efforts | Search | Source max output |
|---|---|---:|---:|
| `solar-pro3` | `low`, `medium`, `high` | yes | 65,536 |
| `solar-pro2` | `low`, `high` | yes | 16,383 |
| `syn-pro` | `low`, `high` | yes | 16,384 |
| `upstage/solar-1-mini-chat` | none | yes | 16,383 |
**Recommended for ZCode:** `solar-pro3`.
## Deploy as a public Hugging Face Space
### 1. Create the Space
1. Open <https://huggingface.co/new-space>.
2. Choose **Docker** as the SDK.
3. Choose **Public** visibility.
4. A free CPU Space is sufficient; inference runs remotely.
### 2. Put this directory at the Space repository root
The Space root must directly contain `README.md`, `Dockerfile`, `app.py`, `tool_protocol.py`, `upstage_provider.py`, and `requirements.txt`.
```bash
git clone https://huggingface.co/spaces/YOUR_USERNAME/YOUR_SPACE
cp -a /path/to/hf-space/. YOUR_SPACE/
cd YOUR_SPACE
git add .
git commit -m "Deploy Upstage Solar OpenAI gateway for ZCode"
git push
```
Hugging Face reads the metadata at the top of this README, builds the Docker image, and exposes port `7860`.
No Space secret is required for the requested public deployment. Credentials discovered from the Upstage Console are cached inside the container under `UPSTAGE_CACHE_DIR` and are automatically refreshed.
### 3. Verify the deployment
```bash
BASE=https://YOUR_USERNAME-YOUR_SPACE.hf.space
curl -sS "$BASE/healthz"
curl -sS "$BASE/v1/models" | python -m json.tool
```
## Connect ZCode
ZCode appends `/chat/completions`, so the provider URL must end at **`/v1`**, not at the full endpoint.
In ZCode:
1. Open **Settings → Model settings**.
2. Select **Add provider → Create custom provider**.
3. Choose the **OpenAI-compatible / Chat Completions** API format.
4. Enter:
```text
Name: Upstage Solar HF
Base URL: https://YOUR_USERNAME-YOUR_SPACE.hf.space/v1
API key: public
Model ID: solar-pro3
```
The API key value is only a placeholder. With the default `PUBLIC_ACCESS=true`, the server accepts requests with no Authorization header and ignores arbitrary Bearer values.
Suggested model limits if ZCode asks for them:
```text
Context: 131072
Output: 65536
```
Use the ZCode UI when possible, because its local configuration schema can change. A typical custom-provider shape is:
```json
{
"provider": {
"upstage-solar-hf": {
"name": "Upstage Solar HF",
"kind": "openai-compatible",
"source": "custom",
"options": {
"baseURL": "https://YOUR_USERNAME-YOUR_SPACE.hf.space/v1",
"apiKey": "public",
"apiKeyRequired": false
},
"models": {
"solar-pro3": {
"name": "Solar Pro 3",
"limit": {
"context": 131072,
"output": 65536
}
}
}
}
}
}
```
ZCode will send its coding functions in `tools`; the gateway handles the call/result loop automatically. The server never executes ZCode tools itself—ZCode remains in control of filesystem and terminal operations.
## API examples
Set a local or deployed base URL:
```bash
BASE=http://127.0.0.1:7860
```
### Non-streaming chat
```bash
curl -sS "$BASE/v1/chat/completions" \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer public' \
-d '{
"model": "solar-pro3",
"messages": [{"role": "user", "content": "Reply with exactly OK"}],
"stream": false,
"max_tokens": 64
}' | python -m json.tool
```
### Realtime streaming with usage
```bash
curl -N "$BASE/v1/chat/completions" \
-H 'Content-Type: application/json' \
-d '{
"model": "solar-pro3",
"messages": [{"role": "user", "content": "Write a short Python function."}],
"stream": true,
"stream_options": {"include_usage": true}
}'
```
Reasoning is returned separately in `delta.reasoning_content`; it is not mixed into visible answer text.
### Function call
```bash
curl -sS "$BASE/v1/chat/completions" \
-H 'Content-Type: application/json' \
-d '{
"model": "solar-pro3",
"messages": [{"role": "user", "content": "Read src/app.py before answering."}],
"tools": [{
"type": "function",
"function": {
"name": "read_file",
"description": "Read a workspace file",
"parameters": {
"type": "object",
"properties": {"path": {"type": "string"}},
"required": ["path"],
"additionalProperties": false
}
}
}],
"tool_choice": "required"
}' | python -m json.tool
```
A successful choice has `finish_reason: "tool_calls"`, `message.content: null`, and standard OpenAI `message.tool_calls`.
### Web search
```bash
curl -sS "$BASE/v1/chat/completions" \
-H 'Content-Type: application/json' \
-d '{
"model": "solar-pro3",
"messages": [{"role": "user", "content": "What changed in Python recently?"}],
"search": true,
"reasoning_effort": "high"
}' | python -m json.tool
```
Search uses the source provider's Tavily-backed Upstage mode. Sources are returned in the top-level `sources` array. During streaming, a chunk may carry a top-level `sources` array before answer tokens.
ZCode custom providers do not currently expose arbitrary per-request parameters in every UI version, so `search` is primarily useful to direct API clients unless the client lets you add it.
### Structured JSON
The gateway supports prompt-backed OpenAI response formats:
```json
"response_format": {"type": "json_object"}
```
and:
```json
{
"response_format": {
"type": "json_schema",
"json_schema": {
"name": "answer",
"schema": {
"type": "object",
"properties": {"answer": {"type": "string"}},
"required": ["answer"]
}
}
}
}
```
Unlike function arguments, final structured answer JSON is prompt-backed and is not server-side schema validated.
## Supported request fields
Core fields:
- `model`
- `messages`
- `stream`
- `stream_options.include_usage`
- `temperature`
- `max_tokens` or `max_completion_tokens`
- `reasoning_effort`, or `reasoning: {"effort": ...}`
- `search`, `web_search`, or `enable_search`
- `tools`
- `tool_choice`: `none`, `auto`, `required`, or a specific function
- `parallel_tool_calls`
- legacy `functions` and `function_call`
- `response_format`
Only `n=1` is supported. The anonymous source transport is text-only; image/audio content parts return a clean `unsupported_content_type` error rather than being silently discarded.
## Configuration
All variables are optional:
| Variable | Default | Purpose |
|---|---:|---|
| `PUBLIC_ACCESS` | `true` | Accept API calls without authentication |
| `PROVIDER_API_KEY` | empty | Required Bearer key when `PUBLIC_ACCESS=false` |
| `PORT` | `7860` | HTTP port |
| `UPSTAGE_CACHE_DIR` | `/home/user/.cache/upstage` in Docker | Credential cache location |
| `MAX_CONCURRENT_REQUESTS` | `6` | Concurrent Upstage generations |
| `QUEUE_TIMEOUT_SECONDS` | `20` | Wait for a generation slot |
| `UPSTREAM_TIMEOUT_SECONDS` | `330` | Per-generation timeout |
| `UPSTREAM_RETRIES` | `1` | Retry count before any streamed output is committed |
| `TOOL_PROTOCOL_RETRIES` | `1` | Corrective retries for invalid tool output; capped at 2 |
| `MAX_BODY_MB` | `4` | Request body limit |
| `MAX_INPUT_CHARS` | `1000000` | Serialized message limit |
| `MAX_BUFFERED_OUTPUT_CHARS` | `8000000` | Tool-aware generation buffer limit |
| `RATE_LIMIT_PER_MINUTE` | `0` | Per-IP in-memory request limit; `0` disables it |
| `LOG_LEVEL` | `INFO` | Python log level |
The requested public deployment defaults to no authentication and no rate limiter so rapid ZCode tool loops are not accidentally blocked. A concurrency limit still protects the Space.
For a safer later deployment, set:
```text
PUBLIC_ACCESS=false
PROVIDER_API_KEY=<long-random-secret>
```
Then use that secret as the ZCode API key.
## Run locally
### Native Python
```bash
python -m venv .venv
. .venv/bin/activate # Windows: .venv\Scripts\activate
pip install -r requirements-dev.txt
uvicorn app:app --host 0.0.0.0 --port 7860
```
### Docker Compose
```bash
cp .env.example .env
docker compose up --build
```
### Docker directly
```bash
docker build -t upstage-zcode .
docker run --rm -p 7860:7860 upstage-zcode
```
## Tests
Offline unit and adapter tests:
```bash
pytest -q
```
Live source-provider tests, including fresh credential capture, realtime timing, search, history, and reasoning separation:
```bash
UPSTAGE_LIVE=1 pytest -q tests/test_upstage_provider.py -k Live
```
Full running-server smoke test, including an OpenAI tool call and tool-result continuation:
```bash
python smoke_test.py http://127.0.0.1:7860
```
A separate two-step ZCode-style coding probe verifies `tool_choice: auto`, a `read_file` call, its tool result, and a following `write_file` call:
```bash
python live_zcode_test.py http://127.0.0.1:7860
```
Both scripts can also target a deployed Space URL. The sandbox's recorded verification results are in [`TESTING.md`](TESTING.md).
## Operational behavior
- Credential discovery is lazy. `/healthz` and `/readyz` stay healthy even if Upstage is temporarily unavailable.
- The first model request may take a few seconds while Next.js action IDs and cookies are captured.
- Credentials are cached and automatically refreshed after auth rejection.
- A streaming request is prefetched through its first Upstage event, so early upstream failures are returned as JSON errors instead of a misleading HTTP 200 SSE stream.
- If an error occurs after streaming has begun, the server emits an SSE `error` object followed by `[DONE]`.
- Usage uses Upstage counts when non-zero and a clearly internal character-based estimate when the demo stream reports zeros.
- Logs contain bounded error summaries, never full prompts or discovered credentials.
- Free Hugging Face Spaces sleep when idle; the first ZCode request after sleep may be slower.
- Public Spaces can be used by anyone who knows the URL. In-memory limits are per replica and are not a substitute for authentication.
|