llmflock 0.0.2__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.
- llmflock-0.0.2/LICENSE.txt +201 -0
- llmflock-0.0.2/PKG-INFO +13 -0
- llmflock-0.0.2/README.md +48 -0
- llmflock-0.0.2/llmflock/__init__.py +0 -0
- llmflock-0.0.2/llmflock/__main__.py +4 -0
- llmflock-0.0.2/llmflock/cli.py +506 -0
- llmflock-0.0.2/llmflock/config.py +101 -0
- llmflock-0.0.2/llmflock/ollama_ollama.py +28 -0
- llmflock-0.0.2/llmflock/simonw_llm.py +18 -0
- llmflock-0.0.2/llmflock.egg-info/PKG-INFO +13 -0
- llmflock-0.0.2/llmflock.egg-info/SOURCES.txt +15 -0
- llmflock-0.0.2/llmflock.egg-info/dependency_links.txt +1 -0
- llmflock-0.0.2/llmflock.egg-info/entry_points.txt +2 -0
- llmflock-0.0.2/llmflock.egg-info/requires.txt +7 -0
- llmflock-0.0.2/llmflock.egg-info/top_level.txt +1 -0
- llmflock-0.0.2/pyproject.toml +34 -0
- llmflock-0.0.2/setup.cfg +4 -0
|
@@ -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.
|
llmflock-0.0.2/PKG-INFO
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: llmflock
|
|
3
|
+
Version: 0.0.2
|
|
4
|
+
Summary: LLM Runner Control is a CLI tool to interact with local and remote LLM, define multiple scenario variations (model × prompt × options), run it over a dataset and capture structured results for comparison or to build knowledge through meta analysis.
|
|
5
|
+
License-File: LICENSE.txt
|
|
6
|
+
Requires-Dist: jsonschema
|
|
7
|
+
Requires-Dist: llm
|
|
8
|
+
Requires-Dist: llm-gpt4all
|
|
9
|
+
Requires-Dist: llm-ollama
|
|
10
|
+
Requires-Dist: ollama
|
|
11
|
+
Requires-Dist: python-dotenv
|
|
12
|
+
Requires-Dist: PyYAML
|
|
13
|
+
Dynamic: license-file
|
llmflock-0.0.2/README.md
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# LLM Runner Control
|
|
2
|
+
|
|
3
|
+
A CLI tool to interact with local and remote LLM, define multiple scenario variations (model × prompt × options), run it over a dataset and capture structured results for comparison or to build knowledge through meta analysis.
|
|
4
|
+
|
|
5
|
+
DRAFT: more on the objective of this tool: it is built to run extraction the same structured data (`data_schemas.default`) in a list (`datasets.default`) of documents (`document_sets.default`) usings LLM and output tabular data. It is designed to run the extraction several times - or variations - (`scenarios.default.variations`) with different models, prompts or model options (temperature, top_p). It also designed to repeat one variation several times (reference to non-deterministic behaviour of LLMs...) (`scenarios.default.variations.repeat`).
|
|
6
|
+
|
|
7
|
+
Note: actually this is not limited to extraction of structured data (ie a task where the research data is already in the input document but drowned in it), but to any task which generate structured data (because then structured data can then be easily compared/assessed)
|
|
8
|
+
|
|
9
|
+
Note 2: maybe that tool is more aimed at smaller models (local or cloud-hosted). By design it will have to be run **very** repetitively on big dataset so cost of running huge models from the frontier labs can be dissuasive. But big models need to be tested too sometimes to make sure the small models jobs remains relevant.
|
|
10
|
+
|
|
11
|
+
Note 3: how to we rate and compare (benchmark) the resulting output structured data, what will be the coverage of the comparison part of this tool?
|
|
12
|
+
|
|
13
|
+
- wanted to find an example of llm comparison tool: found [this one](https://www.simonpcouch.com/blog/2025-04-01-gemini-2-5-pro) (here applied to Gemini 2.5 Pro) from Simon P. Couch ([via](https://simonwillison.net/2026/Jan/20/electricity-use-of-ai-coding-agents/) then [via](https://www.simonpcouch.com/blog/2026-01-20-cc-impact/)) : which lead me to a even more popular approach ? [https://inspect.aisi.org.uk/] ..... take-aways are:
|
|
14
|
+
- use a repeat parameter (epoch) to "Evaluate each sample multiple times to better quantify variation"
|
|
15
|
+
|
|
16
|
+
Note 4: more thought one the viewing result part: need to have a tool to aggregate results, adding comparison with one selected IDEAL run and output all of it in a easy spreadsheet format (csv, excel) for further analysis and visualization. by design, the tool will produce was amount of llm-generated data (over dataset and multiple variation) and exact match is illusionist / unrealistic goal. While study of individual result is still valuable to understand, an essential metric is CONVERGENCE, not EQUALITY when comparing generated data.
|
|
17
|
+
|
|
18
|
+
Hence that tool `llmrunctl` aim to keep it to minimum, focusing on the run+extract part.
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
**On where it sits in the ecosystem of LLM tools:** It is a LLM gateway: meaning it can call different LLM providers (local inference framework or cloud-hosted) with a rudimentary plugin system. If the project matures enough it could be beneficial the transition to a more established LLM gateway tool (like liteLLm, anyLLM).
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
## Getting started
|
|
25
|
+
|
|
26
|
+
1. [Ollama](https://ollama.com/download) should be installed and running
|
|
27
|
+
2. Clone the repository and install it with pip: `pip install .` (At this stage the package is not distributed, ie not published to PyPI, hence cannot be installed directly from PyPI)
|
|
28
|
+
1. Or use `pip install -e .` if you want to install in editable mode.
|
|
29
|
+
|
|
30
|
+
## Usage
|
|
31
|
+
|
|
32
|
+
To run the example in `data/example1-ev`, use the command: `llmr --configfile=data/example1-ev/config.yaml` or `llmr --configfile=data/example1-ev/config.yaml --debug`
|
|
33
|
+
|
|
34
|
+
### Examples
|
|
35
|
+
|
|
36
|
+
- submitting a prompt: `llmrunctl "extract Company and Location entities in JSON format from the following text: 'EU clears merger of Essilor , Luxottica without conditions'"`
|
|
37
|
+
- switch from the default model: `llmrunctl "extract Company and Location entities in JSON format from the following text: 'EU clears merger of Essilor , Luxottica without conditions'" -m gpt-oss` (note: the model need to be defined in the default config)
|
|
38
|
+
- specify repeat count: `llmrunctl "extract Company and Location entities in JSON format from the following text: 'EU clears merger of Essilor , Luxottica without conditions'" -r 3`
|
|
39
|
+
- specify a CSV dataset: `llmrunctl --prompt-filename=data/example4-noconfig/PROMPT.md --dataset-filename=data/example4-noconfig/dataset.csv`
|
|
40
|
+
- specify a schema: `llmrunctl --prompt-filename=data/example4-noconfig/PROMPT.dates.md --dataset-filename=data/example4-noconfig/dataset.dates.csv --schema 'start int NULL, end int NULL'`
|
|
41
|
+
- `llmrunctl "What years mark the start and end of Queen Elizabeth II's reign in the United Kingdom?" --schema 'start int, end int'`
|
|
42
|
+
- `llmrunctl "What years mark the start and end of King Charles III's reign in the United Kingdom?" --schema 'start int NULL, end int NULL'`
|
|
43
|
+
- specify a multi-schema: `llmrunctl --prompt-filename=data/example4-noconfig/PROMPT.borders.md --dataset-filename=data/example4-noconfig/dataset.borders.csv --schema-multi 'name str'`
|
|
44
|
+
|
|
45
|
+
- There are also currently 3 working examples based on provided config file (and associated data):
|
|
46
|
+
- `llmrunctl --configfile=data/example1-ev/config.yaml`
|
|
47
|
+
- `llmrunctl --configfile=data/example2-img-transform/config.yaml`
|
|
48
|
+
- `llmrunctl --configfile=data/example3-finance/config.yaml`
|
|
File without changes
|
|
@@ -0,0 +1,506 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import csv
|
|
3
|
+
import itertools
|
|
4
|
+
import re
|
|
5
|
+
|
|
6
|
+
import llmflock.config as config_module
|
|
7
|
+
from llmflock.concise_schema.utils_external import schema_dsl
|
|
8
|
+
from llmflock.concise_schema.prompt_instructions import build_schema_prompt
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
from datetime import datetime
|
|
12
|
+
from time import perf_counter
|
|
13
|
+
from copy import deepcopy
|
|
14
|
+
from jsonschema import validate, ValidationError
|
|
15
|
+
|
|
16
|
+
# from dotenv import load_dotenv
|
|
17
|
+
# WIP: about adding another provider (openrouter)
|
|
18
|
+
|
|
19
|
+
import logging
|
|
20
|
+
import yaml
|
|
21
|
+
from llmflock.ollama_ollama import ollama_ollama_call
|
|
22
|
+
from llmflock.simonw_llm import simonw_llm_call
|
|
23
|
+
|
|
24
|
+
logger = logging.getLogger(__name__)
|
|
25
|
+
|
|
26
|
+
parser = argparse.ArgumentParser(
|
|
27
|
+
description="Run multiple LLM scenarios over dataset.")
|
|
28
|
+
parser.add_argument('prompt', nargs='?', default=None,
|
|
29
|
+
help="Prompt text to submit (mandatory when no --configfile is given)")
|
|
30
|
+
parser.add_argument('-d', '--debug', action='store_true', default=False,
|
|
31
|
+
help="keep LLM prompts, responses, execution time (+...)")
|
|
32
|
+
parser.add_argument('--dry-run', action='store_true', default=False,)
|
|
33
|
+
parser.add_argument('-c', '--configfile', default=None,
|
|
34
|
+
help="Specify the configuration file to use (without it, the built-in default config is used)")
|
|
35
|
+
parser.add_argument('--scenario', default='default',
|
|
36
|
+
help="Specify the scenario to run (see config.yaml)")
|
|
37
|
+
parser.add_argument('--dataset-filename', default=None,
|
|
38
|
+
help="Override the dataset file specified in config.yaml")
|
|
39
|
+
parser.add_argument('--prompt-filename', default=None,
|
|
40
|
+
help="Override the prompt template file specified in config.yaml")
|
|
41
|
+
parser.add_argument('-m', '--model', default=None,
|
|
42
|
+
help="Override the models specified in config.yaml (Comma-separated list of model names)")
|
|
43
|
+
parser.add_argument('-r', '--repeats', type=int, default=None,
|
|
44
|
+
help="Override the number of repeats of each variation")
|
|
45
|
+
parser.add_argument('--schema', default=None,
|
|
46
|
+
help="Override the JSON schema")
|
|
47
|
+
parser.add_argument('--schema-multi', default=None,
|
|
48
|
+
help="Override the JSON schema")
|
|
49
|
+
args = parser.parse_args()
|
|
50
|
+
|
|
51
|
+
# Ollama-powered models all accept the Ollama modelfile parameters as options
|
|
52
|
+
# see: https://github.com/ollama/ollama/blob/main/docs/modelfile.md#parameter
|
|
53
|
+
|
|
54
|
+
# Hard-coded max tokens (never part of the variations)
|
|
55
|
+
# TODO: move somewhere else?
|
|
56
|
+
MAX_PREDICT_TOKENS = 8192
|
|
57
|
+
|
|
58
|
+
# trying to stick to [Google Python Style Guide](https://google.github.io/styleguide/pyguide.html)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def logger_debug_file(content, filename, directory=None):
|
|
62
|
+
"""Write debug text to a file in the specified directory."""
|
|
63
|
+
if args.debug:
|
|
64
|
+
if directory is None:
|
|
65
|
+
directory = config_module.log_dir
|
|
66
|
+
with open(os.path.join(directory, filename), 'w') as f:
|
|
67
|
+
f.write(content)
|
|
68
|
+
logger.debug(f"File saved: {os.path.join(directory, filename)}")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def build_prompt(template: str, variables: dict) -> str:
|
|
73
|
+
""" Template processing function to build the prompt.
|
|
74
|
+
|
|
75
|
+
:param template:
|
|
76
|
+
:param variables:
|
|
77
|
+
:return:
|
|
78
|
+
"""
|
|
79
|
+
# No variable at all (eg a prompt submitted directly on the command line):
|
|
80
|
+
# the template IS the prompt. Skipping .format() also keeps any literal
|
|
81
|
+
# brace of that prompt intact.
|
|
82
|
+
if not variables:
|
|
83
|
+
return template
|
|
84
|
+
|
|
85
|
+
# if a variable name is suffixed by "_filename", load the file content
|
|
86
|
+
# into a new variable named without that suffix (eg "doc_content_filename"
|
|
87
|
+
# -> "doc_content")
|
|
88
|
+
variables_loaded = {}
|
|
89
|
+
for k, v in variables.items():
|
|
90
|
+
if k.endswith('_filename'):
|
|
91
|
+
var_name = k[:-len('_filename')]
|
|
92
|
+
with open(v, 'r') as file:
|
|
93
|
+
variables_loaded[var_name] = file.read()
|
|
94
|
+
else:
|
|
95
|
+
variables_loaded[k] = v
|
|
96
|
+
|
|
97
|
+
prompt = template.format(**variables_loaded)
|
|
98
|
+
# for k, v in vars.items():
|
|
99
|
+
# placeholder = f'<{k}>'
|
|
100
|
+
# prompt = prompt.replace(placeholder, v)
|
|
101
|
+
|
|
102
|
+
return prompt
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def extract_validate_json(text: str, schema: dict) -> dict:
|
|
106
|
+
extraction = {
|
|
107
|
+
'status': 0,
|
|
108
|
+
'message': None,
|
|
109
|
+
'data': {},
|
|
110
|
+
}
|
|
111
|
+
json_match = re.findall(r"```json\n(.*?)\n```", text, re.DOTALL)
|
|
112
|
+
if json_match:
|
|
113
|
+
logger.debug('JSON code block found in LLM response')
|
|
114
|
+
# Extract the JSON content from the last match
|
|
115
|
+
# Note: we use the last match to avoid issues with multiple JSON
|
|
116
|
+
# blocks in the response
|
|
117
|
+
json_content = json_match[-1].strip()
|
|
118
|
+
|
|
119
|
+
try:
|
|
120
|
+
extraction['data'] = json.loads(json_content)
|
|
121
|
+
validate(instance=extraction['data'], schema=schema)
|
|
122
|
+
|
|
123
|
+
except json.JSONDecodeError as e:
|
|
124
|
+
logger.error(f'Invalid JSON from LLM: {str(e)}')
|
|
125
|
+
logger.error(f'Raw JSON content: {json_content[:200]}...')
|
|
126
|
+
extraction['message'] = f'Invalid JSON from LLM: {str(e)} ; Raw JSON content: {json_content[:200]}...'
|
|
127
|
+
extraction['status'] = 2
|
|
128
|
+
except ValidationError as e:
|
|
129
|
+
logger.error(f'JSON does not conform to schema: {str(e)}')
|
|
130
|
+
logger.error(f'Extracted JSON content: {json_content[:200]}...')
|
|
131
|
+
extraction['message'] = f'JSON does not conform to schema: {str(e)} ; Extracted JSON content: {json_content[:200]}...'
|
|
132
|
+
extraction['status'] = 3
|
|
133
|
+
else:
|
|
134
|
+
logger.error(f'Failed to extract JSON fenced-block from LLM response')
|
|
135
|
+
extraction['message'] = 'Failed to extract JSON fenced-block from LLM response'
|
|
136
|
+
extraction['status'] = 1
|
|
137
|
+
|
|
138
|
+
return extraction
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def call_llm(prompt: str, model_config: dict, model_options: dict) -> dict:
|
|
142
|
+
# generate options by mapping model_options keys to model specific option keys
|
|
143
|
+
model_options_specific = {}
|
|
144
|
+
for key, value in model_options.items():
|
|
145
|
+
if key in model_config['options']:
|
|
146
|
+
model_options_specific[model_config['options'][key]] = value
|
|
147
|
+
|
|
148
|
+
# call appropriate backend
|
|
149
|
+
if model_config['backend'] == 'ollama_ollama':
|
|
150
|
+
response = ollama_ollama_call(prompt, model_config['name'],
|
|
151
|
+
model_options_specific)
|
|
152
|
+
elif model_config['backend'] == 'simonw_llm':
|
|
153
|
+
response = simonw_llm_call(prompt, model_config['name'],
|
|
154
|
+
model_options_specific)
|
|
155
|
+
else:
|
|
156
|
+
raise ValueError(f"Unknown backend: {model_config['backend']}")
|
|
157
|
+
|
|
158
|
+
return response
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def build_variations(scenario_variations: dict) -> list:
|
|
162
|
+
"""Build the list of variations to run (the "matrix"), one dict per LLM call
|
|
163
|
+
(per dataset record).
|
|
164
|
+
|
|
165
|
+
Every parameter is optional but `prompts`: an omitted parameter simply
|
|
166
|
+
contributes a single "unset" value to the product.
|
|
167
|
+
|
|
168
|
+
:param scenario_variations: the `variations` object of the active scenario
|
|
169
|
+
:return: the flat list of variations, in nested-loop order
|
|
170
|
+
"""
|
|
171
|
+
document_sets = scenario_variations.get('document_sets') or [None]
|
|
172
|
+
prompts = scenario_variations.get('prompts') or []
|
|
173
|
+
prompt_const_embeds = scenario_variations.get('prompt_const_embeds') or [None]
|
|
174
|
+
models = scenario_variations.get('models')
|
|
175
|
+
model_options_config = scenario_variations.get('model_options') or {}
|
|
176
|
+
repeats = scenario_variations.get('repeats', 1)
|
|
177
|
+
|
|
178
|
+
# the model options are generic: any key defined in the scenario is a
|
|
179
|
+
# dimension of the matrix, none of them is mandatory.
|
|
180
|
+
option_names = list(model_options_config.keys())
|
|
181
|
+
option_value_combinations = list(itertools.product(
|
|
182
|
+
*[model_options_config[name] for name in option_names]))
|
|
183
|
+
|
|
184
|
+
variations = []
|
|
185
|
+
for (document_set, prompt, prompt_const_embed, model, option_values,
|
|
186
|
+
repeat) in itertools.product(document_sets, prompts,
|
|
187
|
+
prompt_const_embeds, models,
|
|
188
|
+
option_value_combinations,
|
|
189
|
+
range(1, repeats + 1)):
|
|
190
|
+
variations.append({
|
|
191
|
+
'document_set': document_set,
|
|
192
|
+
'prompt': prompt,
|
|
193
|
+
'prompt_const_embed': prompt_const_embed,
|
|
194
|
+
'model': model,
|
|
195
|
+
'model_options': dict(zip(option_names, option_values)),
|
|
196
|
+
'repeat': repeat,
|
|
197
|
+
})
|
|
198
|
+
|
|
199
|
+
return variations
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def variations_breakdown(scenario_variations: dict) -> str:
|
|
203
|
+
"""Human readable breakdown of the variations matrix (eg "1 document set x
|
|
204
|
+
2 prompt x 1 model x 3 temperature x 1 repeat")."""
|
|
205
|
+
factors = [
|
|
206
|
+
(len(scenario_variations.get('document_sets') or [None]), 'document set'),
|
|
207
|
+
(len(scenario_variations.get('prompts') or []), 'prompt'),
|
|
208
|
+
(len(scenario_variations.get('prompt_const_embeds') or [None]), 'prompt const embed'),
|
|
209
|
+
(len(scenario_variations.get('models') or [None]), 'model'),
|
|
210
|
+
]
|
|
211
|
+
for parameter, values in (scenario_variations.get('model_options') or {}).items():
|
|
212
|
+
factors.append((len(values), parameter))
|
|
213
|
+
factors.append((scenario_variations.get('repeats', 1), 'repeat'))
|
|
214
|
+
|
|
215
|
+
return ' x '.join(f'{count} {label}' for count, label in factors)
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def variation_label(variation: dict) -> dict:
|
|
219
|
+
"""The identity of a variation, as stored in output.jsonl and used to name
|
|
220
|
+
the debug files."""
|
|
221
|
+
document_set = variation['document_set']
|
|
222
|
+
prompt_const_embed = variation['prompt_const_embed']
|
|
223
|
+
return {
|
|
224
|
+
'document': document_set['name'] if document_set else None,
|
|
225
|
+
'prompt': variation['prompt']['name'],
|
|
226
|
+
'prompt_const_embed': prompt_const_embed['name'] if prompt_const_embed else None,
|
|
227
|
+
'model': variation['model'],
|
|
228
|
+
'model_options': variation['model_options'],
|
|
229
|
+
'repeat': variation['repeat'],
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def variation_slug(data_id, label: dict) -> str:
|
|
234
|
+
"""Filename-friendly rendering of a variation label."""
|
|
235
|
+
options = '-'.join(f'{name}{value}'
|
|
236
|
+
for name, value in label['model_options'].items())
|
|
237
|
+
parts = [str(data_id), str(label['document']), str(label['prompt']),
|
|
238
|
+
str(label['prompt_const_embed']), str(label['model'])]
|
|
239
|
+
if options:
|
|
240
|
+
parts.append(options)
|
|
241
|
+
parts.append(f'repeat{label["repeat"]}')
|
|
242
|
+
return '-'.join(parts)
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def run_variation(data: dict, variation: dict, models: dict, schema: dict | None):
|
|
246
|
+
"""Run a single variation for a single dataset record (one LLM call)."""
|
|
247
|
+
data_id = data.get('id')
|
|
248
|
+
label = variation_label(variation)
|
|
249
|
+
|
|
250
|
+
# the document set is optional: without it the record carries no
|
|
251
|
+
# variation-specific data
|
|
252
|
+
document_set = variation['document_set']
|
|
253
|
+
if document_set is None:
|
|
254
|
+
document = {}
|
|
255
|
+
else:
|
|
256
|
+
docs_by_id = {}
|
|
257
|
+
# For later: for each run of run_variations (ie for each data item)
|
|
258
|
+
# we are doing this load file operation for the same file. I note that
|
|
259
|
+
# it can be optimized but I think there may be not significant gain in
|
|
260
|
+
# the overall performance of the process. So keeping it simple for now.
|
|
261
|
+
with open(document_set['filename'], 'r') as infile:
|
|
262
|
+
for line in infile:
|
|
263
|
+
if not line.strip():
|
|
264
|
+
continue
|
|
265
|
+
item = json.loads(line.strip())
|
|
266
|
+
docs_by_id[item['id']] = item
|
|
267
|
+
document = docs_by_id[data_id]
|
|
268
|
+
|
|
269
|
+
# the prompt template is either passed directly ('content')
|
|
270
|
+
# or read from a file ('filename')
|
|
271
|
+
template = variation['prompt']['template']
|
|
272
|
+
if template.get('content') is not None:
|
|
273
|
+
prompt_template = template['content']
|
|
274
|
+
else:
|
|
275
|
+
with open(template['filename'], 'r') as file:
|
|
276
|
+
prompt_template = file.read()
|
|
277
|
+
|
|
278
|
+
prompt_const_embed = variation['prompt_const_embed']
|
|
279
|
+
if prompt_const_embed is None:
|
|
280
|
+
const_embed_variables = {}
|
|
281
|
+
else:
|
|
282
|
+
# convert to the "<var_name>_filename" convention expected by build_prompt
|
|
283
|
+
const_embed_variables = {
|
|
284
|
+
f'{var_name}_filename': var_config['filename']
|
|
285
|
+
for var_name, var_config in prompt_const_embed['variables'].items()
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
variables = {**data, **document, **const_embed_variables}
|
|
289
|
+
prompt = build_prompt(prompt_template, variables)
|
|
290
|
+
|
|
291
|
+
# the prompt only depends on the record + document set + prompt + const
|
|
292
|
+
# embed, hence the shorter filename here
|
|
293
|
+
logger_debug_file(prompt, 'prompt-{}-{}-{}-{}.md'.format(
|
|
294
|
+
data_id, label['document'], label['prompt'], label['prompt_const_embed']))
|
|
295
|
+
|
|
296
|
+
model_config = models[variation['model']]
|
|
297
|
+
model_options = {**variation['model_options'],
|
|
298
|
+
'max_predict_tokens': MAX_PREDICT_TOKENS}
|
|
299
|
+
|
|
300
|
+
print('LLM Call for id={} doc={}, prompt={}, const_embed={}, model={}, options={}, repeat={}'.format(
|
|
301
|
+
data_id, label['document'], label['prompt'], label['prompt_const_embed'],
|
|
302
|
+
label['model'], json.dumps(label['model_options']), label['repeat']))
|
|
303
|
+
if args.dry_run:
|
|
304
|
+
return
|
|
305
|
+
|
|
306
|
+
start_variation = perf_counter()
|
|
307
|
+
response = call_llm(prompt, model_config, model_options)
|
|
308
|
+
|
|
309
|
+
logger_debug_file(response['data']['text'],
|
|
310
|
+
f'response-{variation_slug(data_id, label)}.txt')
|
|
311
|
+
|
|
312
|
+
record = {
|
|
313
|
+
'id': data_id,
|
|
314
|
+
'variation': label,
|
|
315
|
+
'llm_call': response['meta'],
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
# the data schema is optional: without it there is nothing to extract and
|
|
319
|
+
# validate, so the raw LLM response is stored instead
|
|
320
|
+
if schema:
|
|
321
|
+
extracted_data = extract_validate_json(response['data']['text'],
|
|
322
|
+
schema)
|
|
323
|
+
logger.debug('Extracted data: ' + json.dumps(extracted_data))
|
|
324
|
+
record['extraction'] = extracted_data
|
|
325
|
+
else:
|
|
326
|
+
record['response'] = response['data']['text']
|
|
327
|
+
|
|
328
|
+
record['duration_ms'] = f'{(perf_counter() - start_variation) * 1000:.0f}'
|
|
329
|
+
|
|
330
|
+
# output in output.jsonl
|
|
331
|
+
with open(os.path.join(config_module.run_dir, 'output.jsonl'), 'a') as f:
|
|
332
|
+
f.write(json.dumps(record) + '\n')
|
|
333
|
+
|
|
334
|
+
return
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def run_variations(dataset, variations: list, models: dict, schema: dict | None):
|
|
338
|
+
"""Run every variation of the matrix for every record of the dataset."""
|
|
339
|
+
for data in dataset:
|
|
340
|
+
for variation in variations:
|
|
341
|
+
run_variation(data, variation, models, schema)
|
|
342
|
+
|
|
343
|
+
return
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def read_dataset(filename: str):
|
|
347
|
+
"""Yield the records of a dataset file (.jsonl or .csv), detected by file extension."""
|
|
348
|
+
ext = os.path.splitext(filename)[1].lower()
|
|
349
|
+
if ext == '.csv':
|
|
350
|
+
with open(filename, 'r', newline='') as infile:
|
|
351
|
+
for record in csv.DictReader(infile):
|
|
352
|
+
if not record.get('id'):
|
|
353
|
+
raise ValueError(f"Dataset record missing mandatory 'id' field: {record}")
|
|
354
|
+
yield record
|
|
355
|
+
else:
|
|
356
|
+
with open(filename, 'r') as infile:
|
|
357
|
+
for line in infile:
|
|
358
|
+
if not line.strip():
|
|
359
|
+
continue
|
|
360
|
+
record = json.loads(line.strip())
|
|
361
|
+
if not record.get('id'):
|
|
362
|
+
raise ValueError(f"Dataset record missing mandatory 'id' field: {record}")
|
|
363
|
+
yield record
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
# if __name__ == "__main__":
|
|
367
|
+
def cli():
|
|
368
|
+
if not args.configfile and not args.prompt and not args.prompt_filename:
|
|
369
|
+
parser.error('a prompt (direct or through prompt-filename) or a --configfile is required')
|
|
370
|
+
|
|
371
|
+
if args.configfile:
|
|
372
|
+
# Load the config file config.yaml:
|
|
373
|
+
with open(args.configfile, 'r') as file:
|
|
374
|
+
config = yaml.safe_load(file)
|
|
375
|
+
base_dir = os.path.dirname(args.configfile)
|
|
376
|
+
else:
|
|
377
|
+
config = deepcopy(config_module.config_default)
|
|
378
|
+
base_dir = os.path.expanduser(config_module.user_dir)
|
|
379
|
+
|
|
380
|
+
logs_dir = os.path.join(base_dir, 'logs')
|
|
381
|
+
runs_dir = os.path.join(base_dir, 'runs')
|
|
382
|
+
run_timestamp = datetime.now().strftime('%Y%m%d-%H%M%S')
|
|
383
|
+
config_module.log_dir = os.path.join(logs_dir, run_timestamp)
|
|
384
|
+
config_module.run_dir = os.path.join(runs_dir, run_timestamp)
|
|
385
|
+
|
|
386
|
+
os.makedirs(config_module.log_dir, exist_ok=True)
|
|
387
|
+
os.makedirs(config_module.run_dir, exist_ok=True)
|
|
388
|
+
|
|
389
|
+
# Configure logger for all (this package + dependencies).
|
|
390
|
+
logging.basicConfig(filename=os.path.join(config_module.log_dir, 'llmrunctl.log'), encoding='utf-8',
|
|
391
|
+
level=logging.INFO,
|
|
392
|
+
format='%(asctime)s - %(levelname)s - %(message)s',
|
|
393
|
+
datefmt='%Y-%m-%d %H:%M:%S')
|
|
394
|
+
# Override this package's logger for level
|
|
395
|
+
if args.debug:
|
|
396
|
+
logging.getLogger('llmrunctl').setLevel(logging.DEBUG)
|
|
397
|
+
|
|
398
|
+
logger.info('Run started')
|
|
399
|
+
|
|
400
|
+
# load_dotenv()
|
|
401
|
+
# api_key = os.getenv('API_KEY')
|
|
402
|
+
|
|
403
|
+
if args.scenario not in config['scenarios']:
|
|
404
|
+
print(f"Scenario '{args.scenario}' not found in "
|
|
405
|
+
f"{args.configfile if args.configfile else 'the default config'}")
|
|
406
|
+
exit(1)
|
|
407
|
+
|
|
408
|
+
# Creating a detached/clone copy of the original data, as it will be
|
|
409
|
+
# overridden by various passed-on argument (right approach?)
|
|
410
|
+
scenario = deepcopy(config['scenarios'][args.scenario])
|
|
411
|
+
scenario_variations = scenario['variations']
|
|
412
|
+
|
|
413
|
+
if args.dataset_filename:
|
|
414
|
+
scenario['dataset'] = {'filename': args.dataset_filename}
|
|
415
|
+
|
|
416
|
+
if args.model:
|
|
417
|
+
scenario_variations['models'] = args.model.split(',')
|
|
418
|
+
|
|
419
|
+
if args.repeats is not None:
|
|
420
|
+
scenario_variations['repeats'] = args.repeats
|
|
421
|
+
|
|
422
|
+
schema_from_args = args.schema is not None or args.schema_multi is not None
|
|
423
|
+
if args.schema is not None:
|
|
424
|
+
scenario['data_schema'] = schema_dsl(args.schema)
|
|
425
|
+
if args.schema_multi is not None:
|
|
426
|
+
scenario['data_schema'] = schema_dsl(args.schema_multi, True)
|
|
427
|
+
|
|
428
|
+
# a prompt passed on the command line (text or file) replaces the whole set
|
|
429
|
+
# of variations['prompts']
|
|
430
|
+
if args.prompt_filename:
|
|
431
|
+
scenario_variations['prompts'] = [{
|
|
432
|
+
'name': 'default',
|
|
433
|
+
'template': {
|
|
434
|
+
'filename': args.prompt_filename
|
|
435
|
+
}
|
|
436
|
+
}]
|
|
437
|
+
elif args.prompt:
|
|
438
|
+
prompt_content = args.prompt
|
|
439
|
+
if schema_from_args:
|
|
440
|
+
prompt_content = build_schema_prompt(
|
|
441
|
+
args.prompt, scenario['data_schema'],
|
|
442
|
+
config_module.prompt_schema_default)
|
|
443
|
+
scenario_variations['prompts'] = [{
|
|
444
|
+
'name': 'default',
|
|
445
|
+
'template': {
|
|
446
|
+
'content': prompt_content
|
|
447
|
+
}
|
|
448
|
+
}]
|
|
449
|
+
|
|
450
|
+
if not scenario_variations.get('prompts'):
|
|
451
|
+
print('No prompt defined: pass a prompt, --prompt-filename, or define one in the config file')
|
|
452
|
+
exit(1)
|
|
453
|
+
|
|
454
|
+
# every model of the scenario must be defined in the `models` section of
|
|
455
|
+
# the config
|
|
456
|
+
model_names = scenario_variations.get('models')
|
|
457
|
+
models_config = config.get('models') or {}
|
|
458
|
+
models_undefined = [name for name in model_names if name not in models_config]
|
|
459
|
+
if models_undefined:
|
|
460
|
+
print("Model(s) {} not found in {}".format(
|
|
461
|
+
', '.join(f"'{name}'" for name in models_undefined),
|
|
462
|
+
args.configfile if args.configfile else 'the default config'))
|
|
463
|
+
exit(1)
|
|
464
|
+
|
|
465
|
+
models = {name: deepcopy(models_config[name]) for name in model_names}
|
|
466
|
+
for model_name, model_config in models.items():
|
|
467
|
+
# the model name defaults to the key of the `models` section
|
|
468
|
+
model_config.setdefault('name', model_name)
|
|
469
|
+
|
|
470
|
+
variations = build_variations(scenario_variations)
|
|
471
|
+
print(f'Total Variations: {len(variations)} ({variations_breakdown(scenario_variations)})')
|
|
472
|
+
|
|
473
|
+
# the dataset is optional: without it a single synthetic record is used
|
|
474
|
+
dataset_config = scenario.get('dataset')
|
|
475
|
+
if dataset_config:
|
|
476
|
+
dataset_filename = dataset_config['filename']
|
|
477
|
+
dataset = list(read_dataset(dataset_filename))
|
|
478
|
+
dataset_length = len(dataset)
|
|
479
|
+
print(f'Total dataset items: {dataset_length} (in {dataset_filename})')
|
|
480
|
+
else:
|
|
481
|
+
dataset_length = 1
|
|
482
|
+
dataset = [{'id': None}]
|
|
483
|
+
print('No dataset: running the variations once')
|
|
484
|
+
|
|
485
|
+
# Iterate over the dataset and run the variations for each item:
|
|
486
|
+
start = perf_counter()
|
|
487
|
+
run_variations(dataset, variations, models, scenario.get('data_schema'))
|
|
488
|
+
|
|
489
|
+
duration_ms = (perf_counter() - start) * 1000
|
|
490
|
+
|
|
491
|
+
meta_file_content = {
|
|
492
|
+
'run_timestamp': run_timestamp,
|
|
493
|
+
'models': models,
|
|
494
|
+
'scenarios': {'default': scenario},
|
|
495
|
+
'stats': {
|
|
496
|
+
'dataset_length': dataset_length,
|
|
497
|
+
'variations_count': len(variations),
|
|
498
|
+
'llm_calls': dataset_length * len(variations),
|
|
499
|
+
'duration_ms': f'{duration_ms:.0f}',
|
|
500
|
+
}}
|
|
501
|
+
with open(os.path.join(config_module.run_dir, 'meta.json'), 'w') as f:
|
|
502
|
+
f.write(json.dumps(meta_file_content, indent=2))
|
|
503
|
+
|
|
504
|
+
print(f'Run completed in {duration_ms:.0f}ms')
|
|
505
|
+
print(f'Run output: {config_module.run_dir}')
|
|
506
|
+
logger.info(f'Run completed in {duration_ms:.0f}ms')
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Configuration for the LLM run process.
|
|
3
|
+
Note: using this module as a centralized configuration point, data is modifiable.
|
|
4
|
+
"""
|
|
5
|
+
log_dir = '.'
|
|
6
|
+
run_dir = '.' # required?
|
|
7
|
+
|
|
8
|
+
# Base directory for logs/ and runs/ when the tool is used WITHOUT a config file.
|
|
9
|
+
user_dir = '~/.llmrunctl'
|
|
10
|
+
|
|
11
|
+
# Fallback model definition, used to synthesize a model configuration for a
|
|
12
|
+
# model name that is not declared in the `models` section of the config
|
|
13
|
+
# (typically `llmrunctl "<prompt>" -m <model>` without a config file).
|
|
14
|
+
model_default = {
|
|
15
|
+
'backend': 'ollama_ollama',
|
|
16
|
+
'name': 'gemma3',
|
|
17
|
+
'options': {
|
|
18
|
+
'temperature': 'temperature',
|
|
19
|
+
'max_predict_tokens': 'num_predict',
|
|
20
|
+
'top_p': 'top_p',
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
# Default config used when no config.yaml file is provided: the minimal
|
|
25
|
+
# scenario, stripped of every parameter that is optional. Only the prompt is
|
|
26
|
+
# missing here: it is injected from the command line by `cli()`.
|
|
27
|
+
config_default = {
|
|
28
|
+
'models': {
|
|
29
|
+
'gpt-oss': {
|
|
30
|
+
'backend': 'ollama_ollama',
|
|
31
|
+
'name': 'gpt-oss',
|
|
32
|
+
'options': {
|
|
33
|
+
'temperature': 'temperature',
|
|
34
|
+
'max_predict_tokens': 'num_predict',
|
|
35
|
+
'top_p': 'top_p',
|
|
36
|
+
}
|
|
37
|
+
},
|
|
38
|
+
'gemma3': {
|
|
39
|
+
'backend': 'ollama_ollama',
|
|
40
|
+
'name': 'gemma3',
|
|
41
|
+
'options': {
|
|
42
|
+
'temperature': 'temperature',
|
|
43
|
+
'max_predict_tokens': 'num_predict',
|
|
44
|
+
'top_p': 'top_p',
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
},
|
|
48
|
+
'scenarios': {
|
|
49
|
+
'default': {
|
|
50
|
+
'name': 'default scenario',
|
|
51
|
+
# dataset omitted
|
|
52
|
+
# data_schema omitted
|
|
53
|
+
'variations': {
|
|
54
|
+
# document_sets omitted
|
|
55
|
+
# prompt_const_embeds omitted
|
|
56
|
+
# prompts: populated from the command line, either as
|
|
57
|
+
# {'template': {'content': '<prompt text>'}} or
|
|
58
|
+
# {'template': {'filename': 'path/to/prompt.md'}}
|
|
59
|
+
'prompts': [],
|
|
60
|
+
'models': ['gemma3'],
|
|
61
|
+
'model_options': {
|
|
62
|
+
# temperature omitted
|
|
63
|
+
# top_p omitted
|
|
64
|
+
},
|
|
65
|
+
'repeats': 1
|
|
66
|
+
},
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
prompt_schema_default = '''
|
|
72
|
+
# LLM Prompt
|
|
73
|
+
|
|
74
|
+
## Instruction
|
|
75
|
+
|
|
76
|
+
{user_prompt}
|
|
77
|
+
|
|
78
|
+
## Formatting the response
|
|
79
|
+
|
|
80
|
+
Format the answer in the response in JSON inside a JSON Markdown fenced code block: <human_json_schema_rules>
|
|
81
|
+
|
|
82
|
+
### Examples:
|
|
83
|
+
|
|
84
|
+
_example 1_:
|
|
85
|
+
|
|
86
|
+
```json
|
|
87
|
+
<json_example_1>
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
_example 2_:
|
|
91
|
+
|
|
92
|
+
```json
|
|
93
|
+
<json_example_2>
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
_example 3_:
|
|
97
|
+
|
|
98
|
+
```json
|
|
99
|
+
<json_example_3>
|
|
100
|
+
```
|
|
101
|
+
'''
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import ollama
|
|
3
|
+
|
|
4
|
+
logger = logging.getLogger(__name__)
|
|
5
|
+
|
|
6
|
+
def ollama_ollama_call(prompt: str, model_name: str, model_options: dict) -> dict:
|
|
7
|
+
response = ollama.generate(
|
|
8
|
+
model=model_name,
|
|
9
|
+
prompt=prompt,
|
|
10
|
+
options=model_options,
|
|
11
|
+
stream=False
|
|
12
|
+
)
|
|
13
|
+
# keep all valuable response attributes except the big ones
|
|
14
|
+
meta = {k: v for k, v in vars(response).items() if k not in ['context', 'response', 'thinking']}
|
|
15
|
+
response_dict = {
|
|
16
|
+
'data': {
|
|
17
|
+
'text': response.response,
|
|
18
|
+
},
|
|
19
|
+
'meta': meta,
|
|
20
|
+
}
|
|
21
|
+
return response_dict
|
|
22
|
+
|
|
23
|
+
# Test ollama server up and running:
|
|
24
|
+
# curl http://localhost:11434/api/generate -d '{
|
|
25
|
+
# "model": "gemma3",
|
|
26
|
+
# "prompt": "Why is the sky blue?",
|
|
27
|
+
# "stream": false
|
|
28
|
+
# }'
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import llm
|
|
2
|
+
import logging
|
|
3
|
+
|
|
4
|
+
logger = logging.getLogger(__name__)
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def simonw_llm_call(prompt: str, model_name: str, model_options: dict) -> dict:
|
|
8
|
+
# STUB
|
|
9
|
+
response_dict = {
|
|
10
|
+
'data': {
|
|
11
|
+
'text': 'BLABLABLA',
|
|
12
|
+
},
|
|
13
|
+
'meta': {
|
|
14
|
+
'var1': 1,
|
|
15
|
+
'var2': 2,
|
|
16
|
+
},
|
|
17
|
+
}
|
|
18
|
+
return response_dict
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: llmflock
|
|
3
|
+
Version: 0.0.2
|
|
4
|
+
Summary: LLM Runner Control is a CLI tool to interact with local and remote LLM, define multiple scenario variations (model × prompt × options), run it over a dataset and capture structured results for comparison or to build knowledge through meta analysis.
|
|
5
|
+
License-File: LICENSE.txt
|
|
6
|
+
Requires-Dist: jsonschema
|
|
7
|
+
Requires-Dist: llm
|
|
8
|
+
Requires-Dist: llm-gpt4all
|
|
9
|
+
Requires-Dist: llm-ollama
|
|
10
|
+
Requires-Dist: ollama
|
|
11
|
+
Requires-Dist: python-dotenv
|
|
12
|
+
Requires-Dist: PyYAML
|
|
13
|
+
Dynamic: license-file
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
LICENSE.txt
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
llmflock/__init__.py
|
|
5
|
+
llmflock/__main__.py
|
|
6
|
+
llmflock/cli.py
|
|
7
|
+
llmflock/config.py
|
|
8
|
+
llmflock/ollama_ollama.py
|
|
9
|
+
llmflock/simonw_llm.py
|
|
10
|
+
llmflock.egg-info/PKG-INFO
|
|
11
|
+
llmflock.egg-info/SOURCES.txt
|
|
12
|
+
llmflock.egg-info/dependency_links.txt
|
|
13
|
+
llmflock.egg-info/entry_points.txt
|
|
14
|
+
llmflock.egg-info/requires.txt
|
|
15
|
+
llmflock.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
llmflock
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "llmflock"
|
|
3
|
+
version = "0.0.2"
|
|
4
|
+
description = "LLM Runner Control is a CLI tool to interact with local and remote LLM, define multiple scenario variations (model × prompt × options), run it over a dataset and capture structured results for comparison or to build knowledge through meta analysis."
|
|
5
|
+
dependencies = [
|
|
6
|
+
"jsonschema",
|
|
7
|
+
"llm",
|
|
8
|
+
"llm-gpt4all",
|
|
9
|
+
"llm-ollama",
|
|
10
|
+
"ollama",
|
|
11
|
+
"python-dotenv",
|
|
12
|
+
"PyYAML"
|
|
13
|
+
]
|
|
14
|
+
|
|
15
|
+
[project.scripts]
|
|
16
|
+
llmflock = "llmflock.cli:cli"
|
|
17
|
+
|
|
18
|
+
# Required to build the package since we are not using src layout
|
|
19
|
+
# IE setuptools would misinterpret extra folder(s) (data) as a package if we
|
|
20
|
+
# don't add this ("Multiple top-level packages discovered in a flat-layout")
|
|
21
|
+
[tool.setuptools]
|
|
22
|
+
packages = ["llmflock"]
|
|
23
|
+
|
|
24
|
+
[build-system]
|
|
25
|
+
requires = ["setuptools"]
|
|
26
|
+
build-backend = "setuptools.build_meta"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
# General note: Written using a mix of python packaging user guides,
|
|
30
|
+
# simonw/llm approach and various sources from Google
|
|
31
|
+
# https://packaging.python.org/en/latest/, specifically:
|
|
32
|
+
# - https://packaging.python.org/en/latest/guides/creating-command-line-tools/
|
|
33
|
+
# - https://packaging.python.org/en/latest/guides/writing-pyproject-toml/
|
|
34
|
+
# - https://packaging.python.org/en/latest/discussions/src-layout-vs-flat-layout/
|
llmflock-0.0.2/setup.cfg
ADDED