Datasets:

Modalities:
Text
Languages:
English
Size:
< 1K
ArXiv:
Libraries:
Datasets
Harbor
License:
File size: 5,363 Bytes
5873600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Public, dependency-free client for one evaluated team seat."""

from __future__ import annotations

import argparse
import json
import os
import sys
import urllib.error
import urllib.request
from pathlib import Path


def request(path: str, payload: dict | None = None, *, timeout: float = 40) -> dict:
    base = os.environ.get("TEAM_URL", "http://team:8000").rstrip("/")
    data = None if payload is None else json.dumps(payload, allow_nan=False).encode()
    req = urllib.request.Request(base + path, data=data, headers={"Content-Type": "application/json"})
    try:
        with urllib.request.urlopen(req, timeout=timeout) as response:
            return json.load(response)
    except urllib.error.HTTPError as error:
        try:
            detail = json.load(error).get("error", str(error.code))
        except (ValueError, AttributeError):
            detail = str(error.code)
        raise RuntimeError(f"Team rejected action ({error.code}): {detail}") from None


def main(argv: list[str] | None = None) -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    sub = parser.add_subparsers(dest="command", required=True)
    read = sub.add_parser("read", help="Read your pending request without consuming it")
    read.add_argument("--wait", type=float, default=0)
    for name in ("say", "answer", "tool", "tools"):
        command = sub.add_parser(name)
        command.add_argument("--request-id", required=True)
        if name == "tool":
            command.add_argument("name")
            command.add_argument("--arguments-json", required=True)
        elif name == "tools":
            command.add_argument("--calls-json", required=True,
                                 help='Array of {"name": NAME, "input": OBJECT}; native tool handling still applies')
        else:
            command.add_argument("text", nargs="?")
            command.add_argument("--file", type=Path)
            if name == "answer":
                command.add_argument("--reasoning", default="")
                command.add_argument("--structured-json", action="store_true",
                                     help='Input is the complete {"answer": ..., "reasoning": ...} object')
    args = parser.parse_args(argv)
    try:
        if args.command == "read":
            if not 0 <= args.wait <= 30:
                parser.error("--wait must be between 0 and 30 seconds")
            result = request(f"/read?wait={args.wait}", timeout=args.wait + 10)
        else:
            payload = {"request_id": args.request_id}
            if args.command == "tools":
                calls = json.loads(args.calls_json)
                if not isinstance(calls, list) or not calls:
                    parser.error("--calls-json must be a non-empty JSON array")
                normalized = []
                for index, call in enumerate(calls):
                    if (not isinstance(call, dict) or set(call) != {"name", "input"}
                            or not isinstance(call["name"], str) or not call["name"]
                            or not isinstance(call["input"], dict)):
                        parser.error('Each tool call must contain only "name" (string) and "input" (object)')
                    normalized.append({**call, "id": f"{args.request_id}_tool_{index}"})
                payload.update(kind="tool", tool_calls=normalized)
            elif args.command == "tool":
                arguments = json.loads(args.arguments_json)
                if not isinstance(arguments, dict):
                    parser.error("--arguments-json must be a JSON object")
                payload.update(kind="tool", name=args.name, arguments=arguments)
            else:
                if args.file and args.text is not None:
                    parser.error("Supply text or --file, not both")
                value = args.file.read_text() if args.file else args.text
                if value is None:
                    value = sys.stdin.read()
                if args.command == "answer" and not value.strip():
                    parser.error("A non-empty final answer is required: supply ANSWER, --file, or stdin; --reasoning alone is not an answer")
                if args.command == "answer" and args.structured_json:
                    structured = json.loads(value)
                    if (args.reasoning or not isinstance(structured, dict)
                            or set(structured) != {"answer", "reasoning"}
                            or not isinstance(structured["answer"], str) or not structured["answer"].strip()
                            or not isinstance(structured["reasoning"], str)):
                        parser.error('--structured-json needs exactly a non-empty string "answer" and string "reasoning"; do not also supply --reasoning')
                    text = json.dumps(structured, allow_nan=False)
                else:
                    text = json.dumps({"answer": value, "reasoning": args.reasoning}) if args.command == "answer" else value
                payload.update(kind="final_answer" if args.command == "answer" else "message", text=text)
            result = request("/reply", payload)
        print(json.dumps(result, ensure_ascii=False, allow_nan=False))
    except (RuntimeError, OSError, ValueError) as error:
        parser.exit(1, str(error) + "\n")


if __name__ == "__main__":
    main()