-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathschema.py
358 lines (269 loc) · 9.76 KB
/
schema.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
# -*- coding: utf-8 -*-
import json
import sys
import typing
import types
from enum import Enum
from functools import reduce
from textwrap import dedent, indent
from typing import Union, List, Dict, Set, Tuple, FrozenSet
from dataclasses import (
dataclass,
fields,
asdict,
is_dataclass,
MISSING,
)
from llama_cpp.llama_grammar import LlamaGrammar
def is_generic_alias(type):
if sys.version_info >= (3, 9):
return isinstance(type, types.GenericAlias) or isinstance(
type, typing._GenericAlias
)
else:
return isinstance(type, typing._GenericAlias)
def convert_native_container_type(container_type, items_type):
items = convert_field_type(items_type)
mapping = {
List: {"type": "array", "items": items},
Tuple: {"type": "array", "items": items},
Dict: {"type": "object", "additionalProperties": items},
Set: {"type": "array", "uniqueItems": True, "items": items},
FrozenSet: {"type": "array", "uniqueItems": True, "items": items},
list: {"type": "array", "items": items},
tuple: {"type": "array", "items": items},
dict: {"type": "object", "additionalProperties": items},
set: {"type": "array", "uniqueItems": True, "items": items},
frozenset: {"type": "array", "uniqueItems": True, "items": items},
}
return mapping[container_type]
def convert_generic_alias(field_type):
container_type = field_type.__origin__
items_type = field_type.__args__
if len(items_type) != 1:
print(field_type)
print(items_type)
raise NotImplementedError("Complex annotations are not supported")
items_type = items_type[0]
return convert_native_container_type(container_type, items_type)
def convert_union(field_type):
available_types = field_type.__args__
return {"anyOf": [convert_field_type(t) for t in available_types]}
def convert_complex_field_type(field_type):
try:
if is_dataclass(field_type):
return to_json_schema(field_type)
elif (
hasattr(field_type, "__origin__")
and field_type.__origin__ is Union
):
return convert_union(field_type)
elif is_generic_alias(field_type):
return convert_generic_alias(field_type)
elif issubclass(field_type, Enum):
return {
"type": "string",
"enum": list(field_type.__members__.keys()),
}
else: #: Let the possibility of having a non specified object
return {
"type": "object",
}
except Exception as e:
print("Error", field_type, is_dataclass(field_type), type(field_type))
raise e
def convert_field_type(field_type):
mapping = {
int: {"type": "integer"},
str: {"type": "string"},
bool: {"type": "boolean"},
float: {"type": "number"},
complex: {"type": "string", "format": "complex-number"},
bytes: {"type": "string", "contentEncoding": "base64"},
}
if field_type in mapping:
return mapping[field_type]
else:
return convert_complex_field_type(field_type)
def to_json_schema(datacls):
if callable(getattr(datacls, "json_schema", None)):
return datacls.json_schema()
properties = {}
required_fields = []
for field in fields(datacls):
properties[field.name] = convert_field_type(field.type)
no_default = field.default == MISSING
no_default_factory = field.default_factory == MISSING
required = no_default and no_default_factory
if required:
required_fields.append(field.name)
return {
"type": "object",
"title": datacls.__name__,
"description": datacls.__doc__,
"properties": properties,
"required": required_fields,
}
def from_dict(cls, attrs):
sequences = (
list,
tuple,
set,
frozenset,
)
try:
if is_dataclass(cls):
field_types = {f.name: f.type for f in fields(cls)}
return cls(
**{k: from_dict(field_types[k], v) for k, v in attrs.items()}
)
elif hasattr(cls, "__origin__") and cls.__origin__ is Union:
return attrs
elif hasattr(cls, "__origin__") and cls.__origin__ in sequences:
return cls.__origin__(
[from_dict(cls.__args__[0], v) for v in attrs]
)
elif hasattr(cls, "__name__") and cls.__name__ == "list":
return [from_dict(cls.__args__[0], v) for v in attrs]
elif hasattr(cls, "__name__") and cls.__name__ == "set":
return set([from_dict(cls.__args__[0], v) for v in attrs])
elif issubclass(cls, Enum):
return getattr(cls, attrs)
else:
return attrs
except AttributeError as e:
print(f"Error on {cls}")
raise e
def to_grammar(schema):
return LlamaGrammar.from_json_schema(json.dumps(schema), verbose=False)
def make_tool(datacls):
interface_schema = to_json_schema(datacls)
tool_schema = {
"type": "object",
"properties": {
"name": datacls.__name__,
"description": datacls.__doc__.strip(),
"parameters": interface_schema,
},
}
return tool_schema
def make_tools(providers):
return [to_json_schema(provider) for provider in providers]
def make_helper(provider):
name = f"name: {provider.__name__}"
doc = f"description: {dedent(provider.__doc__.strip())}"
light_schema = indent(
"\n".join(
[
(
f"{f.name} ({getattr(f.type, '__name__', getattr(f.type, '_name', ''))}) "
f"{'(required)' if f.default == MISSING and f.default_factory == MISSING else ''}"
)
for f in fields(provider)
]
),
" ",
)
return "\n".join((name, doc, "inputs:", light_schema))
def make_tool_helper(providers):
return "\n------\n".join(
["Available tools:"]
+ [make_helper(provider) for provider in providers]
)
def make_selection_tool(providers):
providers_registry = {
provider.__name__: provider for provider in providers
}
ProviderName = Enum(
"FunctionName", [provider.__name__ for provider in providers]
)
@dataclass
class DetailedPlan:
query_analysis: str
entities: List[str]
missing_entities: List[str]
relations: List[str]
missing_relations: List[str]
plan: str
use_function: bool
function_name: ProviderName = ""
function_arguments: reduce(lambda a, b: Union[a, b], providers) = ""
def render(self, results):
return dedent(
f"""
# Detailed Plan
1. Analyze user's query
{self.query_analysis}
2. Identify entities
{', '.join(self.entities)}
3. Identify missing entities
{', '.join(self.missing_entities)}
4. Identify relations
{', '.join(self.relations)}
5. Identify missing relations
{', '.join(self.missing_relations)}
6. Write a concise plan
{self.plan}
7. Write the function name to use
{self.function_name}
8. Write the function arguments
-- hidden for brevity purpose --
## Execution trace
Results:
{results}
"""
).strip()
@dataclass
class SelectionTool:
prompt = """
Design a plan to fulfill the user's query.
Here's a framework to follow:
1. Analyze user's query
2. Identify entities
3. Identify missing entities
4. Identify relations
5. Identify missing relations
6. Write a concise plan
7. Write the function name to use
8. Write the function arguments
"""
detailed_plan: DetailedPlan
def execute(self):
trace = []
function_name = self.detailed_plan.function_name.name
trace.append(f"The execution of the function: {function_name}")
#: This first branch is run when only one tool is available
#: In that case, function_arguments contains a populated
#: dataclass
if is_dataclass(self.detailed_plan.function_arguments):
arguments = asdict(self.detailed_plan.function_arguments)
executable_partial = self.detailed_plan.function_arguments
#: This second branch is run when several tools are available
#: In that case, function_arguments contains a mapping
else:
arguments = self.detailed_plan.function_arguments
executable_partial = from_dict(
providers_registry[function_name], arguments
)
formatted_arguments = ",".join(
[f"{k}={v}" for k, v in arguments.items()]
)
trace.append(f"with arguments: {formatted_arguments}")
result = executable_partial()
trace.append(f"gave the result: `{result}`")
return result, " ".join(trace)
schema = to_json_schema(SelectionTool)
grammar = to_grammar(schema)
SelectionTool.schema = schema
SelectionTool.grammar = grammar
SelectionTool.helpers = make_tool_helper(providers)
return SelectionTool
def as_tool(json_schema):
return {
"type": "function",
"function": {
"name": json_schema["title"],
"description": json_schema["description"],
"parameters": json_schema,
},
}