coder-agent 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.
Files changed (163) hide show
  1. coder_agent-0.1.0.dist-info/METADATA +262 -0
  2. coder_agent-0.1.0.dist-info/RECORD +163 -0
  3. coder_agent-0.1.0.dist-info/WHEEL +5 -0
  4. coder_agent-0.1.0.dist-info/entry_points.txt +2 -0
  5. coder_agent-0.1.0.dist-info/licenses/LICENSE.md +21 -0
  6. coder_agent-0.1.0.dist-info/top_level.txt +1 -0
  7. coderagent/__init__.py +20 -0
  8. coderagent/compat/__init__.py +27 -0
  9. coderagent/compat/cache_control.py +69 -0
  10. coderagent/compat/config_spec.py +60 -0
  11. coderagent/compat/exceptions.py +20 -0
  12. coderagent/compat/retry.py +27 -0
  13. coderagent/compat/serialize.py +31 -0
  14. coderagent/config/__init__.py +1 -0
  15. coderagent/config/defaults.yaml +103 -0
  16. coderagent/config/loader.py +264 -0
  17. coderagent/config/schema.py +548 -0
  18. coderagent/config/writer.py +218 -0
  19. coderagent/core/__init__.py +1 -0
  20. coderagent/core/budget.py +47 -0
  21. coderagent/core/capabilities.py +136 -0
  22. coderagent/core/checkpoint.py +164 -0
  23. coderagent/core/content.py +156 -0
  24. coderagent/core/context.py +618 -0
  25. coderagent/core/events.py +83 -0
  26. coderagent/core/history.py +56 -0
  27. coderagent/core/instructions.py +99 -0
  28. coderagent/core/loop.py +702 -0
  29. coderagent/core/memory.py +56 -0
  30. coderagent/core/mentions.py +81 -0
  31. coderagent/core/os_sandbox.py +191 -0
  32. coderagent/core/otel.py +214 -0
  33. coderagent/core/protocols.py +38 -0
  34. coderagent/core/redact.py +49 -0
  35. coderagent/core/sandbox.py +82 -0
  36. coderagent/core/schema.py +107 -0
  37. coderagent/core/session.py +344 -0
  38. coderagent/core/shell_env.py +74 -0
  39. coderagent/core/subagent.py +474 -0
  40. coderagent/core/summarize.py +312 -0
  41. coderagent/core/telemetry.py +209 -0
  42. coderagent/core/tokens.py +132 -0
  43. coderagent/core/trust.py +301 -0
  44. coderagent/environments/__init__.py +11 -0
  45. coderagent/environments/bubblewrap.py +150 -0
  46. coderagent/environments/contree.py +146 -0
  47. coderagent/environments/docker.py +160 -0
  48. coderagent/environments/local.py +110 -0
  49. coderagent/environments/singularity.py +138 -0
  50. coderagent/environments/swerex_docker.py +79 -0
  51. coderagent/environments/swerex_modal.py +123 -0
  52. coderagent/eval/__init__.py +1 -0
  53. coderagent/eval/compare.py +190 -0
  54. coderagent/eval/report.py +141 -0
  55. coderagent/eval/runner.py +368 -0
  56. coderagent/eval/task.py +194 -0
  57. coderagent/extensions/__init__.py +1 -0
  58. coderagent/extensions/hooks.py +121 -0
  59. coderagent/extensions/plugins.py +217 -0
  60. coderagent/extensions/reflect.py +342 -0
  61. coderagent/models/__init__.py +33 -0
  62. coderagent/models/backends.py +218 -0
  63. coderagent/models/call.py +18 -0
  64. coderagent/models/check.py +139 -0
  65. coderagent/models/gateway.py +60 -0
  66. coderagent/models/litellm_config.py +70 -0
  67. coderagent/models/provider.py +98 -0
  68. coderagent/models/reasoning.py +28 -0
  69. coderagent/models/router.py +136 -0
  70. coderagent/models/settings.py +172 -0
  71. coderagent/models/streaming.py +122 -0
  72. coderagent/models/verbosity.py +14 -0
  73. coderagent/paths.py +31 -0
  74. coderagent/run.py +454 -0
  75. coderagent/skills/__init__.py +119 -0
  76. coderagent/skills/errors.py +11 -0
  77. coderagent/skills/install.py +340 -0
  78. coderagent/skills/presets/code-review/SKILL.md +35 -0
  79. coderagent/skills/presets/codebase-onboarding/SKILL.md +33 -0
  80. coderagent/skills/presets/data-analysis/SKILL.md +35 -0
  81. coderagent/skills/presets/deep-research/SKILL.md +38 -0
  82. coderagent/skills/presets/frontend-dev/SKILL.md +32 -0
  83. coderagent/skills/presets/long-document/SKILL.md +37 -0
  84. coderagent/skills/presets/long-document/scripts/pdf_text.py +37 -0
  85. coderagent/skills/presets/office-docx/SKILL.md +36 -0
  86. coderagent/skills/presets/office-docx/scripts/docx_text.py +36 -0
  87. coderagent/skills/presets/office-pptx/SKILL.md +32 -0
  88. coderagent/skills/presets/office-xlsx/SKILL.md +34 -0
  89. coderagent/skills/presets/office-xlsx/scripts/xlsx_text.py +72 -0
  90. coderagent/skills/presets/writing/SKILL.md +31 -0
  91. coderagent/skills/sandbox.py +269 -0
  92. coderagent/skills/sites.py +177 -0
  93. coderagent/skills/source.py +404 -0
  94. coderagent/testing/__init__.py +5 -0
  95. coderagent/testing/factory.py +59 -0
  96. coderagent/testing/scripted_model.py +54 -0
  97. coderagent/tools/__init__.py +1 -0
  98. coderagent/tools/base.py +54 -0
  99. coderagent/tools/bash_policy.py +486 -0
  100. coderagent/tools/builtin/__init__.py +35 -0
  101. coderagent/tools/builtin/fs.py +283 -0
  102. coderagent/tools/builtin/patch.py +279 -0
  103. coderagent/tools/builtin/search.py +242 -0
  104. coderagent/tools/builtin/shell.py +336 -0
  105. coderagent/tools/builtin/skill.py +41 -0
  106. coderagent/tools/builtin/task.py +53 -0
  107. coderagent/tools/builtin/todo.py +63 -0
  108. coderagent/tools/executor.py +243 -0
  109. coderagent/tools/mcp.py +317 -0
  110. coderagent/tools/permissions.py +472 -0
  111. coderagent/tools/registry.py +83 -0
  112. coderagent/tools/rules.py +138 -0
  113. coderagent/ui/__init__.py +1 -0
  114. coderagent/ui/cli.py +498 -0
  115. coderagent/ui/commands/__init__.py +109 -0
  116. coderagent/ui/commands/builtin.py +778 -0
  117. coderagent/ui/commands/compact.py +12 -0
  118. coderagent/ui/commands/resume.py +26 -0
  119. coderagent/ui/commands/review.py +73 -0
  120. coderagent/ui/commands/rewind.py +28 -0
  121. coderagent/ui/custom_commands.py +179 -0
  122. coderagent/ui/notify.py +46 -0
  123. coderagent/ui/open_file.py +48 -0
  124. coderagent/ui/render.py +62 -0
  125. coderagent/ui/spinner.py +68 -0
  126. coderagent/ui/tui.py +610 -0
  127. coderagent/ui/widgets/__init__.py +29 -0
  128. coderagent/ui/widgets/approval_prompt.py +129 -0
  129. coderagent/ui/widgets/diff_view.py +97 -0
  130. coderagent/ui/widgets/file_tree.py +105 -0
  131. coderagent/ui/widgets/markdown_message.py +44 -0
  132. coderagent/ui/widgets/markup.py +10 -0
  133. coderagent/ui/widgets/message_block.py +61 -0
  134. coderagent/ui/widgets/path_suggester.py +66 -0
  135. coderagent/ui/widgets/session_picker.py +49 -0
  136. coderagent/ui/widgets/status_bar.py +44 -0
  137. coderagent/ui/widgets/todo_panel.py +40 -0
  138. coderagent/ui/widgets/tool_card.py +104 -0
  139. coderagent/ui/widgets/working_dots.py +26 -0
  140. coderagent/version.py +7 -0
  141. coderagent/web/__init__.py +5 -0
  142. coderagent/web/api.py +449 -0
  143. coderagent/web/app.py +113 -0
  144. coderagent/web/approver.py +73 -0
  145. coderagent/web/config_api.py +53 -0
  146. coderagent/web/events.py +159 -0
  147. coderagent/web/files.py +115 -0
  148. coderagent/web/i18n.py +346 -0
  149. coderagent/web/server.py +100 -0
  150. coderagent/web/sessions.py +404 -0
  151. coderagent/web/skills_api.py +376 -0
  152. coderagent/web/static/app.css +283 -0
  153. coderagent/web/static/app.js +1466 -0
  154. coderagent/web/templates/en/base.html +31 -0
  155. coderagent/web/templates/en/chat.html +60 -0
  156. coderagent/web/templates/en/macros.html +9 -0
  157. coderagent/web/templates/en/settings.html +80 -0
  158. coderagent/web/templates/en/skills.html +64 -0
  159. coderagent/web/templates/zh/base.html +31 -0
  160. coderagent/web/templates/zh/chat.html +60 -0
  161. coderagent/web/templates/zh/macros.html +9 -0
  162. coderagent/web/templates/zh/settings.html +77 -0
  163. coderagent/web/templates/zh/skills.html +61 -0
