Can guidance generate list of jsons? #402
-
I want to generate the following format, that is, list of jsons: |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Hi, I have been trying to achieve something similar. Basically I think it would be nice to have a direct way to parse JSONs using a Guidance-grammar. I tried to write a very basic version to match my needs (i.e. short of an implementation of the JSON schema, which would certainly be the best way to do it). I failed. Using GPT3.5, I went the ugly way to simply ask the model for a string and to load it with json.loads(). As the results are most of the time well-formed JSON strings, this works for me, although I would, of course, prefer to really guide the model (and not just hope that it spits out a string that json.loads can process). |
Beta Was this translation helpful? Give feedback.
-
I will push something general for json at some point, but here is a version for your simple use case: from guidance import select, zero_or_more, any_char, one_or_more, commit_point, regex
@guidance(stateless=True)
def simple_json(lm):
lm += ('{"name": ' + one_or_more(any_char()) + commit_point('"') +
', "age": ' + regex('\d+') + commit_point('}') + ',\n')
return lm
@guidance(stateless=True)
def simple_list_of_jsons(lm):
lm += '[\n' + one_or_more(simple_json()) + ']'
return lm The mistral + 'Please generate a list of 5 jsons with name and age:\n' + simple_list_of_jsons()
mistral + 'Please generate a list of 3 jsons with name and age:\n' + simple_list_of_jsons()
|
Beta Was this translation helpful? Give feedback.
I will push something general for json at some point, but here is a version for your simple use case:
The
commit_point
s are just ways of stoppingone_or_more(any_char())
once we hit"
, or\d+
ondce we hit'}'
.Notice that this does not constrain the LM, i.e. it can generate jsons forever…