#!/usr/bin/env -S fragletc --image ofthemachine/python3@sha256:a015b4f9f0e7c1648f8fcd4164f6a296dd3c9189404f88f333a9764d08d13522
#: d=One Cohere chat completion (api.cohere.com/v2/chat) from a prompt file or inline prompt, with an optional system prompt file, written to response.md. The host is fixed -- there is no base-URL parameter -- so the API key can only ever be sent to Cohere. seed makes sampling best-effort reproducible; stdout is a one-line summary (model, seed, tokens, finish reason), never the completion.
#: when=Use when a workflow step needs text generated by a language model -- a poem, a caption, a summary -- from a prompt file, and a Cohere API key (free trial keys work) is available.
#: network=required
#: stdin=none
#: secret=COHERE_API_KEY:d=Cohere API key (trial keys: 1,000 calls/month)
#: param=prompt:file:d=Prompt file (the user message)
#: param=prompt_text:d=Inline prompt, when there is no prompt file
#: param=system:file:d=System prompt file
#: param=model:default=command-a-03-2025:d=Cohere model id
#: param=temperature:default=0.7:d=Sampling temperature, 0 to 1
#: param=seed:default=42:d=Sampling seed; same seed and inputs give best-effort identical output
#: param=max_tokens:default=1024:d=Maximum tokens to generate (a thinking model's thinking counts)
#: param=thinking_budget:d=For a thinking model (e.g. command-a-plus-05-2026): the most tokens it may think before answering, so the answer fits max_tokens; empty: the model's default
#: output=response.md
import json
import os
import sys
import urllib.error
import urllib.request

ENDPOINT = "https://api.cohere.com/v2/chat"


def fail(msg, code=1):
    print(f"Error: {msg}", file=sys.stderr)
    sys.exit(code)


# EX_TEMPFAIL: a rate limit, a server error or a dropped connection may pass,
# so fragletc --retry runs the call again; any other failure is final.
TEMPFAIL = 75


if os.environ.get("PROMPT"):
    prompt = open(os.environ["PROMPT"], encoding="utf-8").read()
else:
    prompt = os.environ.get("PROMPT_TEXT", "")
if not prompt.strip():
    fail("no prompt: pass prompt=<file> or prompt_text=<text>")

messages = []
if os.environ.get("SYSTEM"):
    messages.append({"role": "system", "content": open(os.environ["SYSTEM"], encoding="utf-8").read()})
messages.append({"role": "user", "content": prompt})

model = os.environ["MODEL"]
seed = int(os.environ["SEED"])
body = {
    "model": model,
    "messages": messages,
    "temperature": float(os.environ["TEMPERATURE"]),
    "seed": seed,
    "max_tokens": int(os.environ["MAX_TOKENS"]),
}
if os.environ.get("THINKING_BUDGET"):
    body["thinking"] = {"type": "enabled", "token_budget": int(os.environ["THINKING_BUDGET"])}
key = open(os.environ["COHERE_API_KEY_FILE"], encoding="utf-8").read().strip()
req = urllib.request.Request(
    ENDPOINT,
    data=json.dumps(body).encode(),
    headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json", "Accept": "application/json"},
)
try:
    # a long draft can take Cohere over two minutes
    with urllib.request.urlopen(req, timeout=300) as resp:
        res = json.load(resp)
except urllib.error.HTTPError as e:
    fail(f"Cohere returned HTTP {e.code}: {e.read(500).decode('utf-8', 'replace')}",
         TEMPFAIL if e.code == 429 or e.code >= 500 else 1)
except (urllib.error.URLError, TimeoutError) as e:
    fail(f"Cohere request failed: {e}", TEMPFAIL)

parts = (res.get("message") or {}).get("content")
text = "".join(p.get("text", "") for p in parts or [] if p.get("type") == "text")
if not text.strip():
    fail(f"no text in response: {json.dumps(res)[:300]}")

with open("/output/response.md", "w", encoding="utf-8") as f:
    f.write(text.strip() + "\n")

units = (res.get("usage") or {}).get("billed_units") or {}
print(f"model={model} seed={seed} input_tokens={units.get('input_tokens')} "
      f"output_tokens={units.get('output_tokens')} finish={res.get('finish_reason')} -> response.md")
