Spaces:
Sleeping

LS / README.md
Adarsh Kumar
Upload 20 files
f45a595 verified
|
Raw History Blame Contribute Delete
13.1 kB
metadata
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:

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.

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

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:
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:

Context: 131072
Output:   65536

Use the ZCode UI when possible, because its local configuration schema can change. A typical custom-provider shape is:

{
  "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:

BASE=http://127.0.0.1:7860

Non-streaming chat

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

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

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

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:

"response_format": {"type": "json_object"}

and:

{
  "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:

PUBLIC_ACCESS=false
PROVIDER_API_KEY=<long-random-secret>

Then use that secret as the ZCode API key.

Run locally

Native Python

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

cp .env.example .env
docker compose up --build

Docker directly

docker build -t upstage-zcode .
docker run --rm -p 7860:7860 upstage-zcode

Tests

Offline unit and adapter tests:

pytest -q

Live source-provider tests, including fresh credential capture, realtime timing, search, history, and reasoning separation:

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:

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:

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.

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.