generative-redfoot 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.
- generative_redfoot/__init__.py +1 -0
- generative_redfoot/cli.py +217 -0
- generative_redfoot/extensions/__init__.py +0 -0
- generative_redfoot/extensions/toolio.py +88 -0
- generative_redfoot/extensions/wordloom.py +64 -0
- generative_redfoot/object_pdl_model.py +489 -0
- generative_redfoot/utils.py +5 -0
- generative_redfoot-0.1.0.dist-info/METADATA +245 -0
- generative_redfoot-0.1.0.dist-info/RECORD +13 -0
- generative_redfoot-0.1.0.dist-info/WHEEL +5 -0
- generative_redfoot-0.1.0.dist-info/entry_points.txt +2 -0
- generative_redfoot-0.1.0.dist-info/licenses/LICENSE +21 -0
- generative_redfoot-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
|
|
2
|
+
import click
|
|
3
|
+
import yaml
|
|
4
|
+
import json
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
from .utils import truncate_long_text
|
|
8
|
+
from .object_pdl_model import PDLModel, PDLProgram, ParseDispatcher, PDFRead, PDLRepeat, PDLText, PDLRead
|
|
9
|
+
from .extensions.wordloom import WorldLoomRead
|
|
10
|
+
from .extensions.toolio import ToolioCompletion
|
|
11
|
+
from pyarrow.lib import Mapping
|
|
12
|
+
from transformers import PreTrainedTokenizer
|
|
13
|
+
from typing import Tuple, Dict, List
|
|
14
|
+
|
|
15
|
+
@click.command()
|
|
16
|
+
@click.option('-t', '--temperature', default=1, type=float)
|
|
17
|
+
@click.option('-rp', '--repetition-penalty', default=0, type=float,
|
|
18
|
+
help='The penalty factor for repeating tokens (none if not used)')
|
|
19
|
+
@click.option('--top-k', default=-1, type=int, help='Sampling top_k')
|
|
20
|
+
@click.option('--top-p', default=0.95, type=float, help='Sampling top_p')
|
|
21
|
+
@click.option('--max-tokens', default=800, type=int, help='Max tokens')
|
|
22
|
+
@click.option('--min-p', default=0, type=float, help='Sampling min-p')
|
|
23
|
+
@click.option('--verbose/--no-verbose', default=False)
|
|
24
|
+
@click.option("--variables", "-v", "variables", type=(str, str), multiple=True)
|
|
25
|
+
@click.argument('pdl_file')
|
|
26
|
+
def main(temperature, repetition_penalty, top_k, top_p, max_tokens, min_p, verbose, variables, pdl_file):
|
|
27
|
+
import mlx.nn as nn
|
|
28
|
+
from mlx_lm.utils import load
|
|
29
|
+
from mlx_lm.generate import generate
|
|
30
|
+
from mlx_lm.sample_utils import make_sampler, make_logits_processors
|
|
31
|
+
from mlx_lm.models.cache import load_prompt_cache, make_prompt_cache
|
|
32
|
+
|
|
33
|
+
start_marker = '<s>'
|
|
34
|
+
end_marker = '</s>'
|
|
35
|
+
separator = '\n'
|
|
36
|
+
|
|
37
|
+
def create_propositions_input(text: str) -> str:
|
|
38
|
+
import nltk
|
|
39
|
+
nltk.download('punkt')
|
|
40
|
+
input_sents = nltk.tokenize.sent_tokenize(text)
|
|
41
|
+
propositions_input = ''
|
|
42
|
+
for sent in input_sents:
|
|
43
|
+
propositions_input += f'{start_marker} ' + sent + f' {end_marker}{separator}'
|
|
44
|
+
propositions_input = propositions_input.strip(f'{separator}')
|
|
45
|
+
return propositions_input
|
|
46
|
+
|
|
47
|
+
def process_propositions_output(text):
|
|
48
|
+
pattern = re.compile(f'{re.escape(start_marker)}(.*?){re.escape(end_marker)}', re.DOTALL)
|
|
49
|
+
output_grouped_strs = re.findall(pattern, text)
|
|
50
|
+
predicted_grouped_propositions = []
|
|
51
|
+
for grouped_str in output_grouped_strs:
|
|
52
|
+
grouped_str = grouped_str.strip(separator)
|
|
53
|
+
props = [x[2:] for x in grouped_str.split(separator)]
|
|
54
|
+
predicted_grouped_propositions.append(props)
|
|
55
|
+
return predicted_grouped_propositions
|
|
56
|
+
|
|
57
|
+
class MLXModelEvaluationBase(PDLModel):
|
|
58
|
+
def _get_model_cache_and_tokenizer(self) -> Tuple[nn.Module, PreTrainedTokenizer]:
|
|
59
|
+
eos_token = self.parameters.get("eos_token")
|
|
60
|
+
if eos_token:
|
|
61
|
+
tokenizer_config = {"eos_token": eos_token}
|
|
62
|
+
else:
|
|
63
|
+
tokenizer_config = {}
|
|
64
|
+
model, tokenizer = load(self.model, tokenizer_config=tokenizer_config)
|
|
65
|
+
if self.program.cache:
|
|
66
|
+
if isinstance(self.program.cache, str):
|
|
67
|
+
if self.program.cache == PDLProgram.INTERNAL_CACHE_NAME:
|
|
68
|
+
self.program.cache = (make_prompt_cache(model))
|
|
69
|
+
if verbose:
|
|
70
|
+
print("Using internal cache for prompts")
|
|
71
|
+
else:
|
|
72
|
+
self.program.cache = load_prompt_cache(self.program.cache)
|
|
73
|
+
if verbose:
|
|
74
|
+
print(f"Using external cache for prompts: {self.program.cache}")
|
|
75
|
+
return model, tokenizer
|
|
76
|
+
|
|
77
|
+
def generate(self, messages, tokenizer, model, verbose):
|
|
78
|
+
prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
|
79
|
+
if verbose:
|
|
80
|
+
cache_info = " and cache" if self.program.cache else ""
|
|
81
|
+
print(f"Using parameters: {self.parameters}{cache_info} for {self.model}")
|
|
82
|
+
logits_processor = make_logits_processors(repetition_penalty=self.parameters.get("repetition_penalty",
|
|
83
|
+
repetition_penalty))
|
|
84
|
+
draft_model = self.draft_model
|
|
85
|
+
if draft_model:
|
|
86
|
+
from mlx_lm.utils import load
|
|
87
|
+
draft_model, draft_tokenizer = load(self.draft_model)
|
|
88
|
+
if draft_tokenizer.vocab_size != tokenizer.vocab_size:
|
|
89
|
+
raise ValueError("Draft model tokenizer does not match model tokenizer.")
|
|
90
|
+
elif verbose:
|
|
91
|
+
print(f"Using draft model: {self.draft_model}")
|
|
92
|
+
return generate(model, tokenizer, prompt,
|
|
93
|
+
max_tokens=self.parameters.get("max_tokens", max_tokens),
|
|
94
|
+
sampler=make_sampler(temp=self.parameters.get("temperature", temperature),
|
|
95
|
+
min_p=self.parameters.get("min_p", min_p),
|
|
96
|
+
top_k=self.parameters.get("top_k", top_k)),
|
|
97
|
+
logits_processors=logits_processor,
|
|
98
|
+
verbose=verbose,
|
|
99
|
+
prompt_cache=self.program.cache,
|
|
100
|
+
draft_model=draft_model), prompt
|
|
101
|
+
|
|
102
|
+
class MLXModelEvaluation(MLXModelEvaluationBase):
|
|
103
|
+
def _insert_cot_messages(self, messages: List[Dict], cot_prefix: List[Dict]):
|
|
104
|
+
"""
|
|
105
|
+
Modifies LLM messaging with a chain-of-thought (COT) prefix after any system message.
|
|
106
|
+
|
|
107
|
+
:param messages: List of message dictionaries where each dictionary contains keys like
|
|
108
|
+
'role' or 'content' and other relevant items for message processing.
|
|
109
|
+
:param cot_prefix: Chain-of-thought (COT) prefix, provided as a list of dictionaries
|
|
110
|
+
that serve as the preparatory context/instructions to be inserted into the message
|
|
111
|
+
list, when the first item in `messages` is associated with the 'system' role.
|
|
112
|
+
:return: Updated `messages` list with the COT prefix properly inserted when applicable.
|
|
113
|
+
"""
|
|
114
|
+
idx = 1 if messages[0]['role'] == 'system' else 0
|
|
115
|
+
messages[idx:idx] = cot_prefix
|
|
116
|
+
return messages
|
|
117
|
+
|
|
118
|
+
def execute(self, context: Dict, verbose: bool = False):
|
|
119
|
+
model, tokenizer = self._get_model_cache_and_tokenizer()
|
|
120
|
+
messages = []
|
|
121
|
+
if self.input:
|
|
122
|
+
self.input.execute(context, verbose=verbose)
|
|
123
|
+
messages.extend(context["_"])
|
|
124
|
+
if self.cot_prefix:
|
|
125
|
+
print(f"### Adding Chain-of Thought Few Shot examples specified in {self.cot_prefix} ###")
|
|
126
|
+
with open(self.cot_prefix, 'r') as cot_content:
|
|
127
|
+
self._insert_cot_messages(messages, json.load(cot_content))
|
|
128
|
+
if verbose:
|
|
129
|
+
from pprint import pprint
|
|
130
|
+
print("Generating response using ..")
|
|
131
|
+
pprint([{k: v if k == "role" else truncate_long_text(v)} for i in messages for k,v in i.items()])
|
|
132
|
+
else:
|
|
133
|
+
print("Generating response ... ")
|
|
134
|
+
if self.alpha_one:
|
|
135
|
+
from alpha_one_mlx.reasoner import alpha_one
|
|
136
|
+
from alpha_one_mlx.models import get_configuration
|
|
137
|
+
|
|
138
|
+
configuration = get_configuration(model.model_type)
|
|
139
|
+
alpha = self.alpha_one.get("alpha", 1.4)
|
|
140
|
+
threshold = int(max_tokens - alpha * self.alpha_one["thinking_token_length"])
|
|
141
|
+
prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
|
142
|
+
wait_words = self.alpha_one.get("wait_words", configuration.slow_thinking_stop_words)
|
|
143
|
+
if verbose:
|
|
144
|
+
print(f"Using parameters: {self.parameters} and {self.alpha_one} for {self.model}")
|
|
145
|
+
draft_model = self.draft_model
|
|
146
|
+
if draft_model:
|
|
147
|
+
from mlx_lm.utils import load
|
|
148
|
+
draft_model, draft_tokenizer = load(self.draft_model)
|
|
149
|
+
if draft_tokenizer.vocab_size != tokenizer.vocab_size:
|
|
150
|
+
raise ValueError("Draft model tokenizer does not match model tokenizer.")
|
|
151
|
+
elif verbose:
|
|
152
|
+
print(f"Using draft model: {self.draft_model}")
|
|
153
|
+
response = alpha_one(model, tokenizer, prompt,
|
|
154
|
+
configuration=configuration,
|
|
155
|
+
max_tokens_per_call=self.parameters.get("max_tokens", max_tokens),
|
|
156
|
+
threshold=threshold,
|
|
157
|
+
temperature=self.parameters.get("temperature", temperature),
|
|
158
|
+
top_p=self.parameters.get("top_p", top_p),
|
|
159
|
+
min_p=self.parameters.get("min_p", min_p),
|
|
160
|
+
top_k=self.parameters.get("top_k", top_k),
|
|
161
|
+
apply_chat_template=False,
|
|
162
|
+
verbose=verbose,
|
|
163
|
+
wait_words=wait_words,
|
|
164
|
+
prompt_cache=self.program.cache,
|
|
165
|
+
draft_model=draft_model)
|
|
166
|
+
|
|
167
|
+
else:
|
|
168
|
+
response, prompt = self.generate(messages, tokenizer, model, verbose=verbose)
|
|
169
|
+
if verbose:
|
|
170
|
+
print(f"Executing model: {self.model} using context {context} - (via mlx)-> >\n{response}")
|
|
171
|
+
self._handle_execution_contribution(response, context)
|
|
172
|
+
if "context" not in self.contribute:
|
|
173
|
+
if verbose:
|
|
174
|
+
print("Clearing context ...")
|
|
175
|
+
context["_"] = []
|
|
176
|
+
|
|
177
|
+
@staticmethod
|
|
178
|
+
def dispatch_check(item: Mapping, program: PDLProgram):
|
|
179
|
+
if "model" in item:
|
|
180
|
+
return MLXModelEvaluation(item, program)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
class MLXAPSModel(MLXModelEvaluationBase):
|
|
184
|
+
MODEL_KEY = "APSModel"
|
|
185
|
+
def execute(self, context, return_content=False, verbose=False):
|
|
186
|
+
model, tokenizer = self._get_model_cache_and_tokenizer()
|
|
187
|
+
msg = context["_"][-1].copy()
|
|
188
|
+
if verbose:
|
|
189
|
+
print("Extracting individual facts, statements, and ideas from using ",
|
|
190
|
+
truncate_long_text(msg["content"]))
|
|
191
|
+
else:
|
|
192
|
+
print("Generating response ... ")
|
|
193
|
+
msg["content"] = create_propositions_input(msg["content"])
|
|
194
|
+
msg["role"] = "user"
|
|
195
|
+
response, prompt = self.generate([msg], tokenizer, model, verbose=verbose)
|
|
196
|
+
response = process_propositions_output(response)
|
|
197
|
+
self._handle_execution_contribution(response, context)
|
|
198
|
+
if "context" not in self.contribute:
|
|
199
|
+
if verbose:
|
|
200
|
+
print("Clearing context ...")
|
|
201
|
+
context["_"] = []
|
|
202
|
+
|
|
203
|
+
@staticmethod
|
|
204
|
+
def dispatch_check(item: Mapping, program: PDLProgram):
|
|
205
|
+
if "APSModel" in item:
|
|
206
|
+
return MLXAPSModel(item, program)
|
|
207
|
+
|
|
208
|
+
dispatcher = ParseDispatcher()
|
|
209
|
+
dispatcher.DISPATCH_RESOLUTION_ORDER = [PDLRead, WorldLoomRead, ToolioCompletion, PDLRepeat, PDLText,
|
|
210
|
+
MLXModelEvaluation, MLXAPSModel, PDFRead]
|
|
211
|
+
with open(pdl_file, "r") as file:
|
|
212
|
+
program = PDLProgram(yaml.safe_load(file), dispatcher=dispatcher, initial_context=dict(variables))
|
|
213
|
+
program.execute(verbose=verbose)
|
|
214
|
+
if verbose:
|
|
215
|
+
print(program.evaluation_environment)
|
|
216
|
+
if __name__ == '__main__':
|
|
217
|
+
main()
|
|
File without changes
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import warnings
|
|
2
|
+
import json
|
|
3
|
+
import asyncio
|
|
4
|
+
|
|
5
|
+
from ..object_pdl_model import PDLProgram, PDLModel
|
|
6
|
+
from ..utils import truncate_messages
|
|
7
|
+
|
|
8
|
+
from typing import Mapping, Dict, List
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
class ToolioCompletion(PDLModel):
|
|
12
|
+
"""
|
|
13
|
+
PDL block for structured LLM response generation via Toolio + MLX
|
|
14
|
+
|
|
15
|
+
"""
|
|
16
|
+
MODEL_KEY = "structured_output"
|
|
17
|
+
def __init__(self, content: Mapping, program: PDLProgram):
|
|
18
|
+
super().__init__(content, program)
|
|
19
|
+
self.insert_schema = content["insert_schema"]
|
|
20
|
+
self.schema_file = content["schema_file"]
|
|
21
|
+
self.max_tokens = self.parameters.get("max_tokens", 256)
|
|
22
|
+
|
|
23
|
+
def _insert_cot_messages(self, messages: List[Dict], cot_prefix: List[Dict]):
|
|
24
|
+
"""
|
|
25
|
+
Modifies LLM messaging with a chain-of-thought (COT) prefix after any system message.
|
|
26
|
+
|
|
27
|
+
:param messages: List of message dictionaries where each dictionary contains keys like
|
|
28
|
+
'role' or 'content' and other relevant items for message processing.
|
|
29
|
+
:param cot_prefix: Chain-of-thought (COT) prefix, provided as a list of dictionaries
|
|
30
|
+
that serve as the preparatory context/instructions to be inserted into the message
|
|
31
|
+
list, when the first item in `messages` is associated with the 'system' role.
|
|
32
|
+
:return: Updated `messages` list with the COT prefix properly inserted when applicable.
|
|
33
|
+
"""
|
|
34
|
+
idx = 1 if messages[0]['role'] == 'system' else 0
|
|
35
|
+
messages[idx:idx] = cot_prefix
|
|
36
|
+
return messages
|
|
37
|
+
|
|
38
|
+
def __repr__(self):
|
|
39
|
+
return f"ToolioCompletion(according to '{self.schema_file}' and up to {self.max_tokens:,} tokens)"
|
|
40
|
+
|
|
41
|
+
def execute(self, context: Dict, verbose: bool = False):
|
|
42
|
+
source_phrase = ""
|
|
43
|
+
if self.input:
|
|
44
|
+
source_phrase = f" from {self.input}"
|
|
45
|
+
if verbose:
|
|
46
|
+
messages = truncate_messages(context)
|
|
47
|
+
print(f"Running Toolio completion according to '{self.schema_file}', using {messages}"
|
|
48
|
+
f"{source_phrase} (max of {self.max_tokens:,} tokens)")
|
|
49
|
+
if isinstance(self.input, str):
|
|
50
|
+
self.input
|
|
51
|
+
else:
|
|
52
|
+
self.input.execute(context, verbose=verbose)
|
|
53
|
+
asyncio.run(self.toolio_completion(context, verbose))
|
|
54
|
+
|
|
55
|
+
async def toolio_completion(self, context: Dict, verbose: bool = False):
|
|
56
|
+
from toolio.llm_helper import local_model_runner
|
|
57
|
+
toolio_mm = local_model_runner(self.model)
|
|
58
|
+
if verbose:
|
|
59
|
+
print(context)
|
|
60
|
+
if self.input:
|
|
61
|
+
messages = [{'role': 'user', 'content': self.input}]
|
|
62
|
+
else:
|
|
63
|
+
messages = context["_"]
|
|
64
|
+
|
|
65
|
+
if self.cot_prefix:
|
|
66
|
+
if verbose:
|
|
67
|
+
print(f"### Adding Chain-of Thought Few Shot examples specified in {self.cot_prefix} ###")
|
|
68
|
+
with open(self.cot_prefix, 'r') as cot_content:
|
|
69
|
+
self._insert_cot_messages(messages, json.load(cot_content))
|
|
70
|
+
if self.program.cache:
|
|
71
|
+
warnings.warn(f"Prompt cache ({self.program.cache}) not supported with Toolio")
|
|
72
|
+
|
|
73
|
+
if Path(self.schema_file).exists():
|
|
74
|
+
with open(self.schema_file, mode='r') as schema_file:
|
|
75
|
+
response = await toolio_mm.complete(messages,
|
|
76
|
+
json_schema=schema_file.read(),
|
|
77
|
+
max_tokens=self.max_tokens,
|
|
78
|
+
temperature=self.parameters.get("temperature", 0),
|
|
79
|
+
insert_schema=self.insert_schema,
|
|
80
|
+
full_response=True)
|
|
81
|
+
self._handle_execution_contribution(response.first_choice_text, context)
|
|
82
|
+
else:
|
|
83
|
+
raise ValueError(f"Schema file '{self.schema_file}' does not exist")
|
|
84
|
+
|
|
85
|
+
@staticmethod
|
|
86
|
+
def dispatch_check(item: Mapping, program: PDLProgram):
|
|
87
|
+
if "structured_output" in item:
|
|
88
|
+
return ToolioCompletion(item, program)
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
from ..object_pdl_model import PDLObject, PDLStructuredBlock
|
|
2
|
+
from typing import Mapping, Dict, Any
|
|
3
|
+
|
|
4
|
+
class WorldLoomRead(PDLObject, PDLStructuredBlock):
|
|
5
|
+
"""
|
|
6
|
+
PDL block for reading sections for a prompt from a Worldloom (TOML / YAML) file using ogbujipt.word_loom
|
|
7
|
+
|
|
8
|
+
Example:
|
|
9
|
+
>>> import yaml
|
|
10
|
+
>>> from ..object_pdl_model import PDL3, PDLProgram
|
|
11
|
+
>>> p = PDLProgram(yaml.safe_load(PDL3))
|
|
12
|
+
>>> p.cache
|
|
13
|
+
'prompt_cache.safetensors'
|
|
14
|
+
>>> p.text[0]
|
|
15
|
+
Wordloom('question answer' from file.loom [outputs to context as user])
|
|
16
|
+
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
def __init__(self, pdl_block: Mapping, program: PDLObject):
|
|
20
|
+
self.program = program
|
|
21
|
+
self.loom_file = pdl_block["read_from_wordloom"]
|
|
22
|
+
self.language_items = pdl_block["items"]
|
|
23
|
+
self._get_common_attributes(pdl_block)
|
|
24
|
+
|
|
25
|
+
def __repr__(self):
|
|
26
|
+
return f"Wordloom('{self.language_items}' from {self.loom_file} [{self.descriptive_text()}])"
|
|
27
|
+
|
|
28
|
+
def execute(self, context: Dict, verbose: bool = False):
|
|
29
|
+
from ogbujipt import word_loom
|
|
30
|
+
with open(self.loom_file, mode='rb') as fp:
|
|
31
|
+
loom = word_loom.load(fp)
|
|
32
|
+
items = self.language_items.split(' ')
|
|
33
|
+
if verbose:
|
|
34
|
+
print(f"Expanding {items} from {self.loom_file}")
|
|
35
|
+
content = '\n'.join([WorldLoomRead.get_loom_entry(loom[name], context) for name in items])
|
|
36
|
+
self._handle_execution_contribution(content, context)
|
|
37
|
+
|
|
38
|
+
@staticmethod
|
|
39
|
+
def get_loom_entry(loom_entry:Any, context: Mapping) -> str:
|
|
40
|
+
"""
|
|
41
|
+
Processes a language_item by formatting it with context-specific marker substitutions
|
|
42
|
+
if markers are present in the language_item. If no markers are available, the original
|
|
43
|
+
language_item is returned as is.
|
|
44
|
+
|
|
45
|
+
:param loom_entry: A wordloom `language_item` object that contains potential markers to be
|
|
46
|
+
substituted and formatted with values from the context.
|
|
47
|
+
:param context: A dictionary-like object (`Mapping`) that holds marker-to-value
|
|
48
|
+
mappings to be used for substitutions in the given loom_entry.
|
|
49
|
+
:return: Returns a formatted string if markers are found and substitutions can be
|
|
50
|
+
applied; otherwise, returns the unprocessed `language_item` as is.
|
|
51
|
+
|
|
52
|
+
"""
|
|
53
|
+
if loom_entry.markers:
|
|
54
|
+
marker_kwargs = {}
|
|
55
|
+
for marker in loom_entry.markers:
|
|
56
|
+
marker_kwargs[marker] = context[marker]
|
|
57
|
+
return loom_entry.format(**marker_kwargs)
|
|
58
|
+
else:
|
|
59
|
+
return loom_entry
|
|
60
|
+
|
|
61
|
+
@staticmethod
|
|
62
|
+
def dispatch_check(item: Mapping, program: PDLObject):
|
|
63
|
+
if "read_from_wordloom" in item:
|
|
64
|
+
return WorldLoomRead(item, program)
|
|
@@ -0,0 +1,489 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Object PDL Model
|
|
3
|
+
|
|
4
|
+
Takes a minimal Prompt Declaration Language (PDL) file and generates a finite state generative machine
|
|
5
|
+
as Python objects for a subset of the PDL language [1], [2]. These objects (the "programs" in particular)
|
|
6
|
+
can be executed, and their Model class can be extended to incorporate the functionality for
|
|
7
|
+
evaluating the prompts against the models specified in PDL using any accumulated conversational
|
|
8
|
+
context, prompts, and generation parameters (sampling parameters, for example), (optionally) updating
|
|
9
|
+
the context as the programs execution continues.
|
|
10
|
+
|
|
11
|
+
The model evaluation is implemented using mlx
|
|
12
|
+
|
|
13
|
+
A callback to Redfoot [1] by James Tauber and Dan Krech, way back in the dawn of the Semantic Web agent framework days.
|
|
14
|
+
This current AI dev ops wave could lean alot from that previous one, circa dawn of this millennium
|
|
15
|
+
|
|
16
|
+
[1] https://jtauber.com/redfoot/
|
|
17
|
+
[2] https://github.com/IBM/prompt-declaration-language
|
|
18
|
+
[3] https://arxiv.org/pdf/2410.19135
|
|
19
|
+
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
import re
|
|
23
|
+
from abc import ABC
|
|
24
|
+
from typing import Mapping, Dict, Any, Optional, Union, List
|
|
25
|
+
from pprint import pprint
|
|
26
|
+
|
|
27
|
+
def pretty_print_list(my_list, sep=", ", and_char=", & "):
|
|
28
|
+
return and_char.join([sep.join(my_list[:-1]), my_list[-1]]) if len(my_list) > 2 else '{} and {}'.format(
|
|
29
|
+
my_list[0], my_list[1]
|
|
30
|
+
) if len(my_list) == 2 else my_list[0]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
UNTIL_PATTERN = re.compile(r"^\$\{\s*(?P<variable>[^\s]+)\s+==\s*'(?P<value>[^']+)'\s*\}")
|
|
34
|
+
VAR_REFERENCE_PATTERN = re.compile(r"^\$(?P<variable>[^\s]+)\s*$")
|
|
35
|
+
|
|
36
|
+
PDL = """
|
|
37
|
+
description: chatbot
|
|
38
|
+
text:
|
|
39
|
+
- read:
|
|
40
|
+
message: "What is your query?\n"
|
|
41
|
+
contribute: [context]
|
|
42
|
+
- repeat:
|
|
43
|
+
text:
|
|
44
|
+
- model: google/gemma-2-9b-it
|
|
45
|
+
- def: question
|
|
46
|
+
read:
|
|
47
|
+
contribute: [context]
|
|
48
|
+
message: "Enter a query or say 'quit' to exit"
|
|
49
|
+
until: "${ question == 'quit' }"
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
PDL2 = """
|
|
53
|
+
description: program
|
|
54
|
+
text:
|
|
55
|
+
- model: google/gemma-2-9b-it
|
|
56
|
+
parameters:
|
|
57
|
+
temperature: 0.6
|
|
58
|
+
min_p: .03
|
|
59
|
+
max_tokens: 600
|
|
60
|
+
input:
|
|
61
|
+
contribute: [context]
|
|
62
|
+
text:
|
|
63
|
+
- read: some_file.txt
|
|
64
|
+
contribute: [context]
|
|
65
|
+
- read: other_file.txt
|
|
66
|
+
contribute: [context]
|
|
67
|
+
- |
|
|
68
|
+
|
|
69
|
+
Long text."""
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
PDL3 = """
|
|
73
|
+
description: program
|
|
74
|
+
cache: prompt_cache.safetensors
|
|
75
|
+
text:
|
|
76
|
+
- read_from_wordloom: file.loom
|
|
77
|
+
items: "question answer"
|
|
78
|
+
contribute: [context]
|
|
79
|
+
"""
|
|
80
|
+
|
|
81
|
+
PDL4 = """
|
|
82
|
+
description: program
|
|
83
|
+
text:
|
|
84
|
+
- role: "system"
|
|
85
|
+
text: "Do stuff well"
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
PDL5 = """
|
|
89
|
+
description: program
|
|
90
|
+
defs:
|
|
91
|
+
file: /tmp/file.txt
|
|
92
|
+
text:
|
|
93
|
+
- role: system
|
|
94
|
+
text: foo
|
|
95
|
+
contribute: [context]
|
|
96
|
+
- text: bar
|
|
97
|
+
"""
|
|
98
|
+
|
|
99
|
+
class PDLObject(ABC):
|
|
100
|
+
pass
|
|
101
|
+
|
|
102
|
+
class TextCollator(PDLObject):
|
|
103
|
+
def __init__(self, content: Any, program):
|
|
104
|
+
self.program = program
|
|
105
|
+
self.content = content if isinstance(content,
|
|
106
|
+
str) else list(map(lambda i: self.program.dispatcher.handle(i,
|
|
107
|
+
self.program),
|
|
108
|
+
content))
|
|
109
|
+
|
|
110
|
+
class PDLStructuredBlock:
|
|
111
|
+
"""
|
|
112
|
+
Optional keywords for block: "description", "def", "role", and "contribute" currently
|
|
113
|
+
|
|
114
|
+
- description: is a special comment
|
|
115
|
+
- def: assigns the result of the block to a variable
|
|
116
|
+
- defs: creates multiple variable definitions, each with its own name 𝑥 and a value given
|
|
117
|
+
by a nested PDL program:
|
|
118
|
+
- role: causes the data resulting from a block to be decorated with a role, such as ‘user’,
|
|
119
|
+
‘assistant’, or ‘system’. If a block does not have an explicit role: , it defaults to
|
|
120
|
+
‘assistant’ for model blocks and to ‘user’ for all other blocks. Inner nested blocks have
|
|
121
|
+
the same role as their outer enclosing block.
|
|
122
|
+
- contribute: [specifies] a (possibly empty) subset of the two destinations ‘result’ or
|
|
123
|
+
‘context’. By default, every block contributes to both its own result and the background
|
|
124
|
+
context for later LLM calls. [..] [can limit] the contribution of a block to just the
|
|
125
|
+
context to declutter the output.
|
|
126
|
+
"""
|
|
127
|
+
default_contribution = ["context", "result"]
|
|
128
|
+
default_role = "user"
|
|
129
|
+
def _get_common_attributes(self, item: Mapping):
|
|
130
|
+
self.contribute = item.get("contribute", self.default_contribution)
|
|
131
|
+
self.role = item.get("role", self.default_role)
|
|
132
|
+
self.var_def = item.get("def")
|
|
133
|
+
self.description = item.get("description")
|
|
134
|
+
self.defs = {k:v for k,v in item.get("defs", {}).items()}
|
|
135
|
+
|
|
136
|
+
def _handle_execution_contribution(self, content: Union[List, str], context: Dict):
|
|
137
|
+
if content:
|
|
138
|
+
msg = {"role": self.role, "content": content}
|
|
139
|
+
if "result" in self.contribute:
|
|
140
|
+
print(content)
|
|
141
|
+
if "context" in self.contribute:
|
|
142
|
+
context.setdefault('_', []).append(msg)
|
|
143
|
+
|
|
144
|
+
def descriptive_text(self):
|
|
145
|
+
var_suffix = f" -> ${self.var_def}" if self.var_def else ""
|
|
146
|
+
if self.defs:
|
|
147
|
+
var_suffix = var_suffix + f" (defining: {self.defs})"
|
|
148
|
+
output_destination = (", ".join(self.contribute) if self.contribute else "N/A")
|
|
149
|
+
return f"outputs to {output_destination} as {self.role}{var_suffix}"
|
|
150
|
+
|
|
151
|
+
class PDLText(TextCollator, PDLStructuredBlock):
|
|
152
|
+
"""
|
|
153
|
+
PDL blcck for creating data
|
|
154
|
+
|
|
155
|
+
Example:
|
|
156
|
+
>>> import yaml
|
|
157
|
+
>>> program = PDLProgram(yaml.safe_load(PDL))
|
|
158
|
+
>>> program.text.role
|
|
159
|
+
'user'
|
|
160
|
+
|
|
161
|
+
>>> p = PDLProgram(yaml.safe_load(PDL4))
|
|
162
|
+
>>> p.text.role
|
|
163
|
+
'user'
|
|
164
|
+
>>> p.text[0].role
|
|
165
|
+
'system'
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
>>> p = PDLProgram(yaml.safe_load(PDL5))
|
|
169
|
+
>>> p.descriptive_text()
|
|
170
|
+
"outputs to context, result as user (defining: {'file': '/tmp/file.txt'})"
|
|
171
|
+
>>> len(p.text)
|
|
172
|
+
2
|
|
173
|
+
|
|
174
|
+
>>> p.text[0]
|
|
175
|
+
PDLText('foo' [outputs to context as system])
|
|
176
|
+
|
|
177
|
+
>>> p.text[1]
|
|
178
|
+
PDLText('bar' [outputs to context, result as user])
|
|
179
|
+
|
|
180
|
+
>>> p.text[0].role
|
|
181
|
+
'system'
|
|
182
|
+
|
|
183
|
+
>>> p.text[0].contribute
|
|
184
|
+
['context']
|
|
185
|
+
|
|
186
|
+
>>> p.text[1].contribute
|
|
187
|
+
['context', 'result']
|
|
188
|
+
|
|
189
|
+
>>> p.execute(verbose=True)
|
|
190
|
+
Executing: program
|
|
191
|
+
'bar'
|
|
192
|
+
>>> p.evaluation_environment
|
|
193
|
+
{'_': [{'role': 'system', 'content': 'foo'}, {'role': 'user', 'content': 'bar'}]}
|
|
194
|
+
|
|
195
|
+
"""
|
|
196
|
+
|
|
197
|
+
def __init__(self,
|
|
198
|
+
content: Any,
|
|
199
|
+
program: PDLObject):
|
|
200
|
+
super().__init__(content["text"], program)
|
|
201
|
+
self._get_common_attributes(content)
|
|
202
|
+
self.program = program
|
|
203
|
+
|
|
204
|
+
def __repr__(self):
|
|
205
|
+
content_str = f"'{self.content}'" if isinstance(self.content, str) else f"{self.content}"
|
|
206
|
+
return f"PDLText({content_str} [{self.descriptive_text()}])"
|
|
207
|
+
|
|
208
|
+
def __iter__(self):
|
|
209
|
+
return iter(self.content)
|
|
210
|
+
|
|
211
|
+
def __getitem__(self, index: int):
|
|
212
|
+
return self.content[index]
|
|
213
|
+
|
|
214
|
+
def __len__(self):
|
|
215
|
+
return len(self.content)
|
|
216
|
+
|
|
217
|
+
def execute(self, context: Dict, verbose: bool = False):
|
|
218
|
+
""""""
|
|
219
|
+
content = ''
|
|
220
|
+
if isinstance(self.content, str):
|
|
221
|
+
self.merge_content(context, self.content)
|
|
222
|
+
if "result" in self.contribute:
|
|
223
|
+
pprint(self.content)
|
|
224
|
+
else:
|
|
225
|
+
for item in self.content:
|
|
226
|
+
if isinstance(item, str):
|
|
227
|
+
self.merge_content(context, item)
|
|
228
|
+
if "result" in self.contribute:
|
|
229
|
+
pprint(content)
|
|
230
|
+
else:
|
|
231
|
+
result = item.execute(context, verbose=verbose)
|
|
232
|
+
if result is not None:
|
|
233
|
+
self.merge_content(context, result)
|
|
234
|
+
merged_context = []
|
|
235
|
+
previous_item = None
|
|
236
|
+
for idx, item in enumerate(context.get("_", [])):
|
|
237
|
+
if idx > 0 and item["role"] == previous_item["role"]:
|
|
238
|
+
previous_item["content"] += item["content"]
|
|
239
|
+
else:
|
|
240
|
+
merged_context.append(item)
|
|
241
|
+
previous_item = item
|
|
242
|
+
context["_"] = merged_context
|
|
243
|
+
self._handle_execution_contribution(content, context)
|
|
244
|
+
|
|
245
|
+
def merge_content(self, context, item):
|
|
246
|
+
messages = context.setdefault('_', [])
|
|
247
|
+
if messages and [m for m in messages if m['role'] == "user"]:
|
|
248
|
+
messages[-1]["content"] += item
|
|
249
|
+
else:
|
|
250
|
+
messages.append({"role": self.role, "content": item})
|
|
251
|
+
|
|
252
|
+
@staticmethod
|
|
253
|
+
def dispatch_check(item: Mapping, program: PDLObject):
|
|
254
|
+
if "text" in item:
|
|
255
|
+
return PDLText(item, program)
|
|
256
|
+
|
|
257
|
+
class PDLRead(PDLObject, PDLStructuredBlock):
|
|
258
|
+
def __init__(self, pdl_block: Mapping, program: PDLObject):
|
|
259
|
+
self.program = program
|
|
260
|
+
self.read_from = pdl_block["read"] if pdl_block["read"] else None
|
|
261
|
+
self._get_common_attributes(pdl_block)
|
|
262
|
+
if not self.read_from:
|
|
263
|
+
self.message = pdl_block["message"]
|
|
264
|
+
self.read_from = pdl_block["read"]
|
|
265
|
+
else:
|
|
266
|
+
self.message = None
|
|
267
|
+
|
|
268
|
+
def __repr__(self):
|
|
269
|
+
if self.message:
|
|
270
|
+
return f"PDLRead('{self.message}' [{self.descriptive_text()}])"
|
|
271
|
+
else:
|
|
272
|
+
return f"PDLRead( from '{self.read_from}' [{self.descriptive_text()}])"
|
|
273
|
+
|
|
274
|
+
def execute(self, context: Dict, verbose: bool = False):
|
|
275
|
+
if self.read_from and isinstance(self.read_from, dict):
|
|
276
|
+
var_reference_group = VAR_REFERENCE_PATTERN.match(list(self.read_from)[0])
|
|
277
|
+
if var_reference_group:
|
|
278
|
+
variable_name = var_reference_group.group('variable')
|
|
279
|
+
file_name = context[variable_name]
|
|
280
|
+
else:
|
|
281
|
+
file_name = self.read_from
|
|
282
|
+
if verbose:
|
|
283
|
+
print(f"Reading {file_name} from context")
|
|
284
|
+
with open(file_name, "r") as file:
|
|
285
|
+
content = file.read()
|
|
286
|
+
else:
|
|
287
|
+
content = input(self.message + " ")
|
|
288
|
+
self._handle_execution_contribution(content, context)
|
|
289
|
+
|
|
290
|
+
@staticmethod
|
|
291
|
+
def dispatch_check(item: Mapping, program: PDLObject):
|
|
292
|
+
if "read" in item:
|
|
293
|
+
return PDLRead(item, program)
|
|
294
|
+
|
|
295
|
+
class PDLRepeat(PDLObject, PDLStructuredBlock):
|
|
296
|
+
def __init__(self, content: Mapping, program):
|
|
297
|
+
self.program = program
|
|
298
|
+
self.body = self.program.dispatcher.handle(content["repeat"], self.program)
|
|
299
|
+
self.until = content["until"]
|
|
300
|
+
self._get_common_attributes(content)
|
|
301
|
+
|
|
302
|
+
def __repr__(self):
|
|
303
|
+
return f"PDLRepeat({self.body} UNTIL {self.until} [{self.descriptive_text()}])"
|
|
304
|
+
|
|
305
|
+
def __getitem__(self, index: int):
|
|
306
|
+
return self.body[index]
|
|
307
|
+
|
|
308
|
+
def execute(self, context: Mapping, verbose: bool = False):
|
|
309
|
+
"""
|
|
310
|
+
Executes the provided action repeatedly until a condition is met based on the values in the provided context.
|
|
311
|
+
|
|
312
|
+
Continues to execute its body until the specified variable in the context matches the target value as defined
|
|
313
|
+
by the `until` condition. The evaluation of the until expression determines the stopping criteria
|
|
314
|
+
"""
|
|
315
|
+
self.body.execute(context)
|
|
316
|
+
until_pattern_groups = UNTIL_PATTERN.match(self.until)
|
|
317
|
+
variable_name = until_pattern_groups.group('variable')
|
|
318
|
+
value = until_pattern_groups.group('value')
|
|
319
|
+
while value != context[variable_name]:
|
|
320
|
+
self.body.execute(context)
|
|
321
|
+
|
|
322
|
+
@staticmethod
|
|
323
|
+
def dispatch_check(item: Mapping, program: PDLObject):
|
|
324
|
+
if "repeat" in item:
|
|
325
|
+
return PDLRepeat(item, program)
|
|
326
|
+
|
|
327
|
+
class PDLModel(PDLObject, PDLStructuredBlock):
|
|
328
|
+
"""
|
|
329
|
+
Meant to be extended and for its execute method to be overridden for LLM evaluation
|
|
330
|
+
"""
|
|
331
|
+
default_role = "assistant"
|
|
332
|
+
MODEL_KEY = "model"
|
|
333
|
+
def __init__(self, content: Mapping, program):
|
|
334
|
+
self.program = program
|
|
335
|
+
self.model = content[self.MODEL_KEY]
|
|
336
|
+
self.content = content
|
|
337
|
+
self.input = self.program.dispatcher.handle(content["input"], self.program) if "input" in content else None
|
|
338
|
+
self.parameters = content["parameters"] if "parameters" in content else {}
|
|
339
|
+
self.alpha_one = content["alpha_one"] if "alpha_one" in content else {}
|
|
340
|
+
if "draft_model" in content:
|
|
341
|
+
self.draft_model = content["draft_model"]
|
|
342
|
+
else:
|
|
343
|
+
self.draft_model = None
|
|
344
|
+
self.cot_prefix = content["cot_prefix"] if "cot_prefix" in content else None
|
|
345
|
+
self._get_common_attributes(content)
|
|
346
|
+
|
|
347
|
+
def __repr__(self):
|
|
348
|
+
return f"PDLModel({self.model} [{self.descriptive_text()}])"
|
|
349
|
+
|
|
350
|
+
def execute(self, context: Dict, verbose: bool = False):
|
|
351
|
+
source_phrase = ""
|
|
352
|
+
if self.input:
|
|
353
|
+
source_phrase = f" from {self.input}"
|
|
354
|
+
if verbose:
|
|
355
|
+
print(f"Executing model: {self.model} using {context}{source_phrase}")
|
|
356
|
+
self._handle_execution_contribution(".. model response ..", context)
|
|
357
|
+
|
|
358
|
+
@staticmethod
|
|
359
|
+
def dispatch_check(item: Mapping, program: PDLObject) -> Optional[PDLObject]:
|
|
360
|
+
if "model" in item:
|
|
361
|
+
return PDLModel(item, program)
|
|
362
|
+
|
|
363
|
+
class PDFRead(PDLObject, PDLStructuredBlock):
|
|
364
|
+
"""
|
|
365
|
+
Class that handles PDF reading as part of the execution of a PDL program
|
|
366
|
+
|
|
367
|
+
Parses and extracts from PDF and contributes to the larger operational workflow
|
|
368
|
+
of the execution of a PDL program, leveraging PyPDF2 for the extraction.
|
|
369
|
+
|
|
370
|
+
"""
|
|
371
|
+
def __init__(self, pdl_block: Mapping, program: PDLObject):
|
|
372
|
+
self.program = program
|
|
373
|
+
self.read_from = pdl_block["PDF_read"]
|
|
374
|
+
self._get_common_attributes(pdl_block)
|
|
375
|
+
if not self.read_from:
|
|
376
|
+
self.message = pdl_block["message"]
|
|
377
|
+
self.read_from = pdl_block["read"]
|
|
378
|
+
else:
|
|
379
|
+
self.message = None
|
|
380
|
+
|
|
381
|
+
def __repr__(self):
|
|
382
|
+
return f"PDFRead( from '{self.read_from}' [{self.descriptive_text()}])"
|
|
383
|
+
|
|
384
|
+
def execute(self, context: Dict, verbose: bool = False):
|
|
385
|
+
from PyPDF2 import PdfReader
|
|
386
|
+
if self.read_from and isinstance(self.read_from, dict):
|
|
387
|
+
var_reference_group = VAR_REFERENCE_PATTERN.match(list(self.read_from)[0])
|
|
388
|
+
if var_reference_group:
|
|
389
|
+
variable_name = var_reference_group.group('variable')
|
|
390
|
+
file_name = context[variable_name]
|
|
391
|
+
else:
|
|
392
|
+
file_name = self.read_from
|
|
393
|
+
else:
|
|
394
|
+
file_name = self.read_from
|
|
395
|
+
if verbose:
|
|
396
|
+
print(f"Reading {file_name} from context")
|
|
397
|
+
content = ''.join((page.extract_text() for page in PdfReader(file_name).pages))
|
|
398
|
+
self._handle_execution_contribution(content, context)
|
|
399
|
+
|
|
400
|
+
@staticmethod
|
|
401
|
+
def dispatch_check(item: Mapping, program: PDLObject):
|
|
402
|
+
if "PDF_read" in item:
|
|
403
|
+
return PDFRead(item, program)
|
|
404
|
+
|
|
405
|
+
class ParseDispatcher:
|
|
406
|
+
DISPATCH_RESOLUTION_ORDER = [PDLRead, PDLRepeat, PDLText, PDLModel]
|
|
407
|
+
|
|
408
|
+
def handle(self, item: Mapping, program: PDLObject) -> PDLObject:
|
|
409
|
+
if isinstance(item, str):
|
|
410
|
+
return item
|
|
411
|
+
else:
|
|
412
|
+
for klass in self.DISPATCH_RESOLUTION_ORDER:
|
|
413
|
+
obj = klass.dispatch_check(item, program)
|
|
414
|
+
if obj is not None:
|
|
415
|
+
return obj
|
|
416
|
+
raise RuntimeError(f"Unknown block type: {item}")
|
|
417
|
+
|
|
418
|
+
class PDLProgram(PDLObject, PDLStructuredBlock):
|
|
419
|
+
"""
|
|
420
|
+
A PDL "program"
|
|
421
|
+
|
|
422
|
+
A block or a list of blocks where blocks are expressions or structured blocks
|
|
423
|
+
|
|
424
|
+
Example:
|
|
425
|
+
>>> import yaml
|
|
426
|
+
>>> program = PDLProgram(yaml.safe_load(PDL))
|
|
427
|
+
>>> print(program.text.content[0])
|
|
428
|
+
PDLRead('What is your query? ' [outputs to context as user])
|
|
429
|
+
>>> print(len(program.text.content))
|
|
430
|
+
2
|
|
431
|
+
>>> print(type(program.text[1]))
|
|
432
|
+
<class 'object_pdl_model.PDLRepeat'>
|
|
433
|
+
>>> print(type(program.text[1].body))
|
|
434
|
+
<class 'object_pdl_model.PDLText'>
|
|
435
|
+
|
|
436
|
+
>>> print(len(program.text[1].body))
|
|
437
|
+
2
|
|
438
|
+
>>> print(program.text[1][0])
|
|
439
|
+
PDLModel(google/gemma-2-9b-it [outputs to context, result as assistant])
|
|
440
|
+
>>> print(program.text[1][1])
|
|
441
|
+
PDLRead('Enter a query or say 'quit' to exit' [outputs to context as user -> $question])
|
|
442
|
+
>>> print(program.text[1].until)
|
|
443
|
+
${ question == 'quit' }
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
>>> program = PDLProgram(yaml.safe_load(PDL2))
|
|
447
|
+
>>> len(program.text.content)
|
|
448
|
+
1
|
|
449
|
+
|
|
450
|
+
>>> type(program.text.content[0])
|
|
451
|
+
<class 'object_pdl_model.PDLModel'>
|
|
452
|
+
|
|
453
|
+
>>> program.text[0].input[0]
|
|
454
|
+
PDLRead( from 'some_file.txt' [outputs to context as user])
|
|
455
|
+
|
|
456
|
+
>>> print(program.text[0].input[-1])
|
|
457
|
+
<BLANKLINE>
|
|
458
|
+
Long text.
|
|
459
|
+
|
|
460
|
+
>>> program.text[0].parameters
|
|
461
|
+
{'temperature': 0.6, 'min_p': 0.03, 'max_tokens': 600}
|
|
462
|
+
|
|
463
|
+
>>> program.execute()
|
|
464
|
+
'.. model response ..'
|
|
465
|
+
|
|
466
|
+
>>> program.evaluation_environment
|
|
467
|
+
{'_': [{'role': 'assistant', 'content': '.. model response ..'}]}
|
|
468
|
+
"""
|
|
469
|
+
INTERNAL_CACHE_NAME = "*"
|
|
470
|
+
def __init__(self, pdl: dict, dispatcher: ParseDispatcher = None, initial_context: Dict = None):
|
|
471
|
+
if dispatcher is None:
|
|
472
|
+
self.dispatcher = ParseDispatcher()
|
|
473
|
+
else:
|
|
474
|
+
self.dispatcher = dispatcher
|
|
475
|
+
self.text = PDLText(pdl, self)
|
|
476
|
+
self.cache = pdl.get("cache")
|
|
477
|
+
self._get_common_attributes(pdl)
|
|
478
|
+
self.evaluation_environment = initial_context if initial_context else {}
|
|
479
|
+
|
|
480
|
+
def __repr__(self):
|
|
481
|
+
program_state = self.evaluation_environment if self.evaluation_environment else 'unexecuted'
|
|
482
|
+
caching_info = f" [caching to {self.cache}]" if self.cache else ""
|
|
483
|
+
return f"PDLProgram('{self.description}'\n\t{self.text}\n\t{program_state}{caching_info})"
|
|
484
|
+
|
|
485
|
+
def execute(self, verbose: bool = False):
|
|
486
|
+
if verbose:
|
|
487
|
+
print(f"Executing: {self.description}")
|
|
488
|
+
self.text.execute(self.evaluation_environment, verbose=verbose)
|
|
489
|
+
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: generative_redfoot
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A generative, conversational workflow and multi-agent system using PDL and mlx
|
|
5
|
+
Author-email: Chimezie Ogbuji <chimezie@gmail.com>
|
|
6
|
+
License: MIT License
|
|
7
|
+
|
|
8
|
+
Copyright (c) 2024 Chime Ogbuji
|
|
9
|
+
|
|
10
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
11
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
12
|
+
in the Software without restriction, including without limitation the rights
|
|
13
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
14
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
15
|
+
furnished to do so, subject to the following conditions:
|
|
16
|
+
|
|
17
|
+
The above copyright notice and this permission notice shall be included in all
|
|
18
|
+
copies or substantial portions of the Software.
|
|
19
|
+
|
|
20
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
21
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
22
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
23
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
24
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
25
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
26
|
+
SOFTWARE.
|
|
27
|
+
|
|
28
|
+
Project-URL: Homepage, https://github.com/chimezie/generative_redfoot
|
|
29
|
+
Project-URL: Repository, https://github.com/chimezie/generative_redfoot
|
|
30
|
+
Classifier: Development Status :: 4 - Beta
|
|
31
|
+
Classifier: Programming Language :: Python
|
|
32
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
33
|
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
|
34
|
+
Requires-Python: >=3.10
|
|
35
|
+
Description-Content-Type: text/markdown
|
|
36
|
+
License-File: LICENSE
|
|
37
|
+
Requires-Dist: pyaml
|
|
38
|
+
Requires-Dist: click
|
|
39
|
+
Requires-Dist: tqdm
|
|
40
|
+
Requires-Dist: ogbujipt
|
|
41
|
+
Requires-Dist: mlx>=0.26.3
|
|
42
|
+
Requires-Dist: mlx-lm>=0.26.0
|
|
43
|
+
Requires-Dist: pytest
|
|
44
|
+
Requires-Dist: transformers
|
|
45
|
+
Provides-Extra: gemma-aps
|
|
46
|
+
Requires-Dist: nltk; extra == "gemma-aps"
|
|
47
|
+
Dynamic: license-file
|
|
48
|
+
|
|
49
|
+
# Generative Redfoot
|
|
50
|
+
A generative, conversational workflow and multi-agent system using PDL and [mlx](https://github.com/ml-explore/mlx-examples/tree/main/llms)
|
|
51
|
+
|
|
52
|
+
Takes a minimal [Prompt Declaration Language (PDL)](https://github.com/IBM/prompt-declaration-language) file and generates a finite state generative machine
|
|
53
|
+
as Python objects for a subset of the PDL language. These objects (the "programs" in particular) can be executed.
|
|
54
|
+
|
|
55
|
+
It was mainly motivated by supporting this use case from the PDL documentation/paper:
|
|
56
|
+
|
|
57
|
+
<img src="animated_chatbot.gif" alt="Animated GIF of PDL chatbot."/>
|
|
58
|
+
|
|
59
|
+
The Model class can be extended and incorporated into how a dispatcher creates the PDL Python objects from a PDL file to incorporate the functionality for evaluating
|
|
60
|
+
the prompts against the models specified in PDL. This is done using any accumulated conversational context, prompts, and generation parameters (sampling parameters, for example),
|
|
61
|
+
(optionally) updating the context as the program execution continues and how mlx is used to implement the model loading and inference.
|
|
62
|
+
|
|
63
|
+
However, the language of the PDL file can be extended with additional custom functionality, and
|
|
64
|
+
other LLM systems can handle the evaluation.
|
|
65
|
+
|
|
66
|
+
## Usage
|
|
67
|
+
|
|
68
|
+
It depends on the PyYaml and click third-party Python libraries as well as mlx and can be run this way, where `document.pdl` is a PDL file.
|
|
69
|
+
```commandline
|
|
70
|
+
% Usage: generative_redfoot [OPTIONS] PDL_FILE
|
|
71
|
+
|
|
72
|
+
Options:
|
|
73
|
+
-t, --temperature FLOAT
|
|
74
|
+
-rp, --repetition-penalty FLOAT
|
|
75
|
+
The penalty factor for repeating tokens
|
|
76
|
+
(none if not used)
|
|
77
|
+
--top-k INTEGER Sampling top-k
|
|
78
|
+
--top-p INTEGER Sampling top-p
|
|
79
|
+
--max-tokens INTEGER Max tokens
|
|
80
|
+
--min-p FLOAT Sampling min-p
|
|
81
|
+
--verbose / --no-verbose
|
|
82
|
+
-v, --variables <TEXT TEXT>...
|
|
83
|
+
--help Show this message and exit.
|
|
84
|
+
|
|
85
|
+
generative_redfoot.py document.pdl
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
The main argument is a PDL program (a YAML file), possibly with extensions of the language implemented by generative_redfoot.
|
|
89
|
+
|
|
90
|
+
You can also specify default values for sampling parameters for the LLM calls during the execution of the programs
|
|
91
|
+
using mlx.
|
|
92
|
+
|
|
93
|
+
The model _parameters_ directive in PDL can be used to specify the following mlx generation parameters: **temperature**, **top_k**, **min_p**, **max_tokens**, and **top_p**:
|
|
94
|
+
|
|
95
|
+
```yaml
|
|
96
|
+
description: ...
|
|
97
|
+
text:
|
|
98
|
+
- read:
|
|
99
|
+
message: |
|
|
100
|
+
What is your query?
|
|
101
|
+
contribute: [context]
|
|
102
|
+
- model: .. model ..
|
|
103
|
+
parameters:
|
|
104
|
+
temperature: 0.6
|
|
105
|
+
min_p: .03
|
|
106
|
+
max_tokens: 200
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
## Extensions
|
|
110
|
+
|
|
111
|
+
Generative Redfoot defines a number of extensions from PDL
|
|
112
|
+
|
|
113
|
+
### PDF Reading
|
|
114
|
+
|
|
115
|
+
The `PDF_read` block can be used (within a `text` block) to read content from a PDF file (uses and requires [PyPDF2](https://pypdf2.readthedocs.io/en/3.x/)).
|
|
116
|
+
You can specify where the text is constibuted to (the 'context' is the most common scenario). Below is an example
|
|
117
|
+
that reads PDF content from a run-time specified filename and uses it as context for a model evaluation:
|
|
118
|
+
|
|
119
|
+
```yaml
|
|
120
|
+
description: autocoding_from_pdf
|
|
121
|
+
text:
|
|
122
|
+
- text:
|
|
123
|
+
- PDF_read: { $context_file }
|
|
124
|
+
contribute: [context]
|
|
125
|
+
- |
|
|
126
|
+
|
|
127
|
+
Provide a list of the 5 ICD-10 codes mentioned in the document above
|
|
128
|
+
contribute: [context]
|
|
129
|
+
- model: mlx-community/medgemma-4b-it-4bit
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
### Toolio
|
|
133
|
+
|
|
134
|
+
[Toolio](https://github.com/OoriData/Toolio) can be used for structured output by specifying a `structured_output`
|
|
135
|
+
block like so (from [Toolio algebra tutor demo](https://github.com/OoriData/Toolio/blob/main/demo/algebra_tutor.py)):
|
|
136
|
+
|
|
137
|
+
```yaml
|
|
138
|
+
description: structured_output
|
|
139
|
+
text:
|
|
140
|
+
- structured_output: mlx-community/Llama-3.2-3B-Instruct-4bit
|
|
141
|
+
insert_schema: true
|
|
142
|
+
schema_file: ToolioGit/demo/algebra_tutor.schema.json
|
|
143
|
+
parameters:
|
|
144
|
+
temperature: 0.6
|
|
145
|
+
max_tokens: 512
|
|
146
|
+
input: |
|
|
147
|
+
solve 8x + 31 = 2. Your answer should be only JSON, according to this schema: #!JSON_SCHEMA!#"
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
Beyond the approach above, its input can be specified in all the ways a PDL model can.
|
|
151
|
+
|
|
152
|
+
### Alpha One Reasoning
|
|
153
|
+
|
|
154
|
+
[AlphaOne (α)](https://alphaone-project.github.io/) reasoning modulation can be used with
|
|
155
|
+
a supported, reasoning model using [Alpha One MLX](https://github.com/chimezie/alpha-one-mlx) via providing
|
|
156
|
+
a `alpha_one` block within a model:
|
|
157
|
+
|
|
158
|
+
```yaml
|
|
159
|
+
description: alpha_one_reasoning
|
|
160
|
+
text:
|
|
161
|
+
- model: mlx-community/DeepSeek-R1-0528-Qwen3-8B-4bit-AWQ
|
|
162
|
+
parameters:
|
|
163
|
+
temperature: 0.6
|
|
164
|
+
max_tokens: 1200
|
|
165
|
+
repetition_penalty: 1.4
|
|
166
|
+
top_k: 20
|
|
167
|
+
top_p: 0.95
|
|
168
|
+
alpha_one:
|
|
169
|
+
thinking_token_length: 250
|
|
170
|
+
alpha: 1.4
|
|
171
|
+
wait_words: ["Wait"]
|
|
172
|
+
input: |
|
|
173
|
+
What question has an answer of "42?"
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
This algorithm scales the average thinking phase token length (specified by the `thinking_token_length` parameter and
|
|
177
|
+
with a default of 2,650) by the `alpha` parameter (which defaults to 1.4 per the paper). After
|
|
178
|
+
exiting this phase, it suppresses attempts to transition to slow thinking by replacing references to 'Wait' words
|
|
179
|
+
with the _"</think>"_ token. The specific list of these words can be provided via the `wait_words` parameter or the
|
|
180
|
+
defaults specified by alpha-one-mlx for each model type will be used.
|
|
181
|
+
|
|
182
|
+
### Prompt management via Wordloom
|
|
183
|
+
|
|
184
|
+
Prompt snippets can be loaded for use in a PDL file via a [word loom](https://github.com/OoriData/OgbujiPT/wiki/Word-Loom%3A-Format-%26-tools-for-managing-natural-language-for-AI-LLMs)
|
|
185
|
+
library, providing a clean separation of concerns between prompt language management, prompt construction, and
|
|
186
|
+
LLM workflow management and orchestration. This requires [OgbujiPT](https://github.com/OoriData/OgbujiPT) and below is
|
|
187
|
+
an example that constructs the system and user prompt from a word loom ([TOML](https://toml.io/en/)) file:
|
|
188
|
+
|
|
189
|
+
```yaml
|
|
190
|
+
description: wordloom_prompt_example
|
|
191
|
+
text:
|
|
192
|
+
- text:
|
|
193
|
+
- role: system
|
|
194
|
+
read_from_wordloom: prompt_library.toml
|
|
195
|
+
items: helpful_chatbot_system_prompt
|
|
196
|
+
contribute: [context]
|
|
197
|
+
- text:
|
|
198
|
+
- read_from_wordloom: prompt_library.toml
|
|
199
|
+
items: hello_prompt
|
|
200
|
+
contribute: [context]
|
|
201
|
+
- model: mlx-community/Llama-3.2-3B-Instruct-4bit
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
The `read_from_wordloom` block indicates the use of this extension mechanism and its value is a path to a Word loom.
|
|
205
|
+
|
|
206
|
+
The `items` parameter on the block is a space-separated list of language item names in the word loom. Their values are
|
|
207
|
+
joined together with `\n` and returned as a value for use (as an example from above) to construct the message for
|
|
208
|
+
conversations used by downstream PDL directives.
|
|
209
|
+
|
|
210
|
+
In the example above, the `helpful_chatbot_system_prompt` language item from the `prompt_library.toml` word loom is used
|
|
211
|
+
as the system prompt and the `hello_prompt` language item from the same file is used as the user prompt:
|
|
212
|
+
|
|
213
|
+
```JSON
|
|
214
|
+
[
|
|
215
|
+
{"role": "system", "content": ".. helpful_chatbot_system_prompt language item .. "},
|
|
216
|
+
{"role": "user", "content": ".. hello_prompt language item .. "}
|
|
217
|
+
]
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
### Caching
|
|
221
|
+
A PDL program can use mlx-lm's [Prompt caching](https://github.com/ml-explore/mlx-lm/blob/main/README.md#long-prompts-and-generations)
|
|
222
|
+
by specifying a top-level `cache` parameter at the top of the PDL document. If the value of this parameter is _'*'_,
|
|
223
|
+
then an internal, rotating K/V cache is used for the duration of the PDL evaluation for efficiency.
|
|
224
|
+
|
|
225
|
+
Otherwise, the value is expected to be the path to a previously saved cache, created using `mlx_lm.cache_prompt` for
|
|
226
|
+
example, which is treated as a cached prompt that is a prefix to any prompts specified in the program.
|
|
227
|
+
|
|
228
|
+
### Chain of Thought (CoT) prefix
|
|
229
|
+
If specified within a model block, the `cot_prefix` parameter takes a path to a file that captures COT few shot content
|
|
230
|
+
as a file in the [LLM chat conversation](https://model-spec.openai.com/2025-02-12.html#definitions) JSON format. This
|
|
231
|
+
will be incorporated into the conversation structure to ensure this files content is used as few shot / COT for the
|
|
232
|
+
model generation
|
|
233
|
+
|
|
234
|
+
## Complex example
|
|
235
|
+
|
|
236
|
+
Below is an example showing a PDL file constructing message contexts for prompts to chained LLM calls from fragments
|
|
237
|
+
in a [Wordloom](https://github.com/OoriData/OgbujiPT/wiki/Word-Loom%3A-Format-%26-tools-for-managing-natural-language-for-AI-LLMs)
|
|
238
|
+
library, providing a clean separation of concerns between prompt language management, prompt construction, and
|
|
239
|
+
LLM workflow management and orchestration. The keys in the YAML file in black use the PDL language. Those in
|
|
240
|
+
red are generative_redfoot extensions shown in order of appearance: (mlx) prefix caching, COT few-shot loading,
|
|
241
|
+
reading from a wordloom file, using Google's [__google/gemma-7b-aps-it__](https://huggingface.co/google/gemma-7b-aps-it)
|
|
242
|
+
model to perform ["abstractive proposition segmentation"](https://arxiv.org/abs/2406.19803) from LLM output,
|
|
243
|
+
etc.:
|
|
244
|
+
|
|
245
|
+
<img src="complex_pdl.png" alt="Animated GIF of PDL chatbot."/>
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
generative_redfoot/__init__.py,sha256=Pru0BlFBASFCFo7McHdohtKkUtgMPDwbGfyUZlE2_Vw,21
|
|
2
|
+
generative_redfoot/cli.py,sha256=Eolw5hL9EEV7dmCWy-68ZJf_hvmOTObMy6bhOKE4QjY,11494
|
|
3
|
+
generative_redfoot/object_pdl_model.py,sha256=NWYkd3hMbdiXyglK2hETAoh6J5XMfkQrho_Ag-Y_Fg4,17655
|
|
4
|
+
generative_redfoot/utils.py,sha256=27C28jCLvJsCmNbR7ylhJRhlCE8RDqzsVVGqO1Itbak,255
|
|
5
|
+
generative_redfoot/extensions/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
generative_redfoot/extensions/toolio.py,sha256=HbYUEnw4snYPzmGYpWjcMI_afB_Qe_VZ_dHOtW6B1bM,3981
|
|
7
|
+
generative_redfoot/extensions/wordloom.py,sha256=fyL4A9Fz9IUdr2zzdu9L7EWqmtdpVC0stmrU3_Jy8e0,2739
|
|
8
|
+
generative_redfoot-0.1.0.dist-info/licenses/LICENSE,sha256=6Vq4m5PAhejup27tMJEaXnbGtANWSVD8uA4nxDp2NKg,1069
|
|
9
|
+
generative_redfoot-0.1.0.dist-info/METADATA,sha256=BWW2AtaVeZ5Unb-iDRhmufSGi6_Lf9mu6ES3qPmCcSU,11091
|
|
10
|
+
generative_redfoot-0.1.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
11
|
+
generative_redfoot-0.1.0.dist-info/entry_points.txt,sha256=fo0PqR8GxPxFK81oHPOvfTk3H-ccOWR_RHGFDviHQUw,67
|
|
12
|
+
generative_redfoot-0.1.0.dist-info/top_level.txt,sha256=PIvtkxkiaYaFuFIFSIZPscoS_Hoz6EtQf6Lf-q2mVG8,19
|
|
13
|
+
generative_redfoot-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Chime Ogbuji
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
generative_redfoot
|