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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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
"""OpenAI Chat Completions gateway for Upstage Solar and Z.ai ZCode.

The model transport is derived from ``New Upstage Change Logs/upstage_provider.py``.
This API layer adds canonical OpenAI JSON/SSE responses, request validation,
reasoning/search metadata, public-Space safety limits, and a constrained function-
calling adapter for ZCode's agent loop.
"""
from __future__ import annotations

import asyncio
import hmac
import json
import logging
import os
import re
import time
import uuid
from collections import defaultdict, deque
from dataclasses import dataclass, field
from html import escape
from typing import Any, AsyncGenerator, Callable

from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse, JSONResponse, Response, StreamingResponse

from tool_protocol import (
    ParsedToolCall,
    ToolConfiguration,
    ToolProtocolError,
    build_tool_instruction,
    normalize_messages,
    parse_embedded_tool_calls,
    parse_generated_tool_calls,
    parse_tool_configuration,
)
from upstage_provider import (
    _MODELS,
    StreamEvent,
    UpstageAuthError,
    UpstageError,
    UpstageProvider,
    UpstageStreamError,
    _resolve_model,
)


def env_bool(name: str, default: bool) -> bool:
    value = os.getenv(name)
    if value is None:
        return default
    return value.strip().lower() in {"1", "true", "yes", "on"}


def env_int(name: str, default: int, minimum: int = 0) -> int:
    try:
        return max(minimum, int(os.getenv(name, str(default))))
    except ValueError:
        return max(minimum, default)


def env_float(name: str, default: float, minimum: float = 0.0) -> float:
    try:
        return max(minimum, float(os.getenv(name, str(default))))
    except ValueError:
        return max(minimum, default)


SERVICE_NAME = os.getenv("SERVICE_NAME", "Upstage Solar for ZCode")
PUBLIC_ACCESS = env_bool("PUBLIC_ACCESS", True)
PROVIDER_API_KEY = os.getenv("PROVIDER_API_KEY", "").strip()
MAX_BODY_MB = env_int("MAX_BODY_MB", 4, 1)
MAX_BODY_BYTES = MAX_BODY_MB * 1024 * 1024
MAX_INPUT_CHARS = env_int("MAX_INPUT_CHARS", 1_000_000, 1_000)
MAX_CONCURRENT_REQUESTS = env_int("MAX_CONCURRENT_REQUESTS", 6, 1)
QUEUE_TIMEOUT_SECONDS = env_float("QUEUE_TIMEOUT_SECONDS", 20.0, 0.1)
UPSTREAM_TIMEOUT_SECONDS = env_float("UPSTREAM_TIMEOUT_SECONDS", 330.0, 30.0)
UPSTREAM_RETRIES = env_int("UPSTREAM_RETRIES", 1, 0)
RATE_LIMIT_PER_MINUTE = env_int("RATE_LIMIT_PER_MINUTE", 0, 0)
TOOL_PROTOCOL_RETRIES = min(env_int("TOOL_PROTOCOL_RETRIES", 1, 0), 2)
MAX_BUFFERED_OUTPUT_CHARS = env_int("MAX_BUFFERED_OUTPUT_CHARS", 8_000_000, 10_000)

logging.basicConfig(
    level=os.getenv("LOG_LEVEL", "INFO").upper(),
    format="%(asctime)s %(levelname)s %(name)s %(message)s",
)
logger = logging.getLogger("upstage-zcode")

request_slots = asyncio.Semaphore(MAX_CONCURRENT_REQUESTS)
rate_buckets: dict[str, deque[float]] = defaultdict(deque)
rate_lock = asyncio.Lock()
provider_factory: Callable[[], UpstageProvider] = UpstageProvider


class ApiProblem(Exception):
    def __init__(
        self,
        message: str,
        status: int = 400,
        error_type: str = "invalid_request_error",
        code: str = "invalid_request",
        param: str | None = None,
        headers: dict[str, str] | None = None,
    ):
        super().__init__(message)
        self.message = message
        self.status = status
        self.error_type = error_type
        self.code = code
        self.param = param
        self.headers = headers or {}


@dataclass
class ChatRequest:
    model: str
    messages: list[dict[str, str]]
    stream: bool
    include_usage: bool
    temperature: float | None
    max_tokens: int | None
    reasoning: str | None
    search: bool
    tools: ToolConfiguration
    response_instruction: str = ""


