Skip to content

What is the best practice to extract JSON from the guidance output? #589

Answered by hudson-ai
aeft asked this question in Q&A
Discussion options

You must be logged in to vote

You can enclose the entire bit that generates JSON in a guidance block :)
I.e.

import guidance
from guidance import block

lm = phi2

# define a re-usable "guidance function" that we can use below
@guidance
def quoted_list(lm, name, n):
    for i in range(n):
        if i > 0:
            lm += ", "
        lm += '"' + gen(name, list_append=True, stop='"') + '"'
    return lm

lm = lm + """What are the most common commands used in the Linux operating system?

Here are the 5 most common commands in JSON format:
"""
with block("my_json"):
  lm += f"""
{{
    "commands": [{quoted_list('commands', 5)}],
    "my_favorite_command": "{gen('favorite_command', stop='"')}"
}}"""

print(lm["my_json"])

Replies: 1 comment 3 replies

Comment options

You must be logged in to vote
3 replies
@aeft
Comment options

@hudson-ai
Comment options

Answer selected by aeft
@hudson-ai
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants