chronos-steering 0.1.0a1__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,204 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
203
+
204
+ Copyright 2026 Nikolaus Spence
@@ -0,0 +1,74 @@
1
+ Metadata-Version: 2.4
2
+ Name: chronos-steering
3
+ Version: 0.1.0a1
4
+ Summary: An independent add-on for steering Chronos-3 forecasts with local or hosted LLMs.
5
+ Author: Nikolaus Spence
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Repository, https://github.com/nikspence/chronos-steering
8
+ Project-URL: Issues, https://github.com/nikspence/chronos-steering/issues
9
+ Requires-Python: >=3.10
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: chronos-forecasting==3.0.0
13
+ Dynamic: license-file
14
+
15
+ # Chronos Steering
16
+
17
+ An independent add-on for steering Chronos-3 forecasts with local or hosted LLMs.
18
+
19
+ Describe an event such as a promotion or an outage in plain language. An LLM translates that scenario into structured statements, and Amazon's [chronos-forecasting](https://github.com/amazon-science/chronos-forecasting) package runs the forecast locally. This project is not a fork or an official Amazon package.
20
+
21
+ ## Try it locally
22
+
23
+ Install from the checkout in a Python environment with a compatible PyTorch build. The adapter is pinned to Chronos Forecasting 3.0.0 because it implements that release's translator hook.
24
+
25
+ ```text
26
+ python -m pip install .
27
+ chronos-steering --model frognano:4b --reasoning-effort none --translate-only
28
+ chronos-steering --model frognano:4b --reasoning-effort none
29
+ ```
30
+
31
+ Use a model that is already installed in Ollama or pass another model tag. Ollama must be running at `http://localhost:11434` for the default configuration. The example uses synthetic daily orders and prints the accepted event statements. The full run also prints the baseline median, steered median, and difference for each forecast day. It downloads the Chronos-3 Tiny checkpoint and the separate text encoder on first use. The translation-only run does not download either.
32
+
33
+ ## Use an OpenAI-compatible gateway
34
+
35
+ For LiteLLM, set `LITELLM_API_KEY` in your shell and use a gateway alias that supports tool calls.
36
+
37
+ ```text
38
+ chronos-steering --base-url https://gateway.example/v1 --api-key-env LITELLM_API_KEY --model YOUR_ALIAS --translate-only
39
+ ```
40
+
41
+ Pass the API root, not the full Chat Completions URL. The service receives the Chronos translation prompt, including the scenario and any series context upstream includes in that prompt. Forecast inference remains local. The CLI never automatically switches from a local to a hosted translator.
42
+
43
+ Tool calls are the default. Try `--mode json_schema` only if the selected endpoint and model support schema-constrained responses. Likewise, omit `--reasoning-effort` if the provider does not accept that parameter. Chronos uses a long translation prompt, so a slow local model may need a larger `--timeout`. Endpoint compatibility and translation quality vary by model. LM Studio, llama.cpp, FastFlowLM, Bedrock Mantle, and OpenRouter are candidates for the same adapter, not qualified backends for this release.
44
+
45
+ ## Python API
46
+
47
+ ```python
48
+ from chronos_steering import OpenAICompatibleTranslator
49
+
50
+ translator = OpenAICompatibleTranslator("frognano:4b")
51
+ # history has item_id, timestamp and target columns.
52
+ texts = translator.translate_df(history, scenario, prediction_length=7, strict=True)
53
+ forecast = pipeline.predict_df(history, prediction_length=7, text=texts)
54
+ ```
55
+
56
+ Inspect `texts.items` before using the forecast. A valid tool call does not guarantee that the event was interpreted correctly. With upstream's default non-strict mode, check `texts.failures` for series that were not translated.
57
+
58
+ ## Development
59
+
60
+ From the checkout, install the package in a Python environment and run the smoke test.
61
+
62
+ ```text
63
+ python -m pip install -e .
64
+ python -m unittest discover -s tests
65
+ python -m pip install build twine
66
+ python -m build
67
+ python -m twine check dist/*
68
+ ```
69
+
70
+ See [Releasing Chronos Steering](RELEASE.md) for GitHub Actions and PyPI Trusted Publishing.
71
+
72
+ ## License
73
+
74
+ [Apache License 2.0](LICENSE). Copyright 2026 Nikolaus Spence.
@@ -0,0 +1,60 @@
1
+ # Chronos Steering
2
+
3
+ An independent add-on for steering Chronos-3 forecasts with local or hosted LLMs.
4
+
5
+ Describe an event such as a promotion or an outage in plain language. An LLM translates that scenario into structured statements, and Amazon's [chronos-forecasting](https://github.com/amazon-science/chronos-forecasting) package runs the forecast locally. This project is not a fork or an official Amazon package.
6
+
7
+ ## Try it locally
8
+
9
+ Install from the checkout in a Python environment with a compatible PyTorch build. The adapter is pinned to Chronos Forecasting 3.0.0 because it implements that release's translator hook.
10
+
11
+ ```text
12
+ python -m pip install .
13
+ chronos-steering --model frognano:4b --reasoning-effort none --translate-only
14
+ chronos-steering --model frognano:4b --reasoning-effort none
15
+ ```
16
+
17
+ Use a model that is already installed in Ollama or pass another model tag. Ollama must be running at `http://localhost:11434` for the default configuration. The example uses synthetic daily orders and prints the accepted event statements. The full run also prints the baseline median, steered median, and difference for each forecast day. It downloads the Chronos-3 Tiny checkpoint and the separate text encoder on first use. The translation-only run does not download either.
18
+
19
+ ## Use an OpenAI-compatible gateway
20
+
21
+ For LiteLLM, set `LITELLM_API_KEY` in your shell and use a gateway alias that supports tool calls.
22
+
23
+ ```text
24
+ chronos-steering --base-url https://gateway.example/v1 --api-key-env LITELLM_API_KEY --model YOUR_ALIAS --translate-only
25
+ ```
26
+
27
+ Pass the API root, not the full Chat Completions URL. The service receives the Chronos translation prompt, including the scenario and any series context upstream includes in that prompt. Forecast inference remains local. The CLI never automatically switches from a local to a hosted translator.
28
+
29
+ Tool calls are the default. Try `--mode json_schema` only if the selected endpoint and model support schema-constrained responses. Likewise, omit `--reasoning-effort` if the provider does not accept that parameter. Chronos uses a long translation prompt, so a slow local model may need a larger `--timeout`. Endpoint compatibility and translation quality vary by model. LM Studio, llama.cpp, FastFlowLM, Bedrock Mantle, and OpenRouter are candidates for the same adapter, not qualified backends for this release.
30
+
31
+ ## Python API
32
+
33
+ ```python
34
+ from chronos_steering import OpenAICompatibleTranslator
35
+
36
+ translator = OpenAICompatibleTranslator("frognano:4b")
37
+ # history has item_id, timestamp and target columns.
38
+ texts = translator.translate_df(history, scenario, prediction_length=7, strict=True)
39
+ forecast = pipeline.predict_df(history, prediction_length=7, text=texts)
40
+ ```
41
+
42
+ Inspect `texts.items` before using the forecast. A valid tool call does not guarantee that the event was interpreted correctly. With upstream's default non-strict mode, check `texts.failures` for series that were not translated.
43
+
44
+ ## Development
45
+
46
+ From the checkout, install the package in a Python environment and run the smoke test.
47
+
48
+ ```text
49
+ python -m pip install -e .
50
+ python -m unittest discover -s tests
51
+ python -m pip install build twine
52
+ python -m build
53
+ python -m twine check dist/*
54
+ ```
55
+
56
+ See [Releasing Chronos Steering](RELEASE.md) for GitHub Actions and PyPI Trusted Publishing.
57
+
58
+ ## License
59
+
60
+ [Apache License 2.0](LICENSE). Copyright 2026 Nikolaus Spence.
@@ -0,0 +1,24 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "chronos-steering"
7
+ version = "0.1.0a1"
8
+ description = "An independent add-on for steering Chronos-3 forecasts with local or hosted LLMs."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Nikolaus Spence" }]
14
+ dependencies = ["chronos-forecasting==3.0.0"]
15
+
16
+ [project.scripts]
17
+ chronos-steering = "chronos_steering.demo:main"
18
+
19
+ [project.urls]
20
+ Repository = "https://github.com/nikspence/chronos-steering"
21
+ Issues = "https://github.com/nikspence/chronos-steering/issues"
22
+
23
+ [tool.setuptools.packages.find]
24
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,5 @@
1
+ """Text-steering adapters for Chronos-3."""
2
+
3
+ from .translator import OpenAICompatibleTranslator
4
+
5
+ __all__ = ["OpenAICompatibleTranslator"]
@@ -0,0 +1,72 @@
1
+ """Run a synthetic event through translation and optionally forecast it."""
2
+
3
+ import argparse
4
+ import json
5
+ import os
6
+ from dataclasses import asdict
7
+
8
+ import pandas as pd
9
+ from chronos import Chronos3Pipeline
10
+ from chronos.chronos3.text import TranslationError
11
+
12
+ from .translator import OpenAICompatibleTranslator
13
+
14
+
15
+ DEFAULT_EVENT = "Order volume will spike upward on December 12, 2026 due to a one-day promotion."
16
+
17
+
18
+ def main(argv: list[str] | None = None) -> int:
19
+ parser = argparse.ArgumentParser(description=__doc__)
20
+ parser.add_argument("--model", default="frognano:4b", help="Translator model or gateway alias")
21
+ parser.add_argument("--base-url", default="http://localhost:11434/v1")
22
+ parser.add_argument("--api-key-env", help="Name of the environment variable holding the gateway key")
23
+ parser.add_argument("--mode", choices=["tool", "json_schema"], default="tool")
24
+ parser.add_argument("--timeout", type=float, default=300)
25
+ parser.add_argument("--max-tokens", type=int, default=4096)
26
+ parser.add_argument("--reasoning-effort", help="Endpoint-specific thinking budget (for example, none)")
27
+ parser.add_argument("--event", default=DEFAULT_EVENT, help="Scenario for the synthetic daily orders series")
28
+ parser.add_argument("--translate-only", action="store_true", help="Skip the model downloads and forecast")
29
+ parser.add_argument("--checkpoint", default="amazon/chronos-3-tiny")
30
+ parser.add_argument("--device", default="cpu")
31
+ args = parser.parse_args(argv)
32
+ key = os.environ.get(args.api_key_env) if args.api_key_env else None
33
+ if args.api_key_env and not key:
34
+ parser.error(f"set the {args.api_key_env} environment variable")
35
+
36
+ frame = pd.DataFrame({
37
+ "item_id": "orders",
38
+ "timestamp": pd.date_range(end="2026-12-10", periods=56),
39
+ "target": [100 + i // 7 + 3 * (i % 7) for i in range(56)],
40
+ })
41
+ horizon = 7
42
+ try:
43
+ translator = OpenAICompatibleTranslator(
44
+ args.model, base_url=args.base_url, api_key=key, mode=args.mode,
45
+ timeout=args.timeout, max_tokens=args.max_tokens, max_workers=1,
46
+ reasoning_effort=args.reasoning_effort,
47
+ )
48
+ translated = translator.translate_df(frame, args.event, horizon, strict=True)
49
+ except (TranslationError, ValueError) as exc:
50
+ parser.exit(1, f"Translation failed: {exc}\n")
51
+ statements = translated.items["orders"].statements
52
+ print(json.dumps([asdict(statement) for statement in statements], indent=2), flush=True)
53
+ if not statements:
54
+ parser.exit(1, "Chronos accepted no steering statements for this scenario.\n")
55
+ if args.translate_only:
56
+ return 0
57
+
58
+ pipeline = Chronos3Pipeline.from_pretrained(args.checkpoint, device_map=args.device)
59
+ kwargs = {"prediction_length": horizon, "quantile_levels": [0.5]}
60
+ baseline = pipeline.predict_df(frame, **kwargs)
61
+ steered = pipeline.predict_df(frame, text=translated, **kwargs)
62
+ prefix = ["item_id", "timestamp"]
63
+ comparison = baseline[prefix + ["0.5"]].merge(
64
+ steered[prefix + ["0.5"]], on=prefix, suffixes=("_baseline", "_steered"), validate="one_to_one",
65
+ ).rename(columns={"0.5_baseline": "baseline_median", "0.5_steered": "steered_median"})
66
+ comparison["delta"] = comparison["steered_median"] - comparison["baseline_median"]
67
+ print(comparison.to_string(index=False))
68
+ return 0
69
+
70
+
71
+ if __name__ == "__main__":
72
+ raise SystemExit(main())
@@ -0,0 +1,108 @@
1
+ """OpenAI-compatible transport for the Chronos-3 translation workflow."""
2
+
3
+ import json
4
+ from collections.abc import Mapping, Sequence
5
+ from typing import Any, Literal
6
+ from urllib.error import HTTPError, URLError
7
+ from urllib.parse import urlsplit
8
+ from urllib.request import HTTPRedirectHandler, Request, build_opener
9
+
10
+ from chronos.chronos3.text import TranslationError, Translator
11
+
12
+
13
+ class _NoRedirect(HTTPRedirectHandler):
14
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
15
+ return None
16
+
17
+
18
+ class OpenAICompatibleTranslator(Translator):
19
+ """Translate via Chat Completions using Chronos's own prompt and schema.
20
+
21
+ Pass the API root (for example, http://localhost:11434/v1), not the
22
+ /chat/completions URL. Select json_schema explicitly for servers that
23
+ support structured content but do not reliably produce tool calls.
24
+ """
25
+
26
+ def __init__(
27
+ self,
28
+ model: str,
29
+ *,
30
+ base_url: str = "http://localhost:11434/v1",
31
+ api_key: str | None = None,
32
+ mode: Literal["tool", "json_schema"] = "tool",
33
+ timeout: float = 120,
34
+ max_tokens: int = 4096,
35
+ reasoning_effort: str | None = None,
36
+ **kwargs: Any,
37
+ ):
38
+ super().__init__(**kwargs)
39
+ url = urlsplit(base_url)
40
+ if (
41
+ url.scheme not in {"http", "https"} or not url.hostname
42
+ or url.username is not None or url.query or url.fragment
43
+ or url.path.rstrip("/").endswith("/chat/completions")
44
+ ):
45
+ raise ValueError("base_url must be an HTTP(S) API root without credentials")
46
+ if not model.strip() or mode not in {"tool", "json_schema"} or timeout <= 0 or max_tokens <= 0:
47
+ raise ValueError("provide a model, a valid mode, and positive timeout and max_tokens")
48
+ self.model = model
49
+ self.endpoint = base_url.rstrip("/") + "/chat/completions"
50
+ self.api_key = api_key
51
+ self.mode = mode
52
+ self.timeout = timeout
53
+ self.max_tokens = max_tokens
54
+ self.reasoning_effort = reasoning_effort
55
+
56
+ def _complete(self, system: Sequence[str], user: str, tool: Mapping[str, Any]) -> dict[str, Any]:
57
+ payload: dict[str, Any] = {
58
+ "model": self.model,
59
+ "messages": [
60
+ {"role": "system", "content": "\n\n".join(system)},
61
+ {"role": "user", "content": user},
62
+ ],
63
+ "stream": False,
64
+ "max_tokens": self.max_tokens,
65
+ }
66
+ if self.reasoning_effort is not None:
67
+ payload["reasoning_effort"] = self.reasoning_effort
68
+ if self.mode == "tool":
69
+ payload["tools"] = [{"type": "function", "function": {
70
+ "name": tool["name"], "description": tool["description"],
71
+ "parameters": tool["input_schema"],
72
+ }}]
73
+ else:
74
+ payload["messages"][0]["content"] += (
75
+ f"\n\nReturn the arguments for {tool['name']} as a JSON object. "
76
+ "Return only the object, without calling a tool."
77
+ )
78
+ payload["response_format"] = {"type": "json_schema", "json_schema": {
79
+ "name": tool["name"], "schema": tool["input_schema"],
80
+ }}
81
+ headers = {"Content-Type": "application/json"}
82
+ if self.api_key:
83
+ headers["Authorization"] = f"Bearer {self.api_key}"
84
+ request = Request(self.endpoint, data=json.dumps(payload).encode(), headers=headers)
85
+ try:
86
+ with build_opener(_NoRedirect()).open(request, timeout=self.timeout) as response:
87
+ choice = json.load(response)["choices"][0]
88
+ if choice.get("finish_reason") in {"length", "content_filter"}:
89
+ raise TranslationError("Chat Completions returned truncated or filtered output")
90
+ message = choice["message"]
91
+ if self.mode == "tool":
92
+ calls = [call["function"]["arguments"] for call in message.get("tool_calls") or []
93
+ if call.get("function", {}).get("name") == tool["name"]]
94
+ if len(calls) != 1:
95
+ raise TranslationError("Expected exactly one call to the Chronos translation tool")
96
+ raw = calls[0]
97
+ else:
98
+ raw = message["content"]
99
+ arguments = json.loads(raw)
100
+ if not isinstance(arguments, dict):
101
+ raise TranslationError("Chronos translation arguments must be a JSON object")
102
+ return arguments
103
+ except HTTPError as exc:
104
+ raise TranslationError(f"Chat Completions returned HTTP {exc.code}") from None
105
+ except (URLError, TimeoutError, OSError):
106
+ raise TranslationError("Could not reach the Chat Completions endpoint") from None
107
+ except (KeyError, IndexError, TypeError, ValueError, AttributeError):
108
+ raise TranslationError("Invalid Chat Completions response or JSON arguments") from None
@@ -0,0 +1,74 @@
1
+ Metadata-Version: 2.4
2
+ Name: chronos-steering
3
+ Version: 0.1.0a1
4
+ Summary: An independent add-on for steering Chronos-3 forecasts with local or hosted LLMs.
5
+ Author: Nikolaus Spence
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Repository, https://github.com/nikspence/chronos-steering
8
+ Project-URL: Issues, https://github.com/nikspence/chronos-steering/issues
9
+ Requires-Python: >=3.10
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: chronos-forecasting==3.0.0
13
+ Dynamic: license-file
14
+
15
+ # Chronos Steering
16
+
17
+ An independent add-on for steering Chronos-3 forecasts with local or hosted LLMs.
18
+
19
+ Describe an event such as a promotion or an outage in plain language. An LLM translates that scenario into structured statements, and Amazon's [chronos-forecasting](https://github.com/amazon-science/chronos-forecasting) package runs the forecast locally. This project is not a fork or an official Amazon package.
20
+
21
+ ## Try it locally
22
+
23
+ Install from the checkout in a Python environment with a compatible PyTorch build. The adapter is pinned to Chronos Forecasting 3.0.0 because it implements that release's translator hook.
24
+
25
+ ```text
26
+ python -m pip install .
27
+ chronos-steering --model frognano:4b --reasoning-effort none --translate-only
28
+ chronos-steering --model frognano:4b --reasoning-effort none
29
+ ```
30
+
31
+ Use a model that is already installed in Ollama or pass another model tag. Ollama must be running at `http://localhost:11434` for the default configuration. The example uses synthetic daily orders and prints the accepted event statements. The full run also prints the baseline median, steered median, and difference for each forecast day. It downloads the Chronos-3 Tiny checkpoint and the separate text encoder on first use. The translation-only run does not download either.
32
+
33
+ ## Use an OpenAI-compatible gateway
34
+
35
+ For LiteLLM, set `LITELLM_API_KEY` in your shell and use a gateway alias that supports tool calls.
36
+
37
+ ```text
38
+ chronos-steering --base-url https://gateway.example/v1 --api-key-env LITELLM_API_KEY --model YOUR_ALIAS --translate-only
39
+ ```
40
+
41
+ Pass the API root, not the full Chat Completions URL. The service receives the Chronos translation prompt, including the scenario and any series context upstream includes in that prompt. Forecast inference remains local. The CLI never automatically switches from a local to a hosted translator.
42
+
43
+ Tool calls are the default. Try `--mode json_schema` only if the selected endpoint and model support schema-constrained responses. Likewise, omit `--reasoning-effort` if the provider does not accept that parameter. Chronos uses a long translation prompt, so a slow local model may need a larger `--timeout`. Endpoint compatibility and translation quality vary by model. LM Studio, llama.cpp, FastFlowLM, Bedrock Mantle, and OpenRouter are candidates for the same adapter, not qualified backends for this release.
44
+
45
+ ## Python API
46
+
47
+ ```python
48
+ from chronos_steering import OpenAICompatibleTranslator
49
+
50
+ translator = OpenAICompatibleTranslator("frognano:4b")
51
+ # history has item_id, timestamp and target columns.
52
+ texts = translator.translate_df(history, scenario, prediction_length=7, strict=True)
53
+ forecast = pipeline.predict_df(history, prediction_length=7, text=texts)
54
+ ```
55
+
56
+ Inspect `texts.items` before using the forecast. A valid tool call does not guarantee that the event was interpreted correctly. With upstream's default non-strict mode, check `texts.failures` for series that were not translated.
57
+
58
+ ## Development
59
+
60
+ From the checkout, install the package in a Python environment and run the smoke test.
61
+
62
+ ```text
63
+ python -m pip install -e .
64
+ python -m unittest discover -s tests
65
+ python -m pip install build twine
66
+ python -m build
67
+ python -m twine check dist/*
68
+ ```
69
+
70
+ See [Releasing Chronos Steering](RELEASE.md) for GitHub Actions and PyPI Trusted Publishing.
71
+
72
+ ## License
73
+
74
+ [Apache License 2.0](LICENSE). Copyright 2026 Nikolaus Spence.
@@ -0,0 +1,15 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/chronos_steering/__init__.py
5
+ src/chronos_steering/demo.py
6
+ src/chronos_steering/translator.py
7
+ src/chronos_steering.egg-info/PKG-INFO
8
+ src/chronos_steering.egg-info/SOURCES.txt
9
+ src/chronos_steering.egg-info/dependency_links.txt
10
+ src/chronos_steering.egg-info/entry_points.txt
11
+ src/chronos_steering.egg-info/requires.txt
12
+ src/chronos_steering.egg-info/top_level.txt
13
+ tests/test_demo.py
14
+ tests/test_package.py
15
+ tests/test_translator.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ chronos-steering = chronos_steering.demo:main
@@ -0,0 +1 @@
1
+ chronos-forecasting==3.0.0
@@ -0,0 +1,53 @@
1
+ import io
2
+ import unittest
3
+ from contextlib import redirect_stderr, redirect_stdout
4
+ from types import SimpleNamespace
5
+ from unittest.mock import patch
6
+
7
+ import pandas as pd
8
+ from chronos.chronos3.text import Statement
9
+
10
+ from chronos_steering.demo import main
11
+
12
+
13
+ class DemoTest(unittest.TestCase):
14
+ @patch("chronos_steering.demo.Chronos3Pipeline")
15
+ @patch("chronos_steering.demo.OpenAICompatibleTranslator")
16
+ def test_translate_only_does_not_load_checkpoint(self, translator, pipeline):
17
+ translator.return_value.translate_df.return_value = SimpleNamespace(items={
18
+ "orders": SimpleNamespace(statements=(Statement("Orders spike.", "spike"),)),
19
+ })
20
+ output = io.StringIO()
21
+ with redirect_stdout(output):
22
+ self.assertEqual(main(["--translate-only"]), 0)
23
+ self.assertIn("Orders spike.", output.getvalue())
24
+ pipeline.from_pretrained.assert_not_called()
25
+
26
+ @patch("chronos_steering.demo.Chronos3Pipeline")
27
+ @patch("chronos_steering.demo.OpenAICompatibleTranslator")
28
+ def test_forecast_compares_the_same_series_and_dates(self, translator, pipeline):
29
+ texts = SimpleNamespace(items={
30
+ "orders": SimpleNamespace(statements=(Statement("Orders spike.", "spike"),)),
31
+ })
32
+ translator.return_value.translate_df.return_value = texts
33
+ forecast = pipeline.from_pretrained.return_value.predict_df
34
+ baseline = pd.DataFrame({"item_id": ["orders"], "timestamp": [pd.Timestamp("2026-12-12")],
35
+ "0.5": [100.0]})
36
+ forecast.side_effect = [baseline, baseline.assign(**{"0.5": [120.0]})]
37
+ output = io.StringIO()
38
+ with redirect_stdout(output):
39
+ self.assertEqual(main([]), 0)
40
+ self.assertIn("20.0", output.getvalue())
41
+ self.assertNotIn("text", forecast.call_args_list[0].kwargs)
42
+ self.assertIs(forecast.call_args_list[1].kwargs["text"], texts)
43
+
44
+ @patch("chronos_steering.demo.OpenAICompatibleTranslator")
45
+ def test_empty_translation_fails_loudly(self, translator):
46
+ translator.return_value.translate_df.return_value = SimpleNamespace(items={
47
+ "orders": SimpleNamespace(statements=()),
48
+ })
49
+ with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()) as error:
50
+ with self.assertRaises(SystemExit) as exit_context:
51
+ main(["--translate-only"])
52
+ self.assertEqual(exit_context.exception.code, 1)
53
+ self.assertIn("no steering statements", error.getvalue())
@@ -0,0 +1,8 @@
1
+ import importlib
2
+ import unittest
3
+
4
+
5
+ class PackageTest(unittest.TestCase):
6
+ def test_package_is_importable(self):
7
+ package = importlib.import_module("chronos_steering")
8
+ self.assertEqual(package.__name__, "chronos_steering")
@@ -0,0 +1,86 @@
1
+ import io
2
+ import json
3
+ import unittest
4
+ from unittest.mock import patch
5
+ from urllib.error import HTTPError
6
+
7
+ import pandas as pd
8
+ from chronos.chronos3.text import TranslationError
9
+
10
+ from chronos_steering import OpenAICompatibleTranslator
11
+
12
+
13
+ TOOL = {"name": "translate", "description": "Translate", "input_schema": {"type": "object"}}
14
+
15
+
16
+ def response(message, finish="stop"):
17
+ return io.BytesIO(json.dumps({"choices": [
18
+ {"message": message, "finish_reason": finish},
19
+ ]}).encode())
20
+
21
+
22
+ @patch("chronos_steering.translator.build_opener")
23
+ class TranslatorTest(unittest.TestCase):
24
+ def test_real_translate_df_contract(self, opener):
25
+ def complete(request, *, timeout):
26
+ self.assertEqual(request.full_url, "http://localhost:11434/v1/chat/completions")
27
+ self.assertIsNone(request.get_header("Authorization"))
28
+ payload = json.loads(request.data)
29
+ self.assertEqual(payload["model"], "frognano:4b")
30
+ spec = payload["tools"][0]["function"]
31
+ self.assertIn("per_variate", spec["parameters"]["properties"])
32
+ self.assertIn("promotion", payload["messages"][1]["content"])
33
+ arguments = {"per_variate": [{"variate": "target", "statements": [{
34
+ "sentence": "The series spikes upward on 2026-01-12.",
35
+ "type": "spike", "direction": "up", "source": "text", "confidence": "high",
36
+ "anchor": {"kind": "point", "episodes": [{
37
+ "start_step": 1, "end_step": 1,
38
+ "start_date": "2026-01-12", "end_date": "2026-01-12",
39
+ }]},
40
+ }]}]}
41
+ return response({"tool_calls": [{"function": {
42
+ "name": spec["name"], "arguments": json.dumps(arguments),
43
+ }}]}, "tool_calls")
44
+
45
+ opener.return_value.open.side_effect = complete
46
+ frame = pd.DataFrame({
47
+ "item_id": "a", "timestamp": pd.date_range("2026-01-01", periods=10),
48
+ "target": range(10),
49
+ })
50
+ translator = OpenAICompatibleTranslator("frognano:4b")
51
+ translated = translator.translate_df(frame, "A promotion on January 12", 3, strict=True)
52
+ self.assertEqual(translated.prediction_length, 3)
53
+ statement, = translated.items["a"].statements
54
+ self.assertEqual(statement.type, "spike")
55
+ self.assertEqual(statement.episodes, ((1, 1),))
56
+ self.assertEqual(translated.failures, {})
57
+ opener.return_value.open.assert_called_once()
58
+
59
+ def test_json_schema_and_auth(self, opener):
60
+ opener.return_value.open.return_value = response({"content": '{"per_variate":[]}'})
61
+ translator = OpenAICompatibleTranslator(
62
+ "gateway-model", base_url="https://example.test/v1/", api_key="fake-key",
63
+ mode="json_schema", reasoning_effort="none",
64
+ )
65
+ self.assertEqual(translator._complete(["system"], "user", TOOL), {"per_variate": []})
66
+ request = opener.return_value.open.call_args.args[0]
67
+ self.assertEqual(request.get_header("Authorization"), "Bearer fake-key")
68
+ payload = json.loads(request.data)
69
+ self.assertNotIn("tools", payload)
70
+ self.assertEqual(payload["reasoning_effort"], "none")
71
+ self.assertEqual(payload["response_format"]["json_schema"]["schema"], TOOL["input_schema"])
72
+
73
+ def test_missing_tool_and_truncated_response(self, opener):
74
+ translator = OpenAICompatibleTranslator("local")
75
+ for finish in ("stop", "length"):
76
+ with self.subTest(finish=finish):
77
+ opener.return_value.open.return_value = response({"content": "{}"}, finish)
78
+ with self.assertRaises(TranslationError):
79
+ translator._complete(["system"], "user", TOOL)
80
+
81
+ def test_http_error_does_not_expose_response_body(self, opener):
82
+ opener.return_value.open.side_effect = HTTPError(
83
+ "https://example.test/v1/chat/completions", 401, "sensitive", {}, None,
84
+ )
85
+ with self.assertRaisesRegex(TranslationError, "^Chat Completions returned HTTP 401$"):
86
+ OpenAICompatibleTranslator("local")._complete(["system"], "user", TOOL)