@dataclass
class GenerationResult:
    content: str = ""
    reasoning: str = ""
    sources: list[dict[str, Any]] = field(default_factory=list)
    usage: dict[str, int] = field(default_factory=dict)
    tool_calls: list[ParsedToolCall] = field(default_factory=list)


app = FastAPI(
    title=SERVICE_NAME,
    version="2.0.0",
    description=(
        "OpenAI-compatible Upstage Solar gateway for ZCode, with realtime SSE, "
        "reasoning, web search, and validated function calls."
    ),
)
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=False,
    allow_methods=["GET", "POST", "OPTIONS"],
    allow_headers=["*"],
    expose_headers=["retry-after", "x-request-id", "x-ratelimit-limit"],
)


def error_payload(problem: ApiProblem) -> dict[str, Any]:
    return {
        "error": {
            "message": problem.message,
            "type": problem.error_type,
            "param": problem.param,
            "code": problem.code,
        }
    }


def error_response(problem: ApiProblem, request_id: str | None = None) -> JSONResponse:
    headers = dict(problem.headers)
    if request_id:
        headers["x-request-id"] = request_id
    return JSONResponse(error_payload(problem), status_code=problem.status, headers=headers)


def client_ip(request: Request) -> str:
    forwarded = request.headers.get("x-forwarded-for", "")
    if forwarded:
        return forwarded.split(",", 1)[0].strip()
    return request.client.host if request.client else "unknown"


async def authorize(request: Request) -> None:
    if PUBLIC_ACCESS:
        return
    supplied = request.headers.get("authorization", "")
    expected = f"Bearer {PROVIDER_API_KEY}"
    if not PROVIDER_API_KEY or not hmac.compare_digest(supplied, expected):
        raise ApiProblem(
            "Invalid or missing API key.",
            401,
            "authentication_error",
            "invalid_api_key",
            headers={"WWW-Authenticate": "Bearer"},
        )


async def enforce_rate_limit(request: Request) -> None:
    if RATE_LIMIT_PER_MINUTE <= 0:
        return
    now = time.monotonic()
    key = client_ip(request)
    async with rate_lock:
        bucket = rate_buckets[key]
        while bucket and bucket[0] <= now - 60:
            bucket.popleft()
        if len(bucket) >= RATE_LIMIT_PER_MINUTE:
            retry_after = max(1, int(60 - (now - bucket[0])))
            raise ApiProblem(
                "Public gateway rate limit reached. Retry shortly.",
                429,
                "rate_limit_error",
                "rate_limit_exceeded",
                headers={"Retry-After": str(retry_after)},
            )
        bucket.append(now)


async def read_json_body(request: Request) -> dict[str, Any]:
    length = request.headers.get("content-length")
    if length:
        try:
            if int(length) > MAX_BODY_BYTES:
                raise ApiProblem(
                    f"Request exceeds the {MAX_BODY_MB} MB limit.",
                    413,
                    code="request_too_large",
                )
        except ValueError:
            pass
    body = await request.body()
    if len(body) > MAX_BODY_BYTES:
        raise ApiProblem(
            f"Request exceeds the {MAX_BODY_MB} MB limit.",
            413,
            code="request_too_large",
        )
    try:
        payload = json.loads(body)
    except (json.JSONDecodeError, UnicodeDecodeError) as exc:
        raise ApiProblem("Invalid JSON body.", code="invalid_json") from exc
    if not isinstance(payload, dict):
        raise ApiProblem("JSON body must be an object.", code="invalid_body")
    return payload


