Skip to main content

struct-gpt

codecov PyPI

Get structured output from LLM's.

from struct_gpt import OpenAiBase
from pydantic import Field


class SentimentSchema(OpenAiBase):
    """
    Determine the sentiment of the given text:

    {content}
    """
    # 👆this becomes the prompt

    sentiment: str = Field(description="Either -1, 0, or 1.")


result = SentimentSchema.from_openai(content="I love pizza!").json()
                                     # 👆this ends up in the prompt
print(result)

outputs:

{
  "sentiment": "1"
}

Features

  • Easy creation of custom models using the OpenAI API
  • Integration with Pydantic for model validation and serialization
  • Flexible configuration with retries and temperature settings

Installation

pip install struct-gpt

Usage

  • Template variables in the class' docstring are replaced with the keyword arguments passed to from_openai
  • Classes can reference one another
  • You can use the OpenAiMixin to add functionality to existing Pydantic classes
  • Requires openai>=1.0. By default from_openai builds an openai.OpenAI() client, which reads OPENAI_API_KEY from the environment. Pass client= to use your own (e.g. AzureOpenAI or a custom base_url)
  • JSON mode (response_format={"type": "json_object"}) is on by default. Pass json_mode=False for models that don't support it
  • The default model is gpt-4o-mini; pass model= to change it
from struct_gpt import OpenAiBase, OpenAiMixin
from pydantic import Field, BaseModel
from typing import Mapping


class SentimentSchema(OpenAiBase):
    sentiment: str = Field(description="Either -1, 0, or 1.")


class SentimentAnalysis(BaseModel, OpenAiMixin):
    """
    Determine the sentiment of each word in the following: {text}

    Also determine the overall sentiment of the text and who the narrator is.
    """

    words_to_sentiment: Mapping[str, SentimentSchema]
    overall_sentiment: SentimentSchema
    narrator: str


print(
    SentimentAnalysis.from_openai(
        text="As president, I loved the beautiful scenery, but the long hike was exhausting."
    ).json(indent=2)
)
See Output
{
  "words_to_sentiment": {
    "As": {
      "sentiment": "0"
    },
    "president,": {
      "sentiment": "1"
    },
    "I": {
      "sentiment": "0"
    },
    "loved": {
      "sentiment": "1"
    },
    "the": {
      "sentiment": "0"
    },
    "beautiful": {
      "sentiment": "1"
    },
    "scenery,": {
      "sentiment": "1"
    },
    "but": {
      "sentiment": "-1"
    },
    "long": {
      "sentiment": "-1"
    },
    "hike": {
      "sentiment": "-1"
    },
    "was": {
      "sentiment": "0"
    },
    "exhausting.": {
      "sentiment": "-1"
    }
  },
  "overall_sentiment": {
    "sentiment": "0"
  },
  "narrator": "president"
}

Improving reliability with examples

from_openai can accept a list of examples to guide the model and improve its accuracy.

Each example is a dictionary containing an input and output key.

output should be an instance of the model, a dictionary, or its json string representation,.

from struct_gpt import OpenAiBase
from pydantic import Field


class SentimentSchema(OpenAiBase):
    """
    Determine the sentiment of the given text:

    {content}
    """

    sentiment: str = Field(description="Either -1, 0, or 1.")


examples = [
    {
        "input": "I love the beach!",
        "output": {"sentiment": "1"},
    },
    {
        "input": "don't touch that",
        "output": '{"sentiment": "-1"}',
    },
    {
        "input": "this library is neat!",
        "output": SentimentSchema(sentiment="1"),
    },
]

print(SentimentSchema.from_openai(content="I love pizza!", examples=examples).json())

outputs:

{
  "sentiment": "1"
}

Metadata

Release files for struct-gpt 3.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for struct-gpt 3.0.0
File Size Uploaded Provenance
struct_gpt-3.0.0.tar.gz 6.8 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for struct-gpt 3.0.0
File Interpreter ABI Platform
struct_gpt-3.0.0-py3-none-any.whl Python 3 none any Details

Total release size: 13.3 kB

Release files / struct_gpt-3.0.0.tar.gz

Download URL struct_gpt-3.0.0.tar.gz
Size 6.8 kB
Tags Source
SHA-256 checksum
How to use checksums
d2aa13b8180b3c503ba439702fe729ea1f4678f2d7f42a6e2154d3c4dea10deb
BLAKE2b-256 checksum
How to use checksums
c2f7e03780665749fa22f717b4dc3f2eaaa7a9e99003a83cfdddf6cb5a59db38
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.0 {"installer":{"name":"uv","version":"0.13.0","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / struct_gpt-3.0.0-py3-none-any.whl

Download URL struct_gpt-3.0.0-py3-none-any.whl
Size 6.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
58ec473f9ccbd0d1d5b752680156cbfc48845e1279cadbec5cbedb1dc64e61a0
BLAKE2b-256 checksum
How to use checksums
34ba25024ff92bb719a59591f83c430dd136ed557ed833d1187ea3b4af0841c6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.0 {"installer":{"name":"uv","version":"0.13.0","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for struct-gpt 3.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page