Skip to content

Instantly share code, notes, and snippets.

@johnidm
Created April 1, 2025 00:46
Show Gist options
  • Save johnidm/193d0883624ea8a6be3627d9bd36f731 to your computer and use it in GitHub Desktop.
Save johnidm/193d0883624ea8a6be3627d9bd36f731 to your computer and use it in GitHub Desktop.
Unlock the Power of LLMs with Structured Output

Precise Prompting

from openai import OpenAI


api_key = "sk-proj-..."
client = OpenAI(api_key=api_key)

prompt = """
What are 5 interesting facts about the moon? 

Output in JSON format without any other text:
{
    "facts": [
    ]
}
"""

response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {
            "role": "user",
            "content": prompt,
        },
    ],
    response_format={"type": "json_object"},
)
output = response.choices[0].message.content
print(output)

>>> Output (a JSON string object)
{
    "facts": [
        "The Moon is about ...",
        "The Moon has no ...",
        "The Moon is slowly ...",
        "The Moon has a ...",
        "A day on the ..."
    ]
}

Leverage Powerful Tools

from openai import OpenAI
from typing import List
from pydantic import BaseModel


api_key = "sk-proj-..."
client = OpenAI(api_key=api_key)

prompt = """
What are 5 interesting facts about the moon? 
"""

class MoonFacts(BaseModel):
    facts: List[str]

response = client.beta.chat.completions.parse(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": prompt}],
    response_format=MoonFacts,
)

print(response.choices[0].message.parsed)

>>> Output (a pydantic model)
facts: [
    "The Moon is about ...",
    "The Moon has no ...",
    "The Moon is slowly ...",
    "The Moon has a ...",
    "A day on the ..."
]
@johnidm
Copy link
Author

johnidm commented Apr 1, 2025

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment