Skip to main content

Convert natural language prompts to structured JSON using OpenAI

Project description

prompt-to-json

PyPI version Build Status Coverage Status License Python Versions

Convert natural language prompts to structured JSON using OpenAI's GPT models.

Installation

pip install prompt-to-json

Quick Start

from prompt_to_json import PromptToJSON

# Initialize with API key
converter = PromptToJSON(api_key="sk-...")  # or set OPENAI_API_KEY env var

# Convert natural language to structured JSON
prompt = "Summarize this article in 3 bullet points professionally"
result = converter.convert(prompt)

print(result)
# Output:
# {
#   "task": "summarize",
#   "input_data": {"type": "article", "source": "provided"},
#   "output_format": {"format": "bullet_points", "count": 3},
#   "constraints": {"max_points": 3},
#   "config": {"tone": "professional"}
# }

Features

  • 🎯 Simple API - Just one method: convert()
  • 🧠 Intelligent Parsing - Uses GPT to understand intent and structure
  • 📦 Structured Output - Returns clean JSON ready for downstream processing
  • 🔄 Batch Processing - Convert multiple prompts at once
  • Production Ready - Error handling and fallbacks included

Usage

Basic Usage

from prompt_to_json import PromptToJSON

converter = PromptToJSON()

# Simple prompt
result = converter.convert("Extract key points from this text")

Batch Processing

prompts = [
    "Summarize this article",
    "Translate to Spanish",
    "Extract data points"
]

results = converter.convert_batch(prompts)

Using Different Models

# Use GPT-4.1 for better accuracy (default)
converter = PromptToJSON()

# Use GPT-3.5 Turbo for speed and cost efficiency
converter = PromptToJSON(model="gpt-3.5-turbo")

Output Structure

The converter extracts and structures:

  • task - Main action/verb (summarize, extract, generate, etc.)
  • input_data - Data or content to process
  • output_format - Expected format and structure
  • constraints - Limitations (length, count, style, etc.)
  • context - Background information or purpose
  • config - Settings like tone, approach, style

Examples

# Content Generation
prompt = "Write a marketing email for our new AI product"
# Returns: {"task": "generate", "input_data": {"type": "marketing_email"}, ...}

# Data Extraction
prompt = "Extract all dates and amounts from these invoices"
# Returns: {"task": "extract", "input_data": {"type": "invoices"}, ...}

# Analysis
prompt = "Analyze customer feedback and identify top complaints"
# Returns: {"task": "analyze", "input_data": {"type": "customer_feedback"}, ...}

Advanced Usage

Error Handling, Rate Limits, and Retries

from prompt_to_json import PromptToJSON
from openai import OpenAI, OpenAIError
from time import sleep

converter = PromptToJSON()

for attempt in range(3):
    try:
        result = converter.convert("Summarize this article")
        break
    except OpenAIError as e:
        # basic exponential backoff on failure or rate limit
        sleep(2 ** attempt)
else:
    raise RuntimeError("Request failed after retries")

print(result)

Timeout Configuration

converter = PromptToJSON()
# underlying OpenAI client supports a timeout parameter
converter.client = OpenAI(api_key=converter.api_key, timeout=30)

JSON Schema and Validation

from prompt_to_json import PromptJSON

result = converter.convert("Extract key facts")
PromptJSON.model_validate(result)  # raises if the shape is wrong
schema = PromptJSON.to_schema()

Custom Models and Prompts

# Use a different model and a deterministic temperature
converter = PromptToJSON(model="gpt-4o-mini")

# Modify system instructions or add few-shot examples
custom = PromptToJSON(model="gpt-4o-mini")
custom_prompt = "You are a precise JSON formatter."
response = custom.client.responses.create(
    model=custom.model,
    instructions=custom_prompt,
    input="Translate to French",
    temperature=0,
)

Requirements

  • Python 3.6+
  • OpenAI API key

Environment Setup

export OPENAI_API_KEY="sk-your-api-key-here"

License

MIT

Contributing

Contributions welcome! See CONTRIBUTING.md for details.

Changelog

See CHANGELOG.md for release history.

Support

For issues or questions, please open an issue on GitHub.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

prompt_to_json-0.1.1.tar.gz (6.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

prompt_to_json-0.1.1-py3-none-any.whl (6.1 kB view details)

Uploaded Python 3

File details

Details for the file prompt_to_json-0.1.1.tar.gz.

File metadata

  • Download URL: prompt_to_json-0.1.1.tar.gz
  • Upload date:
  • Size: 6.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for prompt_to_json-0.1.1.tar.gz
Algorithm Hash digest
SHA256 1006ea297b6f3a38125964ef16b1e0ab9061f2163db333cecdd48ef343fbb35b
MD5 cfdfa816bcd1c35047a138bd8b9bb761
BLAKE2b-256 8b5c71cbadb79f4a2152fcfaad01c83c4daff90f27e9f89968aec07a3f0120d6

See more details on using hashes here.

Provenance

The following attestation bundles were made for prompt_to_json-0.1.1.tar.gz:

Publisher: ci.yml on OpenSoucrce/prompt-to-json

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file prompt_to_json-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: prompt_to_json-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 6.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for prompt_to_json-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 9158f70395b6ca4bc79981c6d2204e86f96c219f4c2617f88cdfd50306148795
MD5 b843d9e57efac49af693c3514dc9b986
BLAKE2b-256 a81f4a3ffbad31333709ed3cb971c2f9d8224b27922e967820103ccea9e5bdac

See more details on using hashes here.

Provenance

The following attestation bundles were made for prompt_to_json-0.1.1-py3-none-any.whl:

Publisher: ci.yml on OpenSoucrce/prompt-to-json

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page