litesquad 0.0.1__tar.gz

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.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,55 @@
1
+ Metadata-Version: 2.4
2
+ Name: litesquad
3
+ Version: 0.0.1
4
+ Summary: Lightweight tool for working with a team of LLMs
5
+ Author: EricThomson
6
+ Author-email: EricThomson <thomson.eric@gmail.com>
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Requires-Dist: litellm>=1.90.1
10
+ Requires-Dist: pydantic>=2.13.4
11
+ Requires-Dist: python-dotenv>=1.0.0
12
+ Requires-Dist: rich>=15.0.0
13
+ Requires-Dist: typer>=0.26.8
14
+ Requires-Dist: dash>=3.0,<4.2 ; extra == 'web'
15
+ Requires-Python: >=3.12
16
+ Project-URL: Repository, https://github.com/EricThomson/litesquad
17
+ Provides-Extra: web
18
+ Description-Content-Type: text/markdown
19
+
20
+ # lite squad
21
+ Tool for working with a team of LLMs. Sometimes two, or five, heads are better than one.
22
+
23
+ ## Usage
24
+ Install with pip:
25
+
26
+ pip install litesquad
27
+
28
+ Use in browser:
29
+
30
+ litesquad --web
31
+
32
+ Use at command line:
33
+
34
+ litesquad "plan such and such project"
35
+ litesquad "such and such" --quick # get a quick answer, bypassing the squad
36
+
37
+ litesquad takes a few minutes to run when not in deep think mode. There's a lot of LLM calls going on under the hood (see below).
38
+
39
+ Query is distributed to worker LLMs (gemini and sonnet direct, plus deepseek, mistral, and llama via OpenRouter). Another (grok) acts as a critic that gives feedback to the workers. They revise their response. An intermediate representation of these responses is extracted to pull the content and clustered into categories of suggestions (gpt5). A judge (opus) converts these suggestions into a final coherent answer for the user.
40
+
41
+ To run the default, you will need API keys for [Gemini](https://aistudio.google.com/app/apikey), [OpenAI](https://openai.com/index/openai-api/), [Anthropic](https://platform.claude.com/docs/en/api/admin/api_keys/retrieve), and [OpenRouter](https://openrouter.ai/keys). One OpenRouter key reaches the whole openrouter.ai catalog (deepseek, mistral, llama, grok, qwen, ...), which is how the worker roster grows wide without a key per provider. You can store your API keys in `.env`.
42
+
43
+ ### Basic tests
44
+ To see if api keys are working (from activated env): `python -m litesquad.check_keys`
45
+
46
+ Check on specific models: `litesquad --check`
47
+
48
+ Offline test: `litesquad --smoke --mock`
49
+
50
+
51
+ ### Caveats
52
+ This provides an interface to an ensemble of LLMs to try to generate a better answer than when using a single LLM. No agentic tool-usage, such as web calls, from the LLMs. Just vanilla text processing.
53
+
54
+ With apologies to [squad](https://github.com/bradygaster/squad).
55
+
@@ -0,0 +1,36 @@
1
+ # lite squad
2
+ Tool for working with a team of LLMs. Sometimes two, or five, heads are better than one.
3
+
4
+ ## Usage
5
+ Install with pip:
6
+
7
+ pip install litesquad
8
+
9
+ Use in browser:
10
+
11
+ litesquad --web
12
+
13
+ Use at command line:
14
+
15
+ litesquad "plan such and such project"
16
+ litesquad "such and such" --quick # get a quick answer, bypassing the squad
17
+
18
+ litesquad takes a few minutes to run when not in deep think mode. There's a lot of LLM calls going on under the hood (see below).
19
+
20
+ Query is distributed to worker LLMs (gemini and sonnet direct, plus deepseek, mistral, and llama via OpenRouter). Another (grok) acts as a critic that gives feedback to the workers. They revise their response. An intermediate representation of these responses is extracted to pull the content and clustered into categories of suggestions (gpt5). A judge (opus) converts these suggestions into a final coherent answer for the user.
21
+
22
+ To run the default, you will need API keys for [Gemini](https://aistudio.google.com/app/apikey), [OpenAI](https://openai.com/index/openai-api/), [Anthropic](https://platform.claude.com/docs/en/api/admin/api_keys/retrieve), and [OpenRouter](https://openrouter.ai/keys). One OpenRouter key reaches the whole openrouter.ai catalog (deepseek, mistral, llama, grok, qwen, ...), which is how the worker roster grows wide without a key per provider. You can store your API keys in `.env`.
23
+
24
+ ### Basic tests
25
+ To see if api keys are working (from activated env): `python -m litesquad.check_keys`
26
+
27
+ Check on specific models: `litesquad --check`
28
+
29
+ Offline test: `litesquad --smoke --mock`
30
+
31
+
32
+ ### Caveats
33
+ This provides an interface to an ensemble of LLMs to try to generate a better answer than when using a single LLM. No agentic tool-usage, such as web calls, from the LLMs. Just vanilla text processing.
34
+
35
+ With apologies to [squad](https://github.com/bradygaster/squad).
36
+
@@ -0,0 +1,47 @@
1
+ [build-system]
2
+ requires = ["uv_build>=0.11.26,<0.12.0"]
3
+ build-backend = "uv_build"
4
+
5
+ [project]
6
+ name = "litesquad"
7
+ version = "0.0.1"
8
+ description = "Lightweight tool for working with a team of LLMs"
9
+ license = "Apache-2.0"
10
+ license-files = ["LICENSE"]
11
+ readme = "README.md"
12
+ authors = [
13
+ { name = "EricThomson", email = "thomson.eric@gmail.com" }
14
+ ]
15
+ requires-python = ">=3.12"
16
+ dependencies = [
17
+ "litellm>=1.90.1",
18
+ "pydantic>=2.13.4",
19
+ "python-dotenv>=1.0.0",
20
+ "rich>=15.0.0",
21
+ "typer>=0.26.8",
22
+ ]
23
+
24
+ [project.optional-dependencies]
25
+ web = [
26
+ # <4.2: Dash 4.2+ remounts every child whenever a callback writes a children
27
+ # prop (open regression, plotly/dash#3846), which wipes DOM state like
28
+ # <details> open/closed in the live view. Lift the cap when that issue closes.
29
+ "dash>=3.0,<4.2",
30
+ ]
31
+
32
+ [project.scripts]
33
+ litesquad = "litesquad:main"
34
+ litesquad-keys = "litesquad.check_keys:main"
35
+
36
+ [dependency-groups]
37
+ dev = [
38
+ "pytest>=9.1.1",
39
+ "ruff>=0.15.20",
40
+ ]
41
+
42
+ [project.urls]
43
+ Repository = "https://github.com/EricThomson/litesquad"
44
+
45
+ [tool.uv.build-backend]
46
+ module-root = "src"
47
+
@@ -0,0 +1,5 @@
1
+ from .cli import app
2
+
3
+
4
+ def main() -> None:
5
+ app()
@@ -0,0 +1,57 @@
1
+ """Dead-simple check that each provider API key is valid and active.
2
+
3
+ Run: uv run litesquad-keys (or: uv run python -m litesquad.check_keys)
4
+
5
+ Pings one cheap model per provider with a 1-token request and prints a
6
+ checkmark per key. Independent of the squad config, so it tests the key
7
+ itself, not whichever model your squad happens to use.
8
+ """
9
+
10
+ import os
11
+
12
+ import litellm
13
+ from rich.console import Console
14
+
15
+ from .llm import load_env # loads .env with override=True; importing also quiets litellm
16
+
17
+ console = Console()
18
+
19
+ # One cheap, broadly-available probe model per provider key.
20
+ PROBES = {
21
+ "ANTHROPIC_API_KEY": "anthropic/claude-haiku-4-5",
22
+ "OPENAI_API_KEY": "openai/gpt-4o-mini",
23
+ "GEMINI_API_KEY": "gemini/gemini-2.5-flash",
24
+ "OPENROUTER_API_KEY": "openrouter/openai/gpt-4o-mini",
25
+ }
26
+
27
+
28
+ def check(model: str) -> tuple[bool, str]:
29
+ try:
30
+ litellm.completion(
31
+ model=model,
32
+ messages=[{"role": "user", "content": "ping"}],
33
+ max_tokens=1,
34
+ drop_params=True,
35
+ )
36
+ return True, "ok"
37
+ except Exception as exc: # noqa: BLE001 - any failure means the key isn't usable
38
+ return False, str(exc).splitlines()[0].strip()
39
+
40
+
41
+ def main() -> None:
42
+ load_env()
43
+ for key, model in PROBES.items():
44
+ # An unset key is a distinct state from an invalid one: say "not set"
45
+ # instead of probing and printing a provider auth exception.
46
+ if not os.environ.get(key):
47
+ console.print(f"[red]✗[/] {key} — not set")
48
+ continue
49
+ ok, detail = check(model)
50
+ if ok:
51
+ console.print(f"[green]✓[/] {key} — active")
52
+ else:
53
+ console.print(f"[red]✗[/] {key} — invalid: {detail}")
54
+
55
+
56
+ if __name__ == "__main__":
57
+ main()
@@ -0,0 +1,276 @@
1
+ """Command-line interface: one fixed-flow run, then interactive follow-ups."""
2
+
3
+ from datetime import datetime
4
+ from pathlib import Path
5
+
6
+ import typer
7
+ from rich.console import Console
8
+ from rich.markdown import Markdown
9
+ from rich.panel import Panel
10
+ from rich.prompt import Prompt
11
+ from rich.status import Status
12
+
13
+ from . import paths
14
+ from .config import RunConfig, SquadConfig, ensure_starter, load_config
15
+ from .llm import LLMError, MissingKeysError, call_model, load_env, mock_call_model, preflight
16
+ from .models import Conversation, Stage, TranscriptEvent
17
+ from .squad import run_quick, run_turn
18
+
19
+ app = typer.Typer(add_completion=False, help="Ask a small ensemble of LLMs anything.")
20
+ console = Console()
21
+
22
+ STAGE_LABEL: dict[Stage, str] = {
23
+ "propose": "responding",
24
+ "critique": "critiquing",
25
+ "revise": "revising",
26
+ "extract": "de-stylizing",
27
+ "cluster": "clustering",
28
+ "judge": "judging",
29
+ "reply": "answering",
30
+ }
31
+ QUIT_WORDS = {":quit", ":q", "quit", "exit"}
32
+ SMOKE_PROMPT = "What is 1 + 1? Answer in one short sentence."
33
+
34
+
35
+ class ConsoleReporter:
36
+ """Renders each stage as a Rich panel and appends events to a JSONL file.
37
+
38
+ Worker chains run in parallel, so their stages complete interleaved. Printing them
39
+ as they land is unreadable, so chain stages (propose/critique/revise) are buffered
40
+ per worker and printed as one coherent block the moment that worker's chain finishes
41
+ (or dies) -- blocks appear in chain-completion order. Everything else (extract,
42
+ cluster, judge, reply) prints as it completes, and the spinner always shows everyone
43
+ currently in flight. The transcript JSONL is still appended per event in completion
44
+ order: it is the durable stream, and the web UI regroups it by worker anyway.
45
+
46
+ Per the Reporter contract, calls arrive serialized, so no lock is needed here;
47
+ printing while the Status runs is safe (rich renders it above the spinner).
48
+ """
49
+
50
+ def __init__(self, transcript_path: Path | None) -> None:
51
+ self.transcript_path = transcript_path
52
+ self._status: Status | None = None
53
+ self._in_flight: dict[tuple[str, Stage], str] = {} # (role, stage) -> spinner text
54
+ self._pending_chains: dict[str, list[Panel]] = {} # worker key -> panels so far
55
+
56
+ @staticmethod
57
+ def _worker_key(role: str) -> str:
58
+ """propose/revise carry ``worker_N``; critique carries ``critic->worker_N``."""
59
+ return role.split("->")[-1]
60
+
61
+ @staticmethod
62
+ def _panel(event: TranscriptEvent) -> Panel:
63
+ title = f"{event.role} | {event.model}"
64
+ if event.error:
65
+ return Panel(event.error, title=f"{title} (error)", border_style="red")
66
+ border = "green" if event.stage in ("judge", "reply") else "cyan"
67
+ return Panel(Markdown(event.output), title=title, border_style=border)
68
+
69
+ def _spinner_text(self) -> str:
70
+ return " | ".join(self._in_flight.values())
71
+
72
+ def _flush_chain(self, worker: str) -> None:
73
+ for panel in self._pending_chains.pop(worker, []):
74
+ console.print(panel)
75
+
76
+ def stage_start(self, stage: Stage, role: str, model: str) -> None:
77
+ self._in_flight[(role, stage)] = f"[bold]{role}[/] ({model}) - {STAGE_LABEL[stage]}..."
78
+ if self._status is None:
79
+ self._status = console.status(self._spinner_text(), spinner="dots")
80
+ self._status.start()
81
+ else:
82
+ self._status.update(self._spinner_text())
83
+
84
+ def stage_done(self, event: TranscriptEvent) -> None:
85
+ self._in_flight.pop((event.role, event.stage), None)
86
+ if self.transcript_path is not None:
87
+ with self.transcript_path.open("a", encoding="utf-8") as fh:
88
+ fh.write(event.to_jsonl() + "\n")
89
+ if event.stage in ("propose", "critique", "revise"):
90
+ worker = self._worker_key(event.role)
91
+ self._pending_chains.setdefault(worker, []).append(self._panel(event))
92
+ if event.stage == "revise" or event.error: # chain finished, or died here
93
+ self._flush_chain(worker)
94
+ else:
95
+ console.print(self._panel(event))
96
+ if self._status is not None:
97
+ if self._in_flight:
98
+ self._status.update(self._spinner_text())
99
+ else:
100
+ self._status.stop()
101
+ self._status = None
102
+
103
+ def close(self) -> None:
104
+ """Flush any unfinished chains and stop the spinner. Call in a ``finally``: an
105
+ aborted turn must still show what its surviving chains produced, and must not
106
+ leave a live display running (hidden cursor, endless spinner)."""
107
+ for worker in list(self._pending_chains):
108
+ self._flush_chain(worker)
109
+ if self._status is not None:
110
+ self._status.stop()
111
+ self._status = None
112
+ self._in_flight.clear()
113
+
114
+
115
+ def _transcript_path(save: bool) -> Path | None:
116
+ if not save:
117
+ return None
118
+ stamp = datetime.now().strftime("%Y-%m-%d_%H%M%S")
119
+ return paths.transcripts_dir() / f"{stamp}.jsonl"
120
+
121
+
122
+ def _model_roles(config: SquadConfig) -> list[tuple[str, str]]:
123
+ """Distinct configured models in pipeline order (workers first, then critic ->
124
+ extractor -> clusterer -> judge), each with the role(s) it holds -- so --check
125
+ doubles as a who-does-what roster card."""
126
+ assignments = [
127
+ *(("worker", worker.model) for worker in config.workers),
128
+ ("critic", config.critic.model),
129
+ ("extractor", config.extractor.model),
130
+ ("clusterer", config.clusterer.model),
131
+ ("judge", config.judge.model),
132
+ ]
133
+ roles_by_model: dict[str, list[str]] = {}
134
+ for role, model in assignments:
135
+ roles = roles_by_model.setdefault(model, [])
136
+ if role not in roles: # two workers on one model still read as one "worker"
137
+ roles.append(role)
138
+ return [(model, ", ".join(roles)) for model, roles in roles_by_model.items()]
139
+
140
+
141
+ def _check_models(config: SquadConfig) -> bool:
142
+ """Ping each distinct configured model with a tiny request. Returns all-ok.
143
+
144
+ ``max_tokens`` is generous (not 5) because reasoning models (GPT-5,
145
+ Gemini 2.5 Pro) spend output budget on hidden reasoning before any visible
146
+ text — too small a cap returns empty content. The cap only prevents
147
+ truncation; actual usage stays tiny since the model stops after "ok".
148
+ """
149
+ run_cfg = RunConfig(max_tokens=1024, save_transcript=False)
150
+ messages = [{"role": "user", "content": "Reply with the single word: ok"}]
151
+ all_ok = True
152
+ for model, roles in _model_roles(config):
153
+ try:
154
+ reply = call_model(model, messages, run_cfg, role="check").strip()
155
+ console.print(f"[green]✓[/] {model} [dim]({roles})[/] — {reply[:40]}")
156
+ except LLMError as exc:
157
+ all_ok = False
158
+ console.print(f"[red]✗[/] {model} [dim]({roles})[/] — {exc}")
159
+ return all_ok
160
+
161
+
162
+ @app.command()
163
+ def run(
164
+ task: str = typer.Argument(None, help="Your question or task for the ensemble."),
165
+ quick: bool = typer.Option(
166
+ False, "--quick", help="Talk to just the judge (Opus), skipping the ensemble."
167
+ ),
168
+ mock: bool = typer.Option(
169
+ False, "--mock", help="Use canned offline responses; no API keys needed."
170
+ ),
171
+ check: bool = typer.Option(
172
+ False, "--check", help="Ping each configured model with a tiny request and exit."
173
+ ),
174
+ smoke: bool = typer.Option(
175
+ False, "--smoke", help="Run one real turn on a fixed tiny prompt and exit (cheap end-to-end)."
176
+ ),
177
+ web: bool = typer.Option(
178
+ False, "--web", help="Serve the web UI instead of the terminal (needs the 'web' extra)."
179
+ ),
180
+ port: int = typer.Option(8050, help="Port for the web UI (only used with --web)."),
181
+ ) -> None:
182
+ """Ask the ensemble (or, with --quick, just the judge), then take follow-ups."""
183
+ if web:
184
+ if task is not None:
185
+ console.print("[red]With --web, submit tasks in the browser, not on the command line.[/]")
186
+ raise typer.Exit(2)
187
+ from .web import serve # lazy: dash is an optional extra
188
+
189
+ serve(port=port, mock=mock)
190
+ return
191
+
192
+ load_env()
193
+
194
+ cfg_path = paths.config_path()
195
+ if ensure_starter(cfg_path):
196
+ console.print(
197
+ f"[dim]Wrote a starter config (all defaults, commented) you can edit at {cfg_path}[/]"
198
+ )
199
+ config = load_config(cfg_path)
200
+
201
+ if check:
202
+ try:
203
+ preflight(config)
204
+ except MissingKeysError as exc:
205
+ console.print(f"[red]{exc}[/]")
206
+ raise typer.Exit(1) from exc
207
+ console.print("Pinging configured models…")
208
+ raise typer.Exit(0 if _check_models(config) else 1)
209
+
210
+ if smoke:
211
+ caller = mock_call_model if mock else call_model
212
+ if not mock:
213
+ try:
214
+ preflight(config)
215
+ except MissingKeysError as exc:
216
+ console.print(f"[red]{exc}[/]")
217
+ raise typer.Exit(1) from exc
218
+ console.print(f'Smoke test: one turn on [dim]"{SMOKE_PROMPT}"[/]\n')
219
+ transcript_path = _transcript_path(config.run.save_transcript)
220
+ reporter = ConsoleReporter(transcript_path)
221
+ try:
222
+ run_turn(Conversation(), SMOKE_PROMPT, config, reporter, caller=caller)
223
+ except Exception as exc: # noqa: BLE001 - smoke surfaces ANY failure (call or save)
224
+ console.print(f"[red]Smoke test FAILED: {exc}[/]")
225
+ raise typer.Exit(1) from exc
226
+ finally:
227
+ reporter.close()
228
+ if transcript_path is not None:
229
+ console.print(f"[dim]Transcript: {transcript_path}[/]")
230
+ console.print("[green]Smoke test passed - all stages produced output.[/]")
231
+ raise typer.Exit(0)
232
+
233
+ if task is None:
234
+ console.print('[red]Provide a task, e.g. litesquad "Plan my week", or use --check.[/]')
235
+ raise typer.Exit(2)
236
+
237
+ caller = call_model
238
+ if mock:
239
+ caller = mock_call_model
240
+ console.print("[yellow]Running in --mock mode: canned responses, no API calls.[/]")
241
+ else:
242
+ try:
243
+ preflight(config)
244
+ except MissingKeysError as exc:
245
+ console.print(f"[red]{exc}[/]")
246
+ raise typer.Exit(1) from exc
247
+
248
+ conversation = Conversation()
249
+ transcript_path = _transcript_path(config.run.save_transcript)
250
+ reporter = ConsoleReporter(transcript_path)
251
+ run_one = run_quick if quick else run_turn
252
+ if quick:
253
+ console.print("[dim]Quick mode: just the judge, no ensemble.[/]")
254
+
255
+ current_task = task
256
+ while True:
257
+ try:
258
+ run_one(conversation, current_task, config, reporter, caller=caller)
259
+ except LLMError as exc:
260
+ console.print(f"[red]Turn aborted: {exc}[/]")
261
+ finally:
262
+ reporter.close()
263
+
264
+ if transcript_path is not None:
265
+ console.print(f"[dim]Transcript: {transcript_path}[/]")
266
+
267
+ try:
268
+ reply = Prompt.ask(
269
+ "\n[bold magenta]Follow-up[/] ([bold yellow]:quit to exit[/])"
270
+ ).strip()
271
+ except (EOFError, KeyboardInterrupt):
272
+ console.print()
273
+ break
274
+ if not reply or reply.lower() in QUIT_WORDS:
275
+ break
276
+ current_task = reply