def parse_chat_request(payload: dict[str, Any]) -> ChatRequest:
    model_raw = payload.get("model")
    if not isinstance(model_raw, str) or not model_raw.strip():
        raise ApiProblem("The 'model' field is required.", param="model", code="missing_model")
    model = _resolve_model(model_raw)
    if model not in _MODELS:
        raise ApiProblem(
            f"Model {model_raw!r} does not exist. Use GET /v1/models.",
            404,
            code="model_not_found",
            param="model",
        )

    if payload.get("n", 1) != 1:
        raise ApiProblem("Only n=1 is supported.", param="n", code="unsupported_parameter")
    stream = payload.get("stream", False)
    if not isinstance(stream, bool):
        raise ApiProblem("'stream' must be a boolean.", param="stream")
    stream_options = payload.get("stream_options") or {}
    if not isinstance(stream_options, dict):
        raise ApiProblem("'stream_options' must be an object.", param="stream_options")
    include_usage = bool(stream_options.get("include_usage", False))

    temperature = payload.get("temperature")
    if temperature is not None:
        if isinstance(temperature, bool) or not isinstance(temperature, (int, float)):
            raise ApiProblem("'temperature' must be a number.", param="temperature")
        temperature = float(temperature)
        if not 0 <= temperature <= 2:
            raise ApiProblem("'temperature' must be between 0 and 2.", param="temperature")

    max_tokens = payload.get("max_completion_tokens", payload.get("max_tokens"))
    if max_tokens is not None:
        if isinstance(max_tokens, bool) or not isinstance(max_tokens, int) or max_tokens < 1:
            raise ApiProblem("'max_tokens' must be a positive integer.", param="max_tokens")
        model_limit = int(_MODELS[model]["max_tokens"])
        if max_tokens > model_limit:
            raise ApiProblem(
                f"'max_tokens' exceeds {model!r}'s {model_limit} token limit.",
                param="max_tokens",
                code="context_length_exceeded",
            )

    reasoning = payload.get("reasoning_effort")
    if reasoning is None and isinstance(payload.get("reasoning"), dict):
        reasoning = payload["reasoning"].get("effort")
    if reasoning is not None:
        valid = _MODELS[model].get("reasoning") or []
        if not isinstance(reasoning, str) or reasoning not in valid:
            raise ApiProblem(
                f"Invalid reasoning effort for {model!r}; choose one of {valid or ['none']}.",
                param="reasoning_effort",
            )

    search = payload.get("search", payload.get("web_search", payload.get("enable_search", False)))
    if not isinstance(search, bool):
        raise ApiProblem("'search' must be a boolean.", param="search")

    try:
        tools = parse_tool_configuration(payload)
    except ToolProtocolError as exc:
        raise ApiProblem(str(exc), param=exc.param, code=exc.code) from exc

    response_instruction = ""
    response_format = payload.get("response_format")
    if response_format is not None:
        if not isinstance(response_format, dict):
            raise ApiProblem("'response_format' must be an object.", param="response_format")
        fmt_type = response_format.get("type", "text")
        if fmt_type == "json_object":
            response_instruction = "Return only one valid JSON object, with no Markdown fences."
        elif fmt_type == "json_schema":
            schema_wrapper = response_format.get("json_schema")
            if not isinstance(schema_wrapper, dict):
                raise ApiProblem(
                    "'response_format.json_schema' must be an object.",
                    param="response_format.json_schema",
                )
            response_instruction = (
                "Return only JSON conforming to this response schema, with no Markdown fences:\n"
                + json.dumps(schema_wrapper, ensure_ascii=False, separators=(",", ":"))
            )
        elif fmt_type != "text":
            raise ApiProblem(
                f"Unsupported response format {fmt_type!r}.",
                param="response_format.type",
                code="unsupported_parameter",
            )

    instruction_parts = [part for part in (response_instruction, build_tool_instruction(tools)) if part]
    try:
        messages = normalize_messages(payload.get("messages"), "\n\n".join(instruction_parts))
    except ToolProtocolError as exc:
        raise ApiProblem(str(exc), param=exc.param, code=exc.code) from exc
    serialized_chars = len(json.dumps(messages, ensure_ascii=False))
    if serialized_chars > MAX_INPUT_CHARS:
        raise ApiProblem(
            f"Serialized messages exceed the {MAX_INPUT_CHARS} character limit.",
            413,
            code="input_too_large",
            param="messages",
        )

    return ChatRequest(
        model=model,
        messages=messages,
        stream=stream,
        include_usage=include_usage,
        temperature=temperature,
        max_tokens=max_tokens,
        reasoning=reasoning,
        search=search,
        tools=tools,
        response_instruction=response_instruction,
    )


def estimate_tokens(text: str) -> int:
    return max(1, round(len(text) / 4)) if text else 0


def usage_from_provider(provider: Any, messages: list[dict[str, str]], content: str, reasoning: str) -> dict[str, int]:
    last = getattr(provider, "last_usage", None)
    api_usage = getattr(last, "api_usage", None) if last else None
    if isinstance(api_usage, dict) and api_usage.get("total_tokens"):
        prompt = int(api_usage.get("prompt_tokens") or 0)
        completion = int(api_usage.get("completion_tokens") or 0)
        total = int(api_usage.get("total_tokens") or prompt + completion)
    else:
        prompt = estimate_tokens(json.dumps(messages, ensure_ascii=False))
        completion = estimate_tokens(content + reasoning)
        total = prompt + completion
    result: dict[str, Any] = {
        "prompt_tokens": prompt,
        "completion_tokens": completion,
        "total_tokens": total,
    }
    if reasoning:
        result["completion_tokens_details"] = {"reasoning_tokens": estimate_tokens(reasoning)}
    return result


