AutoGenLib: Generate Python Code on the Fly With OpenAI API

5月16日 Published inDeveloper Tools

AutoGenLib is a Python library that integrates directly into the language's import system. When you attempt to import a module or function that does not yet exist, the library calls the OpenAI API to generate the necessary code on the fly based on a high-level description.

Dynamic code generation – Import modules and functions that haven't been written yet.

Context-aware – When generating new functions, AutoGenLib examines your existing code to maintain consistency across the project.

Progressive enhancement – Add new features to existing modules seamlessly without breaking current functionality.

No default caching – By default, every import triggers a fresh generation. This results in variety and, occasionally, unexpected architectural approaches.

Full codebase context – The LLM has access to all previously generated modules, ensuring that new code remains compatible with what was created earlier.

Caller code analysis – The library analyzes the specific code block attempting the import. This provides the LLM with specific clues about the intended use case.

Automatic error handling – Runtime errors are passed back to the LLM, which then explains the issue and suggests potential fixes.

Installing AutoGenLib

Install the library via pip:

pip install autogenlib

Or install from the source repository:

git clone https://github.com/cofob/autogenlib.git
cd autogenlib
pip install -e .

Requirements

  • Python 3.12 or higher
  • An active OpenAI API key

Quick Start

First, set your OpenAI API key as an environment variable:

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

The following example demonstrates the library in action. Although the function generate_token does not exist in the codebase, AutoGenLib creates it during the import process:

from autogenlib.tokens import generate_token
token = generate_token(length=32)
print(token)

How It Works

  1. You initialize AutoGenLib with a general description of your project’s goals.
  2. When you import a module or function within the autogenlib namespace:
    • AutoGenLib checks if the requested component already exists.
    • If it is missing, the library analyzes the calling code to establish context.
    • It sends a request to the OpenAI API containing your description and the gathered context.
    • The API generates the Python code.
    • AutoGenLib validates and executes the generated code, making the module or function available for immediate use.

Examples

Generate a TOTP generator

from autogenlib.totp import totp_generator
print(totp_generator("SECRETKEY123"))

Add a verification function to the same module later

from autogenlib.totp import verify_totp
result = verify_totp("SECRETKEY123", "123456")
print(f"Verification result: {result}")

Context awareness in action

from autogenlib.processor import get_highest_score
data = [{"user": "Alice", "score": 95}, {"user": "Bob", "score": 82}]
print(get_highest_score(data))  # The LLM correctly identifies how to extract the maximum score from the dictionary list.

Creating multiple modules

from autogenlib import init
init("Password utilities library")

# Generate an encryption module
from autogenlib.encryption import encrypt_text, decrypt_text
encrypted = encrypt_text("secret message", "password123")
decrypted = decrypt_text(encrypted, "password123")
print(decrypted)

# Generate a hashing module
from autogenlib.hashing import hash_password, verify_password
hashed = hash_password("my_secure_password")
is_valid = verify_password("my_secure_password", hashed)
print(f"Password valid: {is_valid}")

Configuration

Setting the OpenAI API key – Use an environment variable for security:

export OPENAI_API_KEY="your-api-key-here"
# Optional settings:
export OPENAI_API_BASE_URL="https://openrouter.ai/api/v1"
export OPENAI_MODEL="openai/gpt-4.1"

You can also set these variables directly in Python (though this is not recommended for production environments):

import os
os.environ["OPENAI_API_KEY"] = "your-api-key-here"

Caching – By default, AutoGenLib does not cache generated code. Every import triggers a new LLM request, which allows for creative variations but may result in different implementations across different runs.

To enable caching for consistency or to reduce API costs:

from autogenlib import init
init("Data processing library", enable_caching=True)

You can also toggle caching at runtime:

from autogenlib import init, set_caching
init("Data processing library")

# Later in your script:
set_caching(True)  # Enable caching
set_caching(False) # Disable caching

When caching is enabled, generated code is stored locally in ~/.autogenlib_cache.

Limitations

  • Requires an active internet connection to generate new code.
  • Functionality depends entirely on the availability and performance of the OpenAI API.
  • The quality of the generated code is directly tied to the clarity of your instructions.

Advanced Usage

Viewing generated code

You can use standard Python tools to inspect the code that AutoGenLib produces for a specific module:

from autogenlib.totp import totp_generator
import inspect
print(inspect.getsource(totp_generator))

How AutoGenLib builds the OpenAI prompt

To ensure high-quality output, the prompt sent to the LLM includes:

  • Your high-level project description.
  • Any existing code within the module currently being extended.
  • The full context of all modules previously generated during the session.
  • The source code of the file that initiated the import.
  • The specific name and purpose of the function or feature you requested.