Skip to main content

OpenAI integration for APE (AI Programmatic Execution)

Project description

ape-openai

OpenAI integration for APE (AI Programmatic Execution).

What is ape-openai?

ape-openai bridges APE's deterministic validation layer with OpenAI's function calling API. It prevents hallucinations in function parameters by enforcing strict type checking and constraints before execution.

Why ape-openai?

OpenAI's function calling is powerful but can be unreliable:

  • Function parameters can be incorrectly formatted
  • Type mismatches cause runtime errors
  • Missing required fields break execution
  • No validation before calling your code

ape-openai solves this by adding APE as a validation layer:

OpenAI → JSON parameters → APE validation → Deterministic execution ✓

Installation

# Core package (schema conversion + execution)
pip install ape-openai

# With OpenAI SDK (for code generation)
pip install ape-openai[openai]

# Development dependencies
pip install ape-openai[dev]

Prerequisites:

  • Python >= 3.11
  • ape-lang >= 0.2.0

Test Coverage

All tests passing

  • Total tests: 49
  • Last verified via pytest discovery

See ../ape/docs/APE_TESTING_GUARANTEES.md for details on what these tests guarantee.

The test suite covers:

  • Schema conversion (APE → OpenAI)
  • Executor (OpenAI → APE runtime)
  • Utils (error formatting, validation)
  • End-to-end integration
  • Generator (NL → APE code)

To verify test counts:

pytest packages/ape-openai/tests --collect-only -q

Quick Start

from openai import OpenAI
from ape_openai import ApeOpenAIFunction

# 1. Create Ape task file
# calculator.ape:
# task add:
#     inputs: a: Integer, b: Integer
#     outputs: sum: Integer
#     constraints: a > 0, b > 0
#     steps: sum = a + b

# 2. Load as OpenAI function
func = ApeOpenAIFunction.from_ape_file("calculator.ape", "add")

# 3. Get OpenAI function schema
function_schema = func.to_openai_function()

# 4. Use with OpenAI
client = OpenAI()
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Add 5 and 3"}],
    functions=[function_schema],
    function_call="auto"
)

# 5. Execute with APE validation
if response.choices[0].message.function_call:
    func_call = response.choices[0].message.function_call
    result = func.execute(func_call.arguments)
    print(f"Result: {result}")  # 8

API Reference

Schema Conversion

ape_task_to_openai_schema(task: ApeTask) -> dict

Converts APE task to OpenAI function schema.

from ape_openai import ape_task_to_openai_schema, ApeTask

task = ApeTask(
    name="calculate_tax",
    inputs={"amount": "float", "rate": "float"},
    output="float",
    description="Calculate tax amount"
)

schema = ape_task_to_openai_schema(task)
# {
#     "name": "calculate_tax",
#     "description": "Calculate tax amount",
#     "parameters": {
#         "type": "object",
#         "properties": {
#             "amount": {"type": "number"},
#             "rate": {"type": "number"}
#         },
#         "required": ["amount", "rate"]
#     }
# }

Execution

execute_openai_call(module, function_name, arguments) -> Any

Execute OpenAI function call with APE validation.

from ape import compile
from ape_openai import execute_openai_call

module = compile("calculator.ape")
result = execute_openai_call(module, "add", '{"a": 5, "b": 3}')

High-Level Wrapper

ApeOpenAIFunction

Complete integration wrapper.

func = ApeOpenAIFunction.from_ape_file("calc.ape", "multiply")

# Get schema
schema = func.to_openai_function()

# Execute
result = func.execute({"a": 4, "b": 7})

Features

  • Schema conversion: APE → OpenAI function format
  • Type validation: Strict parameter checking
  • Error handling: Clear error messages
  • Code generation: Natural language → APE (experimental)
  • Full type support: String, Integer, Float, Boolean, List, Dict

Type Mapping

Ape Type OpenAI Type
String string
Integer integer
Float number
Boolean boolean
List array
Dict object

Advanced Usage

Code Generation

Generate APE code from natural language:

from ape_openai import generate_ape_from_nl

code = generate_ape_from_nl(
    "Create a function that calculates compound interest",
    model="gpt-4o"
)
print(code)

Error Handling

from ape_openai import ApeOpenAIFunction
from ape import ApeExecutionError

func = ApeOpenAIFunction.from_ape_file("calc.ape", "divide")

try:
    result = func.execute({"a": 10, "b": 0})
except ApeExecutionError as e:
    print(f"Execution failed: {e}")

Examples

See the examples/ directory for complete examples:

  • Basic function calling
  • Multi-function conversations
  • Error handling patterns
  • Code generation workflows

Development

# Install dev dependencies
pip install -e ".[dev]"

# Run tests
pytest

# Format code
black .

# Type checking
mypy src/

License

MIT License - see LICENSE file for details.

Links

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

ape_openai-1.0.5.tar.gz (16.0 kB view details)

Uploaded Source

Built Distribution

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

ape_openai-1.0.5-py3-none-any.whl (10.7 kB view details)

Uploaded Python 3

File details

Details for the file ape_openai-1.0.5.tar.gz.

File metadata

  • Download URL: ape_openai-1.0.5.tar.gz
  • Upload date:
  • Size: 16.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.9

File hashes

Hashes for ape_openai-1.0.5.tar.gz
Algorithm Hash digest
SHA256 38b5878f3fe4ffb8894846186739f33a7d7284f78c38be667e965b2c372b1244
MD5 181d00c90b688fe7a0f4a00117f05a86
BLAKE2b-256 b8297d09d0c83de21b90892eeccb8ce017986dd2d5bbeb5f4cd6b42dc6737b0b

See more details on using hashes here.

File details

Details for the file ape_openai-1.0.5-py3-none-any.whl.

File metadata

  • Download URL: ape_openai-1.0.5-py3-none-any.whl
  • Upload date:
  • Size: 10.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.9

File hashes

Hashes for ape_openai-1.0.5-py3-none-any.whl
Algorithm Hash digest
SHA256 6ecf14f25bfd52874f73c447210b9ef6e54f9385b8f1193d6ae19c4e905d43d9
MD5 c7f615c8d9fee9624e63b7aee624b80f
BLAKE2b-256 9ff58bdfa1ae8a84bcc4ae0cfdbeb11aca94b7096e144efa901e9cbee0678b77

See more details on using hashes here.

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