def add_usage(a: dict[str, Any], b: dict[str, Any]) -> dict[str, int]:
    return {
        "prompt_tokens": int(a.get("prompt_tokens", 0)) + int(b.get("prompt_tokens", 0)),
        "completion_tokens": int(a.get("completion_tokens", 0)) + int(b.get("completion_tokens", 0)),
        "total_tokens": int(a.get("total_tokens", 0)) + int(b.get("total_tokens", 0)),
    }


def provider_stream(provider: Any, chat: ChatRequest, messages: list[dict[str, str]] | None = None):
    return provider.stream(
        messages=messages or chat.messages,
        model=chat.model,
        reasoning=chat.reasoning,
        search=chat.search,
        max_tokens=chat.max_tokens,
        temperature=chat.temperature,
    )


async def collect_once(chat: ChatRequest, messages: list[dict[str, str]]) -> GenerationResult:
    provider = provider_factory()
    content_parts: list[str] = []
    reasoning_parts: list[str] = []
    sources: list[dict[str, Any]] = []
    async with asyncio.timeout(UPSTREAM_TIMEOUT_SECONDS):
        async for event in provider_stream(provider, chat, messages):
            if event.kind == "content":
                content_parts.append(event.text)
            elif event.kind == "thinking":
                reasoning_parts.append(event.text)
            elif event.kind == "sources":
                try:
                    parsed = json.loads(event.text)
                    if isinstance(parsed, dict) and isinstance(parsed.get("sources"), list):
                        sources = parsed["sources"]
                except json.JSONDecodeError:
                    pass
            if sum(map(len, content_parts)) + sum(map(len, reasoning_parts)) > MAX_BUFFERED_OUTPUT_CHARS:
                raise ApiProblem(
                    "The buffered model output exceeded the server safety limit.",
                    502,
                    "server_error",
                    "output_too_large",
                )
    content = "".join(content_parts)
    reasoning = "".join(reasoning_parts)
    if not sources:
        sources = list(getattr(provider, "last_sources", []) or [])
    return GenerationResult(
        content=content,
        reasoning=reasoning,
        sources=sources,
        usage=usage_from_provider(provider, messages, content, reasoning),
    )


async def collect_with_retry(chat: ChatRequest, messages: list[dict[str, str]]) -> GenerationResult:
    last_error: Exception | None = None
    for attempt in range(UPSTREAM_RETRIES + 1):
        try:
            return await collect_once(chat, messages)
        except ApiProblem:
            raise
        except (UpstageError, TimeoutError, OSError) as exc:
            last_error = exc
            if attempt >= UPSTREAM_RETRIES:
                break
            logger.warning("upstream generation failed; retrying attempt=%s error=%s", attempt + 1, type(exc).__name__)
            await asyncio.sleep(min(2.0, 0.4 * (2**attempt)))
    assert last_error is not None
    raise last_error


def narrates_unemitted_tool_call(content: str, tools: ToolConfiguration) -> bool:
    """Detect Solar planning to call a tool but returning narration instead.

    This narrow heuristic is only used to trigger the bounded protocol retry. It
    avoids turning ordinary ``auto`` answers into forced calls.
    """
    text = " ".join(content.lower().split())
    if not text:
        return False
    mentions_catalog = any(tool.name.lower() in text for tool in tools.tools)
    intent_patterns = (
        r"\b(?:i|we)\s+(?:will|need to|should|must|have to)\s+(?:now\s+)?(?:use|call|invoke|read|write|edit|create)",
        r"\b(?:i'll|we'll)\s+(?:now\s+)?(?:use|call|invoke|read|write|edit|create)",
        r"\b(?:use|using|call|calling|invoke|invoking)\s+(?:the\s+)?[a-z0-9_-]+\s+(?:tool|function)\b",
        r"\b(?:respond|proceed)\s+with\s+(?:the\s+)?(?:a\s+)?tool call\b",
    )
    return mentions_catalog and any(re.search(pattern, text) for pattern in intent_patterns)


