-
Notifications
You must be signed in to change notification settings - Fork 257
/
Copy pathgenerator_note.py
385 lines (307 loc) · 10.5 KB
/
generator_note.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
from dataclasses import dataclass, field
from adalflow.core import Component, Generator, DataClass
from adalflow.components.model_client import GroqAPIClient
from adalflow.components.output_parsers import JsonOutputParser
from adalflow.utils import setup_env
setup_env()
class SimpleQA(Component):
def __init__(self):
super().__init__()
template = r"""<SYS>
You are a helpful assistant.
</SYS>
User: {{input_str}}
You:
"""
self.generator = Generator(
model_client=GroqAPIClient(),
model_kwargs={"model": "llama3-8b-8192"},
template=template,
)
def call(self, query):
return self.generator({"input_str": query})
async def acall(self, query):
return await self.generator.acall({"input_str": query})
@dataclass
class QAOutput(DataClass):
explanation: str = field(
metadata={"desc": "A brief explanation of the concept in one sentence."}
)
example: str = field(metadata={"desc": "An example of the concept in a sentence."})
qa_template = r"""<SYS>
You are a helpful assistant.
<OUTPUT_FORMAT>
{{output_format_str}}
</OUTPUT_FORMAT>
</SYS>
User: {{input_str}}
You:"""
class QA(Component):
def __init__(self):
super().__init__()
parser = JsonOutputParser(data_class=QAOutput, return_data_class=True)
self.generator = Generator(
model_client=GroqAPIClient(),
model_kwargs={"model": "llama3-8b-8192"},
template=qa_template,
prompt_kwargs={"output_format_str": parser.format_instructions()},
output_processors=parser,
)
def call(self, query: str):
return self.generator.call({"input_str": query})
async def acall(self, query: str):
return await self.generator.acall({"input_str": query})
def minimum_generator():
from adalflow.core import Generator
from adalflow.components.model_client import GroqAPIClient
generator = Generator(
model_client=GroqAPIClient(),
model_kwargs={"model": "llama3-8b-8192"},
)
print(generator)
prompt_kwargs = {"input_str": "What is LLM? Explain in one sentence."}
generator.print_prompt(**prompt_kwargs)
output = generator(
prompt_kwargs=prompt_kwargs,
)
print(output)
def use_a_json_parser():
from adalflow.core import Generator
from adalflow.core.types import GeneratorOutput
from adalflow.components.model_client import OpenAIClient
from adalflow.core.string_parser import JsonParser
output_format_str = """Your output should be formatted as a standard JSON object with two keys:
{
"explaination": "A brief explaination of the concept in one sentence.",
"example": "An example of the concept in a sentence."
}
"""
generator = Generator(
model_client=OpenAIClient(),
model_kwargs={"model": "gpt-3.5-turbo"},
prompt_kwargs={"output_format_str": output_format_str},
output_processors=JsonParser(),
)
prompt_kwargs = {"input_str": "What is LLM?"}
generator.print_prompt(**prompt_kwargs)
output: GeneratorOutput = generator(prompt_kwargs=prompt_kwargs)
print(output)
print(type(output.data))
print(output.data)
def use_its_own_template():
from adalflow.core import Generator
from adalflow.components.model_client import GroqAPIClient
template = r"""<SYS>{{task_desc_str}}</SYS>
User: {{input_str}}
You:"""
generator = Generator(
model_client=GroqAPIClient(),
model_kwargs={"model": "llama3-8b-8192"},
template=template,
prompt_kwargs={"task_desc_str": "You are a helpful assistant"},
)
prompt_kwargs = {"input_str": "What is LLM?"}
generator.print_prompt(
**prompt_kwargs,
)
output = generator(
prompt_kwargs=prompt_kwargs,
)
print(output)
def use_model_client_enum_to_switch_client():
from adalflow.core import Generator
from adalflow.core.types import ModelClientType
generator = Generator(
model_client=ModelClientType.OPENAI(), # or ModelClientType.GROQ()
model_kwargs={"model": "gpt-3.5-turbo"},
)
print(generator)
prompt_kwargs = {"input_str": "What is LLM? Explain in one sentence."}
generator.print_prompt(**prompt_kwargs)
output = generator(
prompt_kwargs=prompt_kwargs,
)
print(output)
def create_purely_from_config():
from adalflow.utils.config import new_component
from adalflow.core import Generator
config = {
"generator": {
"component_name": "Generator",
"component_config": {
"model_client": {
"component_name": "GroqAPIClient",
"component_config": {},
},
"model_kwargs": {
"model": "llama3-8b-8192",
},
},
}
}
generator: Generator = new_component(config["generator"])
print(generator)
prompt_kwargs = {"input_str": "What is LLM? Explain in one sentence."}
generator.print_prompt(**prompt_kwargs)
output = generator(
prompt_kwargs=prompt_kwargs,
)
print(output)
def create_purely_from_config_2():
from adalflow.core import Generator
config = {
"model_client": {
"component_name": "GroqAPIClient",
"component_config": {},
},
"model_kwargs": {
"model": "llama3-8b-8192",
},
}
generator: Generator = Generator.from_config(config)
print(generator)
prompt_kwargs = {"input_str": "What is LLM? Explain in one sentence."}
generator.print_prompt(**prompt_kwargs)
output = generator(
prompt_kwargs=prompt_kwargs,
)
print(output)
def simple_query():
from adalflow.core import Generator
from adalflow.components.model_client.openai_client import OpenAIClient
gen = Generator(
model_client=OpenAIClient(),
model_kwargs={
"model": "o3-mini",
},
)
response = gen({"input_str": "What is LLM?"})
print(response)
def customize_template():
import adalflow as adal
# the template has three variables: system_prompt, few_shot_demos, and input_str
few_shot_template = r"""<START_OF_SYSTEM_PROMPT>
{{system_prompt}}
{# Few shot demos #}
{% if few_shot_demos is not none %}
Here are some examples:
{{few_shot_demos}}
{% endif %}
<END_OF_SYSTEM_PROMPT>
<START_OF_USER>
{{input_str}}
<END_OF_USER>"""
object_counter = Generator(
model_client=adal.GroqAPIClient(),
model_kwargs={
"model": "llama3-8b-8192",
},
template=few_shot_template,
prompt_kwargs={
"system_prompt": "You will answer a reasoning question. Think step by step. The last line of your response should be of the following format: 'Answer: $VALUE' where VALUE is a numerical value.",
},
)
question = "I have a flute, a piano, a trombone, four stoves, a violin, an accordion, a clarinet, a drum, two lamps, and a trumpet. How many musical instruments do I have?"
response = object_counter(prompt_kwargs={"input_str": question})
print(response)
object_counter.print_prompt(input_str=question)
# use an int parser
from adalflow.core.string_parser import IntParser
object_counter = Generator(
model_client=adal.GroqAPIClient(),
model_kwargs={
"model": "llama3-8b-8192",
},
template=few_shot_template,
prompt_kwargs={
"system_prompt": "You will answer a reasoning question. Think step by step. The last line of your response should be of the following format: 'Answer: $VALUE' where VALUE is a numerical value.",
},
output_processors=IntParser(),
)
response = object_counter(prompt_kwargs={"input_str": question})
print(response)
print(type(response.data))
# use customize parser
import re
@adal.func_to_data_component
def parse_integer_answer(answer: str):
try:
numbers = re.findall(r"\d+", answer)
if numbers:
answer = int(numbers[-1])
else:
answer = -1
except ValueError:
answer = -1
return answer
object_counter = Generator(
model_client=adal.GroqAPIClient(),
model_kwargs={
"model": "llama3-8b-8192",
},
template=few_shot_template,
prompt_kwargs={
"system_prompt": "You will answer a reasoning question. Think step by step. The last line of your response should be of the following format: 'Answer: $VALUE' where VALUE is a numerical value.",
},
output_processors=parse_integer_answer,
)
response = object_counter(prompt_kwargs={"input_str": question})
print(response)
print(type(response.data))
template = r"""<START_OF_SYSTEM_PROMPT>
{{system_prompt}}
<OUTPUT_FORMAT>
{{output_format_str}}
</OUTPUT_FORMAT>
<END_OF_SYSTEM_PROMPT>
<START_OF_USER>
{{input_str}}
<END_OF_USER>"""
from dataclasses import dataclass, field
@dataclass
class QAOutput(DataClass):
thought: str = field(
metadata={
"desc": "Your thought process for the question to reach the answer."
}
)
answer: int = field(metadata={"desc": "The answer to the question."})
__output_fields__ = ["thought", "answer"]
parser = adal.DataClassParser(
data_class=QAOutput, return_data_class=True, format_type="json"
)
object_counter = Generator(
model_client=adal.GroqAPIClient(),
model_kwargs={
"model": "llama3-8b-8192",
},
template=template,
prompt_kwargs={
"system_prompt": "You will answer a reasoning question. Think step by step. ",
"output_format_str": parser.get_output_format_str(),
},
output_processors=parser,
)
response = object_counter(prompt_kwargs={"input_str": question})
print(response)
object_counter.print_prompt(input_str=question)
if __name__ == "__main__":
qa1 = SimpleQA()
answer = qa1("What is adalflow?")
print(qa1)
qa2 = QA()
answer = qa2("What is LLM?")
print(qa2)
print(answer)
qa2.generator.print_prompt(
output_format_str=qa2.generator.output_processors.format_instructions(),
input_str="What is LLM?",
)
minimum_generator()
simple_query()
customize_template()
# use_a_json_parser()
# use_its_own_template()
# use_model_client_enum_to_switch_client()
# create_purely_from_config()
# create_purely_from_config_2()