@@ -0,0 +1,218 @@
1
+ """Model backends: the calls to the model, their retries and their cache control."""
2
+
3
+ import logging
4
+ from collections.abc import Iterator
5
+ from functools import cache, cached_property
6
+ from typing import Any
7
+
8
+ from coderagent.compat import retry, set_cache_control
9
+ from coderagent.models import litellm_module
10
+ from coderagent.models.call import check_reserved
11
+ from coderagent.models.litellm_config import resolve as resolve_alias
12
+ from coderagent.models.provider import normalize
13
+ from coderagent.models.reasoning import translate
14
+ from coderagent.models.streaming import ModelEvent, ToolCallAccumulator, message_from_events
15
+
16
+ logger = logging.getLogger("coderagent.backend")
17
+
18
+ AUTH_HINTS = ("api key", "apikey", "invalid token", "unauthorized", "authentication", "no api key")
19
+ """What a provider says when the key is the problem and not the server."""
20
+
21
+
22
+ def is_auth_error(error: Exception) -> bool:
23
+ """Whether the error says that the key is wrong.
24
+
25
+ A relay station without a key answers with a 500, and a 500 is worth
26
+ retrying. This one is not: the key will not become good by waiting.
27
+ """
28
+ text = str(error).lower()
29
+ return any(hint in text for hint in AUTH_HINTS)
30
+
31
+
32
+ @cache
33
+ def _warn_about_the_price(model: str, message: str) -> None:
34
+ """Say that the price of a model is missing, once and not on every call.
35
+
36
+ A model that has no price has no cost: the budget of such a model is
37
+ `agent.token_limit`, and the money never moves.
38
+ """
39
+ logger.warning("Could not calculate cost for model %s: %s", model, message)
40
+
41
+
42
+ @cache
43
+ def has_price(model: str) -> bool:
44
+ """Whether litellm knows the price of the model.
45
+
46
+ A model without a price spends no money: its cost is unknown, not zero.
47
+ """
48
+ try:
49
+ litellm_module().cost_calculator.cost_per_token(model=model, prompt_tokens=0, completion_tokens=0)
50
+ return True
51
+ except Exception:
52
+ return False
53
+
54
+
55
+ def priced_name(model_name: str, litellm_config: str = "") -> str:
56
+ """The name of the model, with the alias of the config file resolved.
57
+
58
+ litellm knows the price of the real model, not the price of its alias.
59
+ """
60
+ return resolve_alias(litellm_config, model_name)[0] if litellm_config else model_name
61
+
62
+
63
+ class LiteLLMBackend:
64
+ """Calls `litellm.completion` and normalizes the response."""
65
+
66
+ @cached_property
67
+ def abort_exceptions(self) -> list[type[Exception]]:
68
+ """The errors that no retry can fix."""
69
+ exceptions = litellm_module().exceptions
70
+ return [
71
+ exceptions.UnsupportedParamsError,
72
+ exceptions.NotFoundError,
73
+ exceptions.PermissionDeniedError,
74
+ exceptions.ContextWindowExceededError,
75
+ exceptions.AuthenticationError,
76
+ exceptions.BadRequestError,
77
+ KeyboardInterrupt,
78
+ ]
79
+
80
+ def __init__(
81
+ self,
82
+ model_name: str,
83
+ *,
84
+ model_kwargs: dict[str, Any] | None = None,
85
+ set_cache_control: str | None = None,
86
+ litellm_config: str = "",
87
+ reasoning_effort: str = "",
88
+ max_retries: int = 0,
89
+ api_key: str = "",
90
+ api_base: str = "",
91
+ ) -> None:
92
+ """The name may be an alias of the model list of a litellm config file."""
93
+ self.alias = model_name
94
+ """The name the user wrote. The capabilities of a model are said about this name."""
95
+ name, params = resolve_alias(litellm_config, model_name) if litellm_config else (model_name, {})
96
+ merged = params | (model_kwargs or {})
97
+ check_reserved(merged)
98
+ """The parameters of the call belong to the agent: a user may not set them."""
99
+ if api_key:
100
+ merged["api_key"] = api_key
101
+ """The key has a field of its own: it wins over the one of `model_kwargs`."""
102
+ if api_base:
103
+ merged["api_base"] = api_base
104
+ """The address has a field of its own: it wins over the one of `model_kwargs`."""
105
+ self.model_kwargs = merged
106
+ self.model_name = normalize(name, str(merged.get("api_base") or ""))
107
+ """The name litellm is called with: the provider is in front of the model."""
108
+ if reasoning_effort:
109
+ """The thinking budget, in the words of the provider of this model."""
110
+ for key, value in translate(self.model_name, reasoning_effort).items():
111
+ self.model_kwargs.setdefault(key, value)
112
+ """What the user wrote in `model_kwargs` wins over the level."""
113
+ self.set_cache_control = set_cache_control
114
+ self.max_retries = max_retries
115
+ """How many times a call is tried at most. 0 lets the retry decide."""
116
+ self.priced = has_price(self.model_name)
117
+ """False when the model has no price. The cost of such a model is unknown, not zero."""
118
+
119
+ def query(self, messages: list[dict], tools: list[dict] | None = None, **kwargs) -> dict:
120
+ return message_from_events(self.query_stream(messages, tools=tools, **kwargs))
121
+
122
+ def query_stream(self, messages: list[dict], tools: list[dict] | None = None, **kwargs) -> Iterator[ModelEvent]:
123
+ """The answer as it arrives: text, reasoning and tool call fragments."""
124
+ prepared = set_cache_control(
125
+ [{k: v for k, v in message.items() if k != "extra"} for message in messages],
126
+ mode=self.set_cache_control,
127
+ )
128
+ call_kwargs = self.model_kwargs | kwargs
129
+ if tools:
130
+ call_kwargs["tools"] = tools
131
+ call_kwargs["stream"] = True
132
+ call_kwargs.setdefault("stream_options", {"include_usage": True})
133
+ yield from self._events(self._open_stream(prepared, call_kwargs))
134
+
135
+ def get_template_vars(self) -> dict[str, Any]:
136
+ return {"model_name": self.model_name, **self.model_kwargs}
137
+
138
+ def _open_stream(self, messages: list[dict], call_kwargs: dict):
139
+ litellm = litellm_module()
140
+ for attempt in retry(logger=logger, abort_exceptions=self.abort_exceptions, attempts=self.max_retries):
141
+ with attempt:
142
+ try:
143
+ return litellm.completion(model=self.model_name, messages=messages, **call_kwargs)
144
+ except litellm.exceptions.InternalServerError as e:
145
+ if is_auth_error(e):
146
+ """The key is wrong. Retrying only makes the user wait longer."""
147
+ raise litellm.exceptions.AuthenticationError(
148
+ str(e), getattr(e, "llm_provider", "") or "", self.model_name
149
+ ) from e
150
+ raise
151
+ raise RuntimeError("the retry loop ended without a response")
152
+
153
+ def _events(self, response) -> Iterator[ModelEvent]:
154
+ accumulator = ToolCallAccumulator()
155
+ for chunk in response:
156
+ delta = self._delta(chunk)
157
+ if delta is not None:
158
+ reasoning = self._field(delta, "reasoning_content") or self._field(delta, "reasoning")
159
+ if reasoning:
160
+ yield ModelEvent(type="reasoning", content=reasoning)
161
+ text = self._field(delta, "content")
162
+ if text:
163
+ yield ModelEvent(type="text", content=text)
164
+ for fragment in self._tool_call_fragments(delta):
165
+ accumulator.feed(fragment)
166
+ yield ModelEvent(type="tool_call_delta", raw=fragment)
167
+ usage = self._field(chunk, "usage")
168
+ if usage:
169
+ yield ModelEvent(type="usage", cost=self._stream_cost(usage), raw={"usage": usage})
170
+ for call in accumulator.finish():
171
+ yield ModelEvent(type="tool_call_done", tool_call=call)
172
+
173
+ @staticmethod
174
+ def _delta(chunk) -> Any:
175
+ choices = getattr(chunk, "choices", None) or []
176
+ return getattr(choices[0], "delta", None) if choices else None
177
+
178
+ @staticmethod
179
+ def _field(obj, name: str):
180
+ value = getattr(obj, name, None)
181
+ if value is None and isinstance(obj, dict):
182
+ value = obj.get(name)
183
+ return value
184
+
185
+ @staticmethod
186
+ def _tool_call_fragments(delta) -> list[dict]:
187
+ fragments = []
188
+ for call in getattr(delta, "tool_calls", None) or []:
189
+ if isinstance(call, dict):
190
+ fragments.append(call)
191
+ elif hasattr(call, "model_dump"):
192
+ fragments.append(call.model_dump())
193
+ else: # pragma: no cover - providers always give one of the two
194
+ function = getattr(call, "function", None)
195
+ fragments.append(
196
+ {
197
+ "index": getattr(call, "index", 0),
198
+ "id": getattr(call, "id", "") or "",
199
+ "function": {
200
+ "name": getattr(function, "name", "") or "",
201
+ "arguments": getattr(function, "arguments", "") or "",
202
+ },
203
+ }
204
+ )
205
+ return fragments
206
+
207
+ def _stream_cost(self, usage) -> float:
208
+ prompt = int(self._field(usage, "prompt_tokens") or 0)
209
+ completion = int(self._field(usage, "completion_tokens") or 0)
210
+ try:
211
+ prompt_cost, completion_cost = litellm_module().cost_calculator.cost_per_token(
212
+ model=self.model_name, prompt_tokens=prompt, completion_tokens=completion
213
+ )
214
+ return float(prompt_cost) + float(completion_cost)
215
+ except Exception as e:
216
+ self.priced = False
217
+ _warn_about_the_price(self.model_name, str(e))
218
+ return 0.0
@@ -0,0 +1,18 @@
1
+ """The parameters of a call to a model: the ones that belong to the agent."""
2
+
3
+ from typing import Any
4
+
5
+ RESERVED = ("model", "messages", "tools", "stream", "stream_options")
6
+ """The parameters of the call that the agent sets itself.
7
+
8
+ The model and the messages are the ones of the agent, the tools are the ones
9
+ of the session, and the stream is how the answer arrives. A user who sets one
10
+ of them breaks the call in a way that only shows at runtime.
11
+ """
12
+
13
+
14
+ def check_reserved(kwargs: dict[str, Any]) -> None:
15
+ """Refuse the parameters that the agent sets itself."""
16
+ for key in RESERVED:
17
+ if key in kwargs:
18
+ raise ValueError(f"'model_kwargs' must not have '{key}': the agent sets it itself.")
@@ -0,0 +1,139 @@
1
+ """The try-out of the model: does it answer, does it call the tools.
2
+
3
+ The try-out never writes anything: it says whether the settings work, and the
4
+ writing is a step of its own. A configuration that does not work yet is worth
5
+ writing down, to be fixed later.
6
+ """
7
+
8
+ import time
9
+ from typing import Any
10
+
11
+ import yaml
12
+
13
+ from coderagent.models.litellm_config import locate
14
+ from coderagent.models.provider import env_var
15
+ from coderagent.models.settings import hint, key_of, key_source, key_text, provider_of
16
+
17
+
18
+ def check_litellm_config(path: str, name: str = "") -> dict[str, Any]:
19
+ """The file of the aliases: does it exist, does it parse, what is in it."""
20
+ if not path:
21
+ return {"ok": True, "path": "", "aliases": [], "error": ""}
22
+ file = locate(path)
23
+ if not file.is_file():
24
+ return {"ok": False, "path": str(file), "aliases": [], "error": "the file does not exist"}
25
+ try:
26
+ data = yaml.safe_load(file.read_text(encoding="utf-8")) or {}
27
+ except yaml.YAMLError as error:
28
+ return {"ok": False, "path": str(file), "aliases": [], "error": f"the file is not valid YAML: {error}"}
29
+ if not isinstance(data, dict) or not isinstance(data.get("model_list"), list):
30
+ return {"ok": False, "path": str(file), "aliases": [], "error": "the file has no model_list"}
31
+ aliases = [
32
+ entry.get("model_name") for entry in data["model_list"] if isinstance(entry, dict) and entry.get("model_name")
33
+ ]
34
+ if name and name not in aliases:
35
+ return {
36
+ "ok": False,
37
+ "path": str(file),
38
+ "aliases": aliases,
39
+ "error": f"'{name}' is not one of the aliases of this file",
40
+ }
41
+ return {"ok": True, "path": str(file), "aliases": aliases, "error": ""}
42
+
43
+
44
+ def check_tools(backend) -> dict[str, Any]:
45
+ """The model has to call the tools, or the agent cannot work at all."""
46
+ tools = [
47
+ {
48
+ "type": "function",
49
+ "function": {
50
+ "name": "ping",
51
+ "description": "Answer with a ping.",
52
+ "parameters": {"type": "object", "properties": {}},
53
+ },
54
+ }
55
+ ]
56
+ try:
57
+ message = backend.query([{"role": "user", "content": "Call the ping tool."}], tools=tools, max_tokens=64)
58
+ except Exception as error:
59
+ return {"ok": False, "error": f"{type(error).__name__}: {error}"}
60
+ calls = message.get("tool_calls") or []
61
+ return {
62
+ "ok": bool(calls),
63
+ "error": "" if calls else "the model did not call the tool",
64
+ "calls": len(calls),
65
+ }
66
+
67
+
68
+ def test_connection(effective: dict) -> dict[str, Any]:
69
+ """See whether the settings work: the file, the call and the tools."""
70
+ from coderagent.models.backends import LiteLLMBackend
71
+
72
+ name = effective["model_name"]
73
+ kwargs = effective["model_kwargs"]
74
+ base = str(kwargs.get("api_base") or "")
75
+ provider = effective.get("provider") or provider_of(name, base)
76
+ key = key_of(effective)
77
+ """The key of the environment counts too: the call below uses it."""
78
+ report: dict[str, Any] = {
79
+ "ok": False,
80
+ "resolved": {
81
+ "model_name": name,
82
+ "provider": provider,
83
+ "alias": effective.get("alias", ""),
84
+ "api_base": base,
85
+ "api_key_set": bool(key),
86
+ "api_key_hint": hint(key),
87
+ "key_source": key_source(str(kwargs.get("api_key") or ""), provider),
88
+ "key_env": env_var(provider),
89
+ },
90
+ "file": check_litellm_config(effective.get("litellm_config", ""), effective.get("requested", "")),
91
+ }
92
+ """A wrong key should fail right away, not after ten tries."""
93
+ started = time.time()
94
+ try:
95
+ backend = LiteLLMBackend(
96
+ name,
97
+ model_kwargs=kwargs,
98
+ reasoning_effort=effective.get("reasoning_effort", ""),
99
+ max_retries=1,
100
+ )
101
+ message = backend.query([{"role": "user", "content": "ping"}], max_tokens=1)
102
+ except Exception as error:
103
+ report["error"] = f"{type(error).__name__}: {error}"
104
+ return report
105
+ extra = message.get("extra") or {}
106
+ report.update(
107
+ {
108
+ "ok": True,
109
+ "content": str(message.get("content", ""))[:200],
110
+ "cost": float(extra.get("cost") or 0.0),
111
+ "latency_ms": int((time.time() - started) * 1000),
112
+ "tools": check_tools(backend),
113
+ }
114
+ )
115
+ return report
116
+
117
+
118
+ def report_text(report: dict) -> str:
119
+ """The report of a try-out, as the terminal and the interface show it."""
120
+ resolved = report.get("resolved") or {}
121
+ lines = [
122
+ f"model: {resolved.get('model_name', '')}",
123
+ f"provider: {resolved.get('provider', '') or '(none)'}",
124
+ f"api base: {resolved.get('api_base', '') or '(none)'}",
125
+ f"api key: {key_text(resolved)}",
126
+ ]
127
+ if report.get("error"):
128
+ lines.append(f"error: {report['error']}")
129
+ return "\n".join(lines)
130
+ lines.append(f"latency: {report.get('latency_ms', 0)} ms")
131
+ lines.append(f"cost: {report.get('cost', 0.0):.6f}")
132
+ tools = report.get("tools") or {}
133
+ lines.append(
134
+ "tools: the model calls the tools" if tools.get("ok") else f"tools: {tools.get('error', 'not checked')}"
135
+ )
136
+ aliases = report.get("file") or {}
137
+ if not aliases.get("ok", True):
138
+ lines.append(f"aliases file: {aliases.get('error', '')}")
139
+ return "\n".join(lines)
@@ -0,0 +1,60 @@
1
+ """Model backends and the gateway that fronts them."""
2
+
3
+ from collections.abc import Iterator
4
+ from typing import Any
5
+
6
+ from coderagent.core.protocols import ModelBackend
7
+ from coderagent.models import litellm_module
8
+ from coderagent.models.streaming import ModelEvent, message_from_events, usage_tokens
9
+
10
+
11
+ def is_context_overflow(error: Exception) -> bool:
12
+ """True when the provider refused the request because the context was too long."""
13
+ if isinstance(error, litellm_module().exceptions.ContextWindowExceededError):
14
+ return True
15
+ text = str(error).lower()
16
+ return any(marker in text for marker in ("context window", "context_length_exceeded", "maximum context length"))
17
+
18
+
19
+ class ModelGateway:
20
+ """Fronts one or more model backends and keeps track of what they spend."""
21
+
22
+ def __init__(self, backend: ModelBackend) -> None:
23
+ self.backend = backend
24
+ self.total_cost = 0.0
25
+ self.total_tokens_in = 0
26
+ self.total_tokens_out = 0
27
+ """The tokens of every call. The budget of a model that has no price."""
28
+ self.n_calls = 0
29
+
30
+ @property
31
+ def total_tokens(self) -> int:
32
+ """The tokens of every call, in and out."""
33
+ return self.total_tokens_in + self.total_tokens_out
34
+
35
+ @property
36
+ def priced(self) -> bool:
37
+ """Whether the model has a price. A model without one spends no money."""
38
+ return getattr(self.backend, "priced", True)
39
+
40
+ def query_stream(self, messages: list[dict], tools: list[dict] | None = None, **kwargs) -> Iterator[ModelEvent]:
41
+ """The answer as it arrives. The cost is booked when the provider reports it."""
42
+ self.n_calls += 1
43
+ for event in self.backend.query_stream(messages, tools=tools, **kwargs):
44
+ if event.type == "usage":
45
+ self.total_cost += event.cost
46
+ prompt, completion = usage_tokens(event.raw.get("usage"))
47
+ self.total_tokens_in += prompt
48
+ self.total_tokens_out += completion
49
+ yield event
50
+
51
+ def query(self, messages: list[dict], tools: list[dict] | None = None, **kwargs) -> dict:
52
+ """The whole answer in one piece."""
53
+ return message_from_events(self.query_stream(messages, tools=tools, **kwargs))
54
+
55
+ def complete(self, messages: list[dict], **kwargs) -> str:
56
+ """Non-streaming convenience call, e.g. for summarization."""
57
+ return self.query(messages, **kwargs).get("content", "")
58
+
59
+ def get_template_vars(self) -> dict[str, Any]:
60
+ return self.backend.get_template_vars()
@@ -0,0 +1,70 @@
1
+ """The model list of a litellm config file: the aliases of the models."""
2
+
3
+ import logging
4
+ from functools import cache
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ import yaml
9
+
10
+ from coderagent.paths import config_home
11
+
12
+ logger = logging.getLogger("coderagent.models.litellm_config")
13
+
14
+
15
+ def locate(path: str | Path) -> Path:
16
+ """The file of the aliases.
17
+
18
+ A relative path is looked for in the home of the user first and in the
19
+ working directory after it: the setting lives in a file that does not move,
20
+ the working directory does.
21
+ """
22
+ file = Path(path).expanduser()
23
+ if file.is_absolute():
24
+ return file
25
+ for candidate in (config_home() / file, Path.cwd() / file):
26
+ if candidate.exists():
27
+ return candidate
28
+ """The file that is not there: the home of the user is the place to look for it."""
29
+ return config_home() / file
30
+
31
+
32
+ def deployments(path: str | Path) -> dict[str, dict[str, Any]]:
33
+ """The model list of the file, keyed by the alias of every entry."""
34
+ if not path:
35
+ return {}
36
+ file = locate(path)
37
+ if not file.is_file():
38
+ return {}
39
+ data = yaml.safe_load(file.read_text(encoding="utf-8")) or {}
40
+ return {
41
+ entry["model_name"]: entry.get("litellm_params") or {}
42
+ for entry in data.get("model_list") or []
43
+ if entry.get("model_name")
44
+ }
45
+
46
+
47
+ @cache
48
+ def _warn_about_the_alias(path: str, name: str, aliases: tuple[str, ...]) -> None:
49
+ """The file of the aliases does not have this name: it is of no use."""
50
+ logger.warning(
51
+ "The model '%s' is not one of the aliases of %s (%s): the settings of that file are not used.",
52
+ name,
53
+ path,
54
+ ", ".join(aliases),
55
+ )
56
+
57
+
58
+ def resolve(path: str | Path, model_name: str) -> tuple[str, dict[str, Any]]:
59
+ """The real model and the parameters of an alias.
60
+
61
+ The name itself and no parameters when the name is not an alias.
62
+ """
63
+ entries = deployments(path)
64
+ params = entries.get(model_name)
65
+ if params is None:
66
+ if entries:
67
+ """The file has models, but not this one: the file is of no use for it."""
68
+ _warn_about_the_alias(str(locate(path)), model_name, tuple(entries))
69
+ return model_name, {}
70
+ return params.get("model", model_name), {key: value for key, value in params.items() if key != "model"}
@@ -0,0 +1,98 @@
1
+ """The provider of a model: which one it is, and which key it uses.
2
+
3
+ One rule, one place. The name of a model may carry the provider
4
+ (`openai/MiniMax-M2.7`, `openai:MiniMax-M2.7`) or not (`MiniMax-M2.7`).
5
+ When it does not, the address of the endpoint says the protocol, and the
6
+ family of the model says the provider. What is still unknown stays as it is:
7
+ the name of the user is never rewritten behind their back.
8
+ """
9
+
10
+ import os
11
+
12
+ PROVIDERS = {
13
+ "openai": "OPENAI_API_KEY",
14
+ "anthropic": "ANTHROPIC_API_KEY",
15
+ "deepseek": "DEEPSEEK_API_KEY",
16
+ "gemini": "GEMINI_API_KEY",
17
+ "openrouter": "OPENROUTER_API_KEY",
18
+ "groq": "GROQ_API_KEY",
19
+ "mistral": "MISTRAL_API_KEY",
20
+ "xai": "XAI_API_KEY",
21
+ "together_ai": "TOGETHERAI_API_KEY",
22
+ "fireworks_ai": "FIREWORKS_API_KEY",
23
+ "azure": "AZURE_API_KEY",
24
+ "cohere": "COHERE_API_KEY",
25
+ "moonshot": "MOONSHOT_API_KEY",
26
+ "nvidia_nim": "NVIDIA_NIM_API_KEY",
27
+ "perplexity": "PERPLEXITYAI_API_KEY",
28
+ "dashscope": "DASHSCOPE_API_KEY",
29
+ "minimax": "MINIMAX_API_KEY",
30
+ }
31
+ """The provider of a model and the environment variable of its key."""
32
+
33
+ FAMILIES = {
34
+ "gpt-": "openai",
35
+ "o1": "openai",
36
+ "o3": "openai",
37
+ "o4": "openai",
38
+ "claude": "anthropic",
39
+ "gemini": "gemini",
40
+ "deepseek": "deepseek",
41
+ "grok": "xai",
42
+ "qwen": "dashscope",
43
+ "kimi": "moonshot",
44
+ "minimax": "minimax",
45
+ "mistral": "mistral",
46
+ "command": "cohere",
47
+ "sonar": "perplexity",
48
+ }
49
+ """The family of a model says the provider, when the name does not."""
50
+
51
+
52
+ def split(name: str) -> tuple[str, str]:
53
+ """The provider and the model of a name.
54
+
55
+ A slash always counts. A colon counts only when what is in front of it is
56
+ a known provider: `ft:gpt-4o:acme` is one name.
57
+ """
58
+ head, sep, tail = name.partition("/")
59
+ if sep:
60
+ return head.lower(), tail
61
+ head, sep, tail = name.partition(":")
62
+ if sep and head.lower() in PROVIDERS:
63
+ return head.lower(), tail
64
+ return "", name
65
+
66
+
67
+ def provider_of(name: str, api_base: str = "") -> str:
68
+ """The provider of a model: the name says it, the endpoint does, the family does."""
69
+ provider, model = split(name)
70
+ if provider:
71
+ return provider
72
+ if api_base:
73
+ """The address speaks for itself: Anthropic, or the OpenAI protocol every relay speaks."""
74
+ return "anthropic" if "anthropic" in api_base.lower() else "openai"
75
+ for prefix, provider in FAMILIES.items():
76
+ if model.lower().startswith(prefix):
77
+ return provider
78
+ return ""
79
+
80
+
81
+ def normalize(name: str, api_base: str = "") -> str:
82
+ """The name litellm is called with: the provider in front of the model.
83
+
84
+ A name that says nothing about its provider stays as it is.
85
+ """
86
+ provider, model = split(name)
87
+ provider = provider or provider_of(name, api_base)
88
+ return f"{provider}/{model}" if provider else name
89
+
90
+
91
+ def env_var(provider: str) -> str:
92
+ """The environment variable of the key of a provider."""
93
+ return PROVIDERS.get(provider, "")
94
+
95
+
96
+ def env_key(name: str, api_base: str = "") -> str:
97
+ """The key the environment has for this model."""
98
+ return os.getenv(env_var(provider_of(name, api_base)), "")
@@ -0,0 +1,28 @@
1
+ """How much a model thinks, in the words of its provider.
2
+
3
+ The user asks for a level (`minimal`, `low`, `medium`, `high`) and every
4
+ provider names it differently: OpenAI wants `reasoning_effort`, Anthropic wants
5
+ a number of tokens to think with. The translation happens here, once.
6
+ """
7
+
8
+ from typing import Any
9
+
10
+ from coderagent.models.provider import provider_of
11
+
12
+ EFFORTS = ("minimal", "low", "medium", "high")
13
+ """The levels the user may ask for. Empty means: the default of the model."""
14
+
15
+ BUDGETS = {"minimal": 1024, "low": 2048, "medium": 8192, "high": 16384}
16
+ """The tokens of thinking, for the providers that count tokens and not levels.
17
+
18
+ Anthropic asks for at least 1024 tokens, so `minimal` is that.
19
+ """
20
+
21
+
22
+ def translate(model_name: str, effort: str) -> dict[str, Any]:
23
+ """The parameter the provider of this model understands."""
24
+ if effort not in EFFORTS:
25
+ raise ValueError(f"unknown reasoning effort '{effort}'. Use one of: {', '.join(EFFORTS)}.")
26
+ if provider_of(model_name) == "anthropic":
27
+ return {"thinking": {"type": "enabled", "budget_tokens": BUDGETS[effort]}}
28
+ return {"reasoning_effort": effort}