def last_mentioned_tool(content: str, tools: ToolConfiguration) -> str | None:
    """Return the catalog function mentioned latest in a narrated response."""
    lowered = content.lower()
    positions = [
        (lowered.rfind(tool.name.lower()), tool.name)
        for tool in tools.tools
        if lowered.rfind(tool.name.lower()) >= 0
    ]
    return max(positions, default=(-1, None))[1]


async def generate_buffered(chat: ChatRequest) -> GenerationResult:
    """Collect a response, validating/retrying prompt-level function calls."""
    messages = list(chat.messages)
    aggregate_usage: dict[str, Any] = {}
    last_problem: ToolProtocolError | None = None
    for attempt in range(TOOL_PROTOCOL_RETRIES + 1):
        result = await collect_with_retry(chat, messages)
        aggregate_usage = add_usage(aggregate_usage, result.usage)
        try:
            narrated_intent = narrates_unemitted_tool_call(result.content, chat.tools)
            try:
                calls = parse_generated_tool_calls(result.content, chat.tools)
            except ToolProtocolError:
                calls = (
                    parse_embedded_tool_calls(result.content, chat.tools)
                    if narrated_intent
                    else []
                )
                if not calls:
                    raise
            if not calls and narrated_intent:
                calls = parse_embedded_tool_calls(result.content, chat.tools)
                if not calls:
                    raise ToolProtocolError(
                        "The model narrated an intended tool call instead of emitting it.",
                        code="invalid_tool_output",
                    )
            if chat.tools.must_call and not calls:
                raise ToolProtocolError(
                    "The model did not emit the required function call.",
                    code="invalid_tool_output",
                )
            result.tool_calls = calls
            result.usage = aggregate_usage
            return result
        except ToolProtocolError as exc:
            last_problem = exc
            if attempt >= TOOL_PROTOCOL_RETRIES:
                break
            logger.warning("tool output validation failed; retrying attempt=%s error=%s", attempt + 1, str(exc)[:200])
            messages = [message.copy() for message in messages]
            target = chat.tools.required_name or last_mentioned_tool(
                result.content, chat.tools
            )
            target_text = (
                f" The required function is {target!r}." if target else ""
            )
            strict_retry = (
                "CORRECTION FOR THIS RETRY: A function call is now mandatory."
                f"{target_text} Return exactly one plain JSON object with keys "
                '"name" and "arguments", where "arguments" is a JSON object matching '
                "the function schema. The first character must be { and the last must "
                "be }. Do not use special tokens, XML, Markdown, explanation, planning, "
                "or apologies."
            )
            if messages and messages[0].get("role") == "system":
                messages[0]["content"] += "\n\n" + strict_retry
            else:
                messages.insert(0, {"role": "system", "content": strict_retry})
            # Do not replay the model's narration as an assistant turn: it tends to
            # anchor Solar into continuing the same prose. Retry from the original
            # conversation with one terse correction instead.
            messages.append(
                {
                    "role": "user",
                    "content": (
                        "TOOL GATEWAY VALIDATION ERROR: "
                        f"{exc}. Emit the function call now as one plain JSON object: "
                        '{"name":"FUNCTION_NAME","arguments":{}}. Return no prose.'
                    ),
                }
            )
    raise ApiProblem(
        f"Solar could not produce a valid function call after retry: {last_problem}",
        502,
        "server_error",
        "invalid_upstream_tool_call",
    )


def upstream_problem(exc: Exception) -> ApiProblem:
    if isinstance(exc, ApiProblem):
        return exc
    if isinstance(exc, (TimeoutError, asyncio.TimeoutError)):
        return ApiProblem(
            "Upstage timed out while generating the response.",
            504,
            "server_error",
            "upstream_timeout",
        )
    if isinstance(exc, UpstageAuthError):
        return ApiProblem(
            "Could not establish an anonymous Upstage Console session.",
            502,
            "server_error",
            "upstream_auth_error",
        )
    if isinstance(exc, (UpstageStreamError, UpstageError, OSError)):
        return ApiProblem(
            f"Upstage generation failed: {str(exc)[:240]}",
            502,
            "server_error",
            "upstream_error",
        )
    logger.exception("unexpected generation error", exc_info=exc)
    return ApiProblem(
        "Internal server error.", 500, "server_error", "internal_error"
    )


def model_object(model_id: str) -> dict[str, Any]:
    cfg = _MODELS[model_id]
    return {
        "id": model_id,
        "object": "model",
        "created": 0,
        "owned_by": "upstage",
        "permission": [],
        "capabilities": {
            "chat_completions": True,
            "streaming": True,
            "tools": True,
            "tool_transport": "validated_prompt_adapter",
            "reasoning": cfg.get("reasoning") or [],
            "web_search": bool(cfg.get("search")),
            "max_output_tokens": cfg.get("max_tokens"),
        },
    }


def chat_id() -> str:
    return f"chatcmpl-{uuid.uuid4().hex}"


def completion_json(chat: ChatRequest, result: GenerationResult, request_id: str) -> dict[str, Any]:
    message: dict[str, Any] = {"role": "assistant"}
    if result.tool_calls:
        message["content"] = None
        message["tool_calls"] = [call.as_openai() for call in result.tool_calls]
        finish_reason = "tool_calls"
    else:
        message["content"] = result.content
        finish_reason = "stop"
    if result.reasoning:
        message["reasoning_content"] = result.reasoning
    body: dict[str, Any] = {
        "id": chat_id(),
        "object": "chat.completion",
        "created": int(time.time()),
        "model": chat.model,
        "system_fingerprint": "upstage-console-zcode-v2",
        "choices": [{"index": 0, "message": message, "logprobs": None, "finish_reason": finish_reason}],
        "usage": result.usage,
    }
    if result.sources:
        body["sources"] = result.sources
    return body


def sse(data: dict[str, Any] | str) -> bytes:
    encoded = data if isinstance(data, str) else json.dumps(data, ensure_ascii=False, separators=(",", ":"))
    return f"data: {encoded}\n\n".encode("utf-8")


def stream_chunk(
    completion_id: str,
    created: int,
    model: str,
    delta: dict[str, Any],
    finish_reason: str | None = None,
    **extra: Any,
) -> dict[str, Any]:
    body: dict[str, Any] = {
        "id": completion_id,
        "object": "chat.completion.chunk",
        "created": created,
        "model": model,
        "system_fingerprint": "upstage-console-zcode-v2",
        "choices": [{"index": 0, "delta": delta, "logprobs": None, "finish_reason": finish_reason}],
    }
    body.update(extra)
    return body


async def buffered_sse(chat: ChatRequest, result: GenerationResult) -> AsyncGenerator[bytes, None]:
    cid, created = chat_id(), int(time.time())
    yield sse(stream_chunk(cid, created, chat.model, {"role": "assistant", "content": ""}))
    if result.sources:
        yield sse(stream_chunk(cid, created, chat.model, {}, sources=result.sources))
    if result.reasoning:
        for offset in range(0, len(result.reasoning), 512):
            yield sse(stream_chunk(cid, created, chat.model, {"reasoning_content": result.reasoning[offset:offset + 512]}))
    if result.tool_calls:
        for index, call in enumerate(result.tool_calls):
            item = call.as_openai()
            item["index"] = index
            yield sse(stream_chunk(cid, created, chat.model, {"tool_calls": [item]}))
        finish = "tool_calls"
    else:
        for offset in range(0, len(result.content), 512):
            yield sse(stream_chunk(cid, created, chat.model, {"content": result.content[offset:offset + 512]}))
        finish = "stop"
    yield sse(stream_chunk(cid, created, chat.model, {}, finish))
    if chat.include_usage:
        yield sse(
            {
                "id": cid,
                "object": "chat.completion.chunk",
                "created": created,
                "model": chat.model,
                "system_fingerprint": "upstage-console-zcode-v2",
                "choices": [],
                "usage": result.usage,
            }
        )
    yield sse("[DONE]")


async def acquire_slot() -> None:
    try:
        await asyncio.wait_for(request_slots.acquire(), QUEUE_TIMEOUT_SECONDS)
    except TimeoutError as exc:
        raise ApiProblem(
            "The gateway is busy. Retry shortly.",
            503,
            "server_error",
            "gateway_busy",
            headers={"Retry-After": "5"},
        ) from exc


async def prepare_realtime(chat: ChatRequest):
    """Open a provider stream and prefetch one event so early failures stay JSON."""
    last_error: Exception | None = None
    for attempt in range(UPSTREAM_RETRIES + 1):
        provider = provider_factory()
        iterator = provider_stream(provider, chat).__aiter__()
        try:
            first = await asyncio.wait_for(anext(iterator), UPSTREAM_TIMEOUT_SECONDS)
            return provider, iterator, first
        except StopAsyncIteration:
            return provider, iterator, StreamEvent("done", "")
        except (UpstageError, TimeoutError, OSError) as exc:
            last_error = exc
            try:
                await iterator.aclose()
            except Exception:
                pass
            if attempt >= UPSTREAM_RETRIES:
                break
            logger.warning("realtime upstream prefetch failed; retrying error=%s", type(exc).__name__)
            await asyncio.sleep(min(2.0, 0.4 * (2**attempt)))
    assert last_error is not None
    raise last_error


async def realtime_sse(
    chat: ChatRequest,
    provider: Any,
    iterator: Any,
    first: StreamEvent,
) -> AsyncGenerator[bytes, None]:
    cid, created = chat_id(), int(time.time())
    sources: list[dict[str, Any]] = []
    try:
        yield sse(stream_chunk(cid, created, chat.model, {"role": "assistant", "content": ""}))

        async def emit(event: StreamEvent):
            nonlocal sources
            if event.kind == "content":
                return sse(stream_chunk(cid, created, chat.model, {"content": event.text}))
            if event.kind == "thinking":
                return sse(stream_chunk(cid, created, chat.model, {"reasoning_content": event.text}))
            if event.kind == "sources":
                try:
                    parsed = json.loads(event.text)
                    sources = parsed.get("sources", []) if isinstance(parsed, dict) else []
                except json.JSONDecodeError:
                    sources = []
                return sse(stream_chunk(cid, created, chat.model, {}, sources=sources))
            return None

        chunk = await emit(first)
        if chunk:
            yield chunk
        async with asyncio.timeout(UPSTREAM_TIMEOUT_SECONDS):
            async for event in iterator:
                chunk = await emit(event)
                if chunk:
                    yield chunk
        yield sse(stream_chunk(cid, created, chat.model, {}, "stop"))
        if chat.include_usage:
            content = getattr(provider, "last_response", "") or ""
            reasoning = getattr(provider, "last_reasoning", "") or ""
            usage = usage_from_provider(provider, chat.messages, content, reasoning)
            yield sse(
                {
                    "id": cid,
                    "object": "chat.completion.chunk",
                    "created": created,
                    "model": chat.model,
                    "system_fingerprint": "upstage-console-zcode-v2",
                    "choices": [],
                    "usage": usage,
                }
            )
        yield sse("[DONE]")
    except asyncio.CancelledError:
        raise
    except Exception as exc:
        problem = upstream_problem(exc)
        logger.warning("stream failed code=%s error=%s", problem.code, problem.message[:240])
        yield sse(error_payload(problem))
        yield sse("[DONE]")
    finally:
        try:
            await iterator.aclose()
        except Exception:
            pass
        request_slots.release()


@app.get("/healthz", include_in_schema=False)
async def healthz() -> dict[str, Any]:
    return {"ok": True, "service": SERVICE_NAME, "version": "2.0.0"}


@app.get("/readyz", include_in_schema=False)
async def readyz() -> dict[str, Any]:
    # Upstream credential capture is intentionally lazy: a transient Upstage outage
    # must not cause Hugging Face to restart an otherwise healthy container.
    return {"ready": True, "upstream_credentials": "lazy"}


@app.get("/favicon.ico", include_in_schema=False)
async def favicon() -> Response:
    return Response(status_code=204)


@app.get("/v1/models")
async def list_models(request: Request) -> Response:
    try:
        await authorize(request)
        return JSONResponse({"object": "list", "data": [model_object(name) for name in _MODELS]})
    except ApiProblem as problem:
        return error_response(problem)


@app.get("/v1/models/{model_id:path}")
async def retrieve_model(model_id: str, request: Request) -> Response:
    try:
        await authorize(request)
        model = _resolve_model(model_id)
        if model not in _MODELS:
            raise ApiProblem(f"Model {model_id!r} was not found.", 404, code="model_not_found", param="model")
        return JSONResponse(model_object(model))
    except ApiProblem as problem:
        return error_response(problem)


@app.post("/v1/chat/completions")
async def chat_completions(request: Request) -> Response:
    request_id = request.headers.get("x-request-id") or f"req_{uuid.uuid4().hex}"
    slot_acquired = False
    try:
        await authorize(request)
        await enforce_rate_limit(request)
        payload = await read_json_body(request)
        chat = parse_chat_request(payload)
        await acquire_slot()
        slot_acquired = True

        # Tool-aware responses are buffered so malformed model protocol never leaks
        # into ZCode as ordinary text. Standard chat remains token-by-token realtime.
        if chat.tools.enabled:
            result = await generate_buffered(chat)
            request_slots.release()
            slot_acquired = False
            if chat.stream:
                return StreamingResponse(
                    buffered_sse(chat, result),
                    media_type="text/event-stream",
                    headers={
                        "Cache-Control": "no-cache",
                        "X-Accel-Buffering": "no",
                        "x-request-id": request_id,
                    },
                )
            return JSONResponse(
                completion_json(chat, result, request_id),
                headers={"x-request-id": request_id},
            )

        if chat.stream:
            provider, iterator, first = await prepare_realtime(chat)
            # realtime_sse owns and releases this slot from here onward.
            slot_acquired = False
            return StreamingResponse(
                realtime_sse(chat, provider, iterator, first),
                media_type="text/event-stream",
                headers={
                    "Cache-Control": "no-cache",
                    "X-Accel-Buffering": "no",
                    "x-request-id": request_id,
                },
            )

        result = await collect_with_retry(chat, chat.messages)
        request_slots.release()
        slot_acquired = False
        return JSONResponse(
            completion_json(chat, result, request_id),
            headers={"x-request-id": request_id},
        )
    except Exception as exc:
        if slot_acquired:
            request_slots.release()
        problem = upstream_problem(exc)
        logger.warning("request failed request_id=%s code=%s error=%s", request_id, problem.code, problem.message[:240])
        return error_response(problem, request_id)


@app.get("/", response_class=HTMLResponse, include_in_schema=False)
async def home() -> HTMLResponse:
    models = "".join(f"<code>{escape(name)}</code>" for name in _MODELS)
    return HTMLResponse(
        f"""<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>{escape(SERVICE_NAME)}</title><style>
:root{{--bg:#07111f;--card:#0d1b2e;--line:#203552;--text:#eaf2ff;--muted:#98abc7;--sun:#ffbf47;--ok:#53dda3}}*{{box-sizing:border-box}}body{{margin:0;min-height:100vh;background:radial-gradient(circle at 20% 0,#16335b 0,transparent 37%),var(--bg);color:var(--text);font:16px/1.55 ui-sans-serif,system-ui,sans-serif;display:grid;place-items:center;padding:28px}}main{{width:min(820px,100%);background:linear-gradient(145deg,rgba(18,40,70,.95),rgba(8,20,36,.98));border:1px solid var(--line);border-radius:24px;padding:clamp(26px,6vw,54px);box-shadow:0 30px 90px #0008}}.eyebrow{{color:var(--sun);font-weight:800;letter-spacing:.14em;text-transform:uppercase;font-size:.78rem}}h1{{font-size:clamp(2rem,6vw,4rem);line-height:1.02;margin:.35em 0}}p{{color:var(--muted);max-width:65ch}}.status{{display:inline-flex;align-items:center;gap:9px;color:var(--ok);font-weight:750}}.dot{{width:9px;height:9px;background:var(--ok);border-radius:50%;box-shadow:0 0 20px var(--ok)}}.grid{{display:grid;grid-template-columns:repeat(auto-fit,minmax(210px,1fr));gap:14px;margin:28px 0}}.box{{padding:18px;border:1px solid var(--line);border-radius:15px;background:#071423aa}}.box b{{display:block;margin-bottom:7px}}code{{display:inline-block;background:#06101d;border:1px solid var(--line);border-radius:8px;padding:5px 9px;margin:4px;color:#cbe0ff}}a{{color:#7db7ff}}
</style></head><body><main><div class="eyebrow">Upstage Solar · OpenAI compatible</div><h1>Built for ZCode.</h1><div class="status"><span class="dot"></span>Gateway healthy</div><p>Realtime Chat Completions, separated reasoning, optional web search, and schema-validated OpenAI function calls over the anonymous Upstage Console transport.</p><div class="grid"><div class="box"><b>Provider base URL</b><code>/v1</code></div><div class="box"><b>API key</b><code>public</code></div><div class="box"><b>Endpoints</b><a href="/v1/models">Models</a> · <a href="/docs">API docs</a></div></div><p>{models}</p><p><small>This is an independent compatibility gateway, not an official Upstage service.</small></p></main></body></html>"""
    )