diff-chat 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- adapters/README.md +28 -0
- adapters/__init__.py +48 -0
- adapters/_base.py +102 -0
- adapters/_cli.py +405 -0
- adapters/claude.py +141 -0
- adapters/gemini.py +323 -0
- adapters/gpt.py +217 -0
- adapters/local.py +146 -0
- adapters/registry.py +33 -0
- api_fallback.py +189 -0
- app.py +827 -0
- app_preferences.py +205 -0
- archive_schema.py +142 -0
- attachments.py +129 -0
- chat_titles.py +60 -0
- connection_handoff.py +64 -0
- context_engine.py +256 -0
- conversation_actions.py +160 -0
- diff_chat-0.1.0.dist-info/METADATA +101 -0
- diff_chat-0.1.0.dist-info/RECORD +91 -0
- diff_chat-0.1.0.dist-info/WHEEL +4 -0
- diff_chat-0.1.0.dist-info/entry_points.txt +2 -0
- diff_chat-0.1.0.dist-info/licenses/LICENSE +21 -0
- diff_chat_assets/memory.example.md +1 -0
- diff_chat_assets/prompts/about_you_export.md +19 -0
- diff_chat_assets/settings.json +6 -0
- diff_chat_assets/static/about-you-parser.js +46 -0
- diff_chat_assets/static/about-you.js +171 -0
- diff_chat_assets/static/actions.css +275 -0
- diff_chat_assets/static/actions.js +650 -0
- diff_chat_assets/static/app.css +345 -0
- diff_chat_assets/static/app.js +1344 -0
- diff_chat_assets/static/attachments.js +80 -0
- diff_chat_assets/static/brand/favicon-32.png +0 -0
- diff_chat_assets/static/brand/icon.svg +11 -0
- diff_chat_assets/static/brand/wordmark-dark.svg +15 -0
- diff_chat_assets/static/brand/wordmark-light.svg +13 -0
- diff_chat_assets/static/characters/CREDITS.md +7 -0
- diff_chat_assets/static/characters/characters.css +37 -0
- diff_chat_assets/static/characters/claude.json +507 -0
- diff_chat_assets/static/characters/claude.png +0 -0
- diff_chat_assets/static/characters/claude.webp +0 -0
- diff_chat_assets/static/characters/gemini.json +54 -0
- diff_chat_assets/static/characters/gemini.png +0 -0
- diff_chat_assets/static/characters/gemini.webp +0 -0
- diff_chat_assets/static/characters/gpt.json +507 -0
- diff_chat_assets/static/characters/gpt.png +0 -0
- diff_chat_assets/static/characters/gpt.webp +0 -0
- diff_chat_assets/static/characters/local.json +387 -0
- diff_chat_assets/static/characters/local.png +0 -0
- diff_chat_assets/static/characters/local.webp +0 -0
- diff_chat_assets/static/characters/player.js +318 -0
- diff_chat_assets/static/chat-filing.js +84 -0
- diff_chat_assets/static/controls.js +194 -0
- diff_chat_assets/static/corners.css +59 -0
- diff_chat_assets/static/craft.css +246 -0
- diff_chat_assets/static/drafts.js +41 -0
- diff_chat_assets/static/index.html +208 -0
- diff_chat_assets/static/library.css +30 -0
- diff_chat_assets/static/library.js +181 -0
- diff_chat_assets/static/memory.js +81 -0
- diff_chat_assets/static/preference-dialog.js +21 -0
- diff_chat_assets/static/preferences.css +56 -0
- diff_chat_assets/static/session.js +46 -0
- diff_chat_assets/static/settings.css +111 -0
- diff_chat_assets/static/settings.js +463 -0
- diff_chat_assets/static/setup.js +238 -0
- diff_chat_assets/static/utility.js +64 -0
- diff_chat_assets/static/vendor/LICENSES.txt +531 -0
- diff_chat_assets/static/vendor/highlight.min.js +1262 -0
- diff_chat_assets/static/vendor/markdown-it.min.js +13 -0
- diff_chat_assets/static/vendor/plex-mono.woff2 +0 -0
- diff_chat_assets/static/vendor/plex-sans.woff2 +0 -0
- diff_launcher.py +93 -0
- discussion.py +239 -0
- history_search.py +68 -0
- library_manager.py +251 -0
- model_options.py +132 -0
- plan_usage.py +72 -0
- private_store.py +71 -0
- probe.py +195 -0
- runtime_paths.py +195 -0
- server_security.py +100 -0
- setup_status.py +123 -0
- shared_memory.py +189 -0
- storage.py +185 -0
- usage_budget.py +77 -0
- usage_claude.py +110 -0
- usage_codex.py +170 -0
- usage_gemini.py +70 -0
- utility_models.py +104 -0
usage_codex.py
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
"""Read ChatGPT subscription limits through the official Codex app-server RPC."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import asyncio
|
|
5
|
+
from datetime import datetime, timezone
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
import tempfile
|
|
10
|
+
|
|
11
|
+
from adapters import (
|
|
12
|
+
CODEX_DISABLE, INSTALL, VERSIONS, ModelError, _environment, _Invocation,
|
|
13
|
+
_prepare_codex, _terminate,
|
|
14
|
+
)
|
|
15
|
+
from probe import find_cli
|
|
16
|
+
from app_preferences import VERSION
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _utc_now() -> str:
|
|
20
|
+
return datetime.now(timezone.utc).isoformat(timespec="seconds")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _unavailable(message: str) -> dict:
|
|
24
|
+
return {"status": "unavailable", "windows": [], "detail": message, "checked_at": _utc_now()}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _reset_time(seconds) -> str | None:
|
|
28
|
+
if type(seconds) not in (int, float) or seconds <= 0:
|
|
29
|
+
return None
|
|
30
|
+
try:
|
|
31
|
+
return datetime.fromtimestamp(seconds, timezone.utc).isoformat(timespec="seconds")
|
|
32
|
+
except (ValueError, OverflowError, OSError):
|
|
33
|
+
return None
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _window_name(minutes, kind: str) -> str:
|
|
37
|
+
if type(minutes) is not int or minutes <= 0:
|
|
38
|
+
return f"{kind.title()} window"
|
|
39
|
+
if minutes == 10080:
|
|
40
|
+
return "Weekly"
|
|
41
|
+
if minutes % 1440 == 0:
|
|
42
|
+
return f"{minutes // 1440}-day window"
|
|
43
|
+
if minutes % 60 == 0:
|
|
44
|
+
return f"{minutes // 60}-hour window"
|
|
45
|
+
return f"{minutes}-minute window"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _format_limits(result: dict) -> dict:
|
|
49
|
+
# rateLimits is the compatibility copy of the main bucket. Prefer the
|
|
50
|
+
# keyed collection and append the legacy main bucket only if it is absent.
|
|
51
|
+
buckets = result.get("rateLimitsByLimitId")
|
|
52
|
+
buckets = dict(buckets) if isinstance(buckets, dict) else {}
|
|
53
|
+
main = result.get("rateLimits")
|
|
54
|
+
if isinstance(main, dict):
|
|
55
|
+
main_id = main.get("limitId") or "codex"
|
|
56
|
+
if isinstance(main_id, str):
|
|
57
|
+
buckets.setdefault(main_id, main)
|
|
58
|
+
windows = []
|
|
59
|
+
for key in sorted(buckets, key=lambda item: (item != "codex", item)):
|
|
60
|
+
snapshot = buckets[key]
|
|
61
|
+
if not isinstance(snapshot, dict):
|
|
62
|
+
continue
|
|
63
|
+
name = snapshot.get("limitName") or key
|
|
64
|
+
for kind in ("primary", "secondary"):
|
|
65
|
+
record = snapshot.get(kind)
|
|
66
|
+
if not isinstance(record, dict):
|
|
67
|
+
continue
|
|
68
|
+
used = record.get("usedPercent")
|
|
69
|
+
if type(used) not in (int, float) or not 0 <= used <= 100:
|
|
70
|
+
continue
|
|
71
|
+
label = _window_name(record.get("windowDurationMins"), kind)
|
|
72
|
+
if key != "codex":
|
|
73
|
+
label = f"{name} · {label}"
|
|
74
|
+
windows.append({"label": label, "remaining_percent": 100 - used,
|
|
75
|
+
"reset_at": _reset_time(record.get("resetsAt"))})
|
|
76
|
+
if not windows:
|
|
77
|
+
return _unavailable("Codex did not report a plan usage window for this account.")
|
|
78
|
+
detail = None
|
|
79
|
+
if result.get("ordinaryUsageAllowed") is False:
|
|
80
|
+
detail = "Codex reports that included usage is currently unavailable."
|
|
81
|
+
return {"status": "available", "windows": windows, "detail": detail, "checked_at": _utc_now()}
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
async def _query_server(call: _Invocation) -> dict:
|
|
85
|
+
# No thread or model turn is created. The stdio connection performs only
|
|
86
|
+
# the handshake and the provider's read-only account/rateLimits/read method.
|
|
87
|
+
args = ["--no-daemon", "-a", "never", "-s", "read-only", "app-server",
|
|
88
|
+
"--stdio", "--strict-config", "-c", f'cli_auth_credentials_store="{call.codex_store}"',
|
|
89
|
+
"-c", 'forced_login_method="chatgpt"', "-c", "analytics.enabled=false",
|
|
90
|
+
"-c", 'chatgpt_base_url="https://chatgpt.com/backend-api/"',
|
|
91
|
+
"-c", "mcp_servers={}", "-c", "agents.enabled=false"]
|
|
92
|
+
for feature in CODEX_DISABLE:
|
|
93
|
+
args.extend(["--disable", feature])
|
|
94
|
+
spawn = asyncio.create_task(asyncio.create_subprocess_exec(
|
|
95
|
+
*call.prefix, call.binary, *args, cwd=call.cwd, env=call.env,
|
|
96
|
+
stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE,
|
|
97
|
+
stderr=asyncio.subprocess.DEVNULL, start_new_session=os.name == "posix",
|
|
98
|
+
limit=2 * 1024 * 1024,
|
|
99
|
+
))
|
|
100
|
+
try:
|
|
101
|
+
process = await asyncio.shield(spawn)
|
|
102
|
+
except asyncio.CancelledError:
|
|
103
|
+
await _terminate(await spawn)
|
|
104
|
+
raise
|
|
105
|
+
|
|
106
|
+
async def send(message: dict) -> None:
|
|
107
|
+
process.stdin.write(json.dumps(message).encode() + b"\n")
|
|
108
|
+
await process.stdin.drain()
|
|
109
|
+
|
|
110
|
+
async def response(request_id: int) -> dict:
|
|
111
|
+
while line := await process.stdout.readline():
|
|
112
|
+
message = json.loads(line)
|
|
113
|
+
if not isinstance(message, dict) or message.get("id") != request_id:
|
|
114
|
+
continue
|
|
115
|
+
error = message.get("error")
|
|
116
|
+
if error:
|
|
117
|
+
# Avoid returning raw server errors or account objects to the UI.
|
|
118
|
+
diagnostic = str(error).lower()
|
|
119
|
+
if any(word in diagnostic for word in ("authentication", "unauthorized", "401")):
|
|
120
|
+
raise ModelError("Sign in again with codex login to read ChatGPT usage.")
|
|
121
|
+
if "429" in diagnostic:
|
|
122
|
+
raise ModelError("Codex is rate-limiting usage checks. Try again shortly.")
|
|
123
|
+
raise ModelError("Codex could not retrieve usage from ChatGPT.")
|
|
124
|
+
data = message.get("result")
|
|
125
|
+
if isinstance(data, dict):
|
|
126
|
+
return data
|
|
127
|
+
break
|
|
128
|
+
raise ModelError("Codex ended the usage check without a result.")
|
|
129
|
+
|
|
130
|
+
try:
|
|
131
|
+
await send({"id": 1, "method": "initialize", "params": {
|
|
132
|
+
"clientInfo": {"name": "diff", "version": VERSION},
|
|
133
|
+
"capabilities": {"explicitGatewayOauth": True},
|
|
134
|
+
}})
|
|
135
|
+
await response(1)
|
|
136
|
+
await send({"method": "initialized"})
|
|
137
|
+
await send({"id": 2, "method": "account/rateLimits/read",
|
|
138
|
+
"params": {"excludeResetCreditDetails": True}})
|
|
139
|
+
return await response(2)
|
|
140
|
+
finally:
|
|
141
|
+
await _terminate(process)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
async def get_codex_usage() -> dict:
|
|
145
|
+
"""Get the provider's timestamped plan percentages without requesting inference."""
|
|
146
|
+
binary = find_cli("codex")
|
|
147
|
+
if not binary:
|
|
148
|
+
return _unavailable(f"Install Codex with {INSTALL['gpt']}.")
|
|
149
|
+
try:
|
|
150
|
+
async with asyncio.timeout(12):
|
|
151
|
+
with tempfile.TemporaryDirectory(prefix="transcript-codex-usage-") as directory:
|
|
152
|
+
root = Path(directory).resolve()
|
|
153
|
+
cwd, home = root / "workspace", root / "codex"
|
|
154
|
+
cwd.mkdir()
|
|
155
|
+
home.mkdir(mode=0o700)
|
|
156
|
+
env = _environment(root, "gpt")
|
|
157
|
+
account_home = Path(env["CODEX_HOME"]).expanduser().resolve()
|
|
158
|
+
env["CODEX_HOME"] = str(home)
|
|
159
|
+
call = _Invocation(str(Path(binary).absolute()), cwd, env)
|
|
160
|
+
code, version = await call.execute(["--version"])
|
|
161
|
+
if code or version.decode(errors="replace").strip() != VERSIONS["gpt"]:
|
|
162
|
+
return _unavailable(f"Usage needs {VERSIONS['gpt']}. Install with {INSTALL['gpt']}.")
|
|
163
|
+
await _prepare_codex(call, account_home)
|
|
164
|
+
return _format_limits(await _query_server(call))
|
|
165
|
+
except TimeoutError:
|
|
166
|
+
return _unavailable("The ChatGPT usage check timed out.")
|
|
167
|
+
except ModelError as error:
|
|
168
|
+
return _unavailable(error.message)
|
|
169
|
+
except (OSError, ValueError, ExceptionGroup):
|
|
170
|
+
return _unavailable("The local Codex usage check could not complete.")
|
usage_gemini.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Read the official Antigravity CLI's standalone /usage command (zero model turns)."""
|
|
2
|
+
import asyncio
|
|
3
|
+
from datetime import datetime, timezone
|
|
4
|
+
import json
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
from adapters.gemini import ModelError, find_cli, isolated, policy_args
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def windows_from_report(report):
|
|
11
|
+
if not isinstance(report, dict) or report.get("status") != "SUCCESS" or report.get("num_turns") != 0:
|
|
12
|
+
return []
|
|
13
|
+
command = report.get("command")
|
|
14
|
+
if not isinstance(command, dict) or command.get("name") != "usage":
|
|
15
|
+
return []
|
|
16
|
+
data = command.get("data")
|
|
17
|
+
if not isinstance(data, dict) or not isinstance(data.get("groups"), list):
|
|
18
|
+
return []
|
|
19
|
+
windows, seen = [], set()
|
|
20
|
+
for group in data["groups"]:
|
|
21
|
+
if not isinstance(group, dict) or not isinstance(group.get("buckets"), list):
|
|
22
|
+
continue
|
|
23
|
+
group_name = group.get("name", "")
|
|
24
|
+
gemini_group = isinstance(group_name, str) and re.fullmatch(r"Gemini(?: [a-zA-Z0-9 .-]{1,48})?", group_name)
|
|
25
|
+
for bucket in group["buckets"]:
|
|
26
|
+
if not isinstance(bucket, dict) or bucket.get("disabled"):
|
|
27
|
+
continue
|
|
28
|
+
key, fraction = bucket.get("id"), bucket.get("remaining_fraction")
|
|
29
|
+
if not isinstance(key, str) or not re.fullmatch(r"[a-z0-9-]{1,64}", key) or key in seen:
|
|
30
|
+
continue
|
|
31
|
+
if not gemini_group and not key.startswith("gemini-"):
|
|
32
|
+
continue
|
|
33
|
+
if type(fraction) not in (float, int) or not 0 <= fraction <= 1:
|
|
34
|
+
continue
|
|
35
|
+
period = bucket.get("window")
|
|
36
|
+
if not isinstance(period, str) or not re.fullmatch(r"[a-zA-Z0-9 _-]{1,40}", period):
|
|
37
|
+
continue
|
|
38
|
+
period = period.lower().replace("_", "-")
|
|
39
|
+
if key.endswith("-5h") or period in {"5h", "5-hour", "5-hours", "five-hour", "five-hours", "fivehour"}:
|
|
40
|
+
label = "5-hour limit"
|
|
41
|
+
else:
|
|
42
|
+
label = period.capitalize() + " limit"
|
|
43
|
+
if gemini_group and group_name.casefold() not in {"gemini", "gemini models"}:
|
|
44
|
+
label += " · " + group_name
|
|
45
|
+
reset = bucket.get("reset_time")
|
|
46
|
+
try:
|
|
47
|
+
stamp = datetime.fromisoformat(reset) if isinstance(reset, str) else None
|
|
48
|
+
reset = stamp.astimezone(timezone.utc).isoformat() if stamp and stamp.tzinfo else None
|
|
49
|
+
except (ValueError, OverflowError):
|
|
50
|
+
reset = None
|
|
51
|
+
seen.add(key)
|
|
52
|
+
windows.append({"label": label, "remaining_percent": round(fraction * 100, 2), "reset_at": reset})
|
|
53
|
+
return windows
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
async def get_gemini_usage():
|
|
57
|
+
windows = []
|
|
58
|
+
detail = "Install Antigravity CLI to check plan usage."
|
|
59
|
+
if binary := find_cli("agy"):
|
|
60
|
+
try:
|
|
61
|
+
async with asyncio.timeout(12), isolated(binary) as call:
|
|
62
|
+
code, raw = await call.execute([*policy_args(builtin_command=True), "--output-format", "json",
|
|
63
|
+
"--print-timeout", "8s", "-p", "/usage"])
|
|
64
|
+
if not code:
|
|
65
|
+
windows = windows_from_report(json.loads(raw))
|
|
66
|
+
detail = None if windows else "No Gemini quota window reported. Check your Google sign-in or use /usage in Antigravity."
|
|
67
|
+
except (TimeoutError, OSError, ValueError, ModelError):
|
|
68
|
+
detail = "Couldn’t refresh Gemini usage. Check your Antigravity connection and try again."
|
|
69
|
+
return {"status": "available" if windows else "unavailable", "windows": windows, "detail": detail,
|
|
70
|
+
"checked_at": datetime.now(timezone.utc).isoformat()}
|
utility_models.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""Independent model preference for automatic and carry-forward summaries."""
|
|
2
|
+
from typing import Literal
|
|
3
|
+
from adapters import REGISTRY
|
|
4
|
+
from app_preferences import Provider
|
|
5
|
+
from fastapi import APIRouter, HTTPException
|
|
6
|
+
from pydantic import BaseModel, Field
|
|
7
|
+
|
|
8
|
+
import private_store
|
|
9
|
+
import storage
|
|
10
|
+
from model_options import get_model_options
|
|
11
|
+
|
|
12
|
+
router = APIRouter()
|
|
13
|
+
AUTO = {"provider": "auto"}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class UtilityEdit(BaseModel):
|
|
17
|
+
provider: Literal["auto"] | Provider
|
|
18
|
+
model: str = Field(default="", max_length=120)
|
|
19
|
+
effort: str = Field(default="", max_length=32)
|
|
20
|
+
revision: str = Field(min_length=64, max_length=64)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def supported(options, provider, model, effort):
|
|
24
|
+
return any(item["id"] == model and effort in item["efforts"]
|
|
25
|
+
for item in options.get(provider, {}).get("models", []))
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def select_utility(options, enabled, choices):
|
|
29
|
+
preferred = private_store.read("summary-model", AUTO)
|
|
30
|
+
provider = preferred.get("provider")
|
|
31
|
+
if (provider in enabled and
|
|
32
|
+
supported(options, provider, preferred.get("model"), preferred.get("effort"))):
|
|
33
|
+
return provider, {"model": preferred["model"], "effort": preferred["effort"]}
|
|
34
|
+
return automatic_choice(options, enabled, choices)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def automatic_choice(options, enabled, choices):
|
|
38
|
+
# Resolve against the current CLI catalog. Keep smaller families ahead of frontier options.
|
|
39
|
+
for family in ("haiku", "nano", "mini", "luna", "sol", "flash", "sonnet"):
|
|
40
|
+
for name in enabled:
|
|
41
|
+
for item in options.get(name, {}).get("models", []):
|
|
42
|
+
if family in item["id"].lower().split("-") and item["efforts"]:
|
|
43
|
+
effort = next((v for v in ("low", "minimal", "default") if v in item["efforts"]), item["efforts"][0])
|
|
44
|
+
return name, {"model": item["id"], "effort": effort}
|
|
45
|
+
name = next((key for key in enabled if options.get(key, {}).get("models")), None)
|
|
46
|
+
if name is None:
|
|
47
|
+
# Older clients allow an installed CLI to select its own model.
|
|
48
|
+
name = next((key for key in enabled if key in REGISTRY and key not in options), None)
|
|
49
|
+
if name is None:
|
|
50
|
+
return None
|
|
51
|
+
choice = dict(choices.get(name, {}))
|
|
52
|
+
if not choice:
|
|
53
|
+
group = options.get(name, {})
|
|
54
|
+
default = next((item for item in group.get("models", []) if item["id"] == group.get("default_model")), None)
|
|
55
|
+
if default:
|
|
56
|
+
choice = {"model": default["id"], "effort": default["default_effort"]}
|
|
57
|
+
# Even a catalog with a single model can have a lower effort for utility work.
|
|
58
|
+
for item in options.get(name, {}).get("models", []):
|
|
59
|
+
if item["id"] == choice.get("model") and "low" in item["efforts"]:
|
|
60
|
+
choice["effort"] = "low"
|
|
61
|
+
return name, choice
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@router.get("/api/utility-model")
|
|
65
|
+
def current():
|
|
66
|
+
return private_store.snapshot(private_store.read("summary-model", AUTO))
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@router.get("/api/utility-model/automatic")
|
|
70
|
+
async def preview(claude: bool | None = None, gpt: bool | None = None, chat_id: str = "", models: str | None = None):
|
|
71
|
+
if models is not None:
|
|
72
|
+
selected = set(filter(None, models.split(",")))
|
|
73
|
+
if selected - REGISTRY.keys():
|
|
74
|
+
raise HTTPException(400, "Unknown participant.")
|
|
75
|
+
enabled = [key for key in REGISTRY if key in selected]
|
|
76
|
+
elif claude is not None or gpt is not None:
|
|
77
|
+
# Query format used by the original two-participant interface.
|
|
78
|
+
enabled = [name for name, on in (("claude", claude), ("gpt", gpt)) if on is not False]
|
|
79
|
+
else:
|
|
80
|
+
enabled = list(REGISTRY)
|
|
81
|
+
if not enabled:
|
|
82
|
+
return {}
|
|
83
|
+
options = await get_model_options()
|
|
84
|
+
choices = {}
|
|
85
|
+
if chat_id:
|
|
86
|
+
try:
|
|
87
|
+
choices = storage.read(chat_id).get("preferences", {})
|
|
88
|
+
except FileNotFoundError:
|
|
89
|
+
raise HTTPException(404, "Chat not found.")
|
|
90
|
+
selected = automatic_choice(options, enabled, choices)
|
|
91
|
+
if not selected:
|
|
92
|
+
return {}
|
|
93
|
+
provider, choice = selected
|
|
94
|
+
return {"provider": provider, **choice}
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@router.patch("/api/utility-model")
|
|
98
|
+
async def save(change: UtilityEdit):
|
|
99
|
+
value = AUTO
|
|
100
|
+
if change.provider != "auto":
|
|
101
|
+
if not supported(await get_model_options(), change.provider, change.model, change.effort):
|
|
102
|
+
raise HTTPException(400, "Choose a model and reasoning level from the current catalog.")
|
|
103
|
+
value = {"provider": change.provider, "model": change.model, "effort": change.effort}
|
|
104
|
+
return private_store.update("summary-model", value, AUTO, change.revision)
|