A Python library enabling dynamic code generation using LLMs, iteratively creating executable code from goals, schemas, arguments, and modules.
Project description
ForgeCode
ForgeCode is a Python library that enables dynamic code generation using LLMs. It allows developers to write high-level code by specifying a goal, schema, arguments, and modules, and then iteratively generates executable code that satisfies the given constraints. On subsequent calls, it remembers and reuses the last successful execution.
Installation
pip install forgecode
Or with Poetry:
poetry add forgecode
Quick Start
from forgecode import ForgeCode
# Simple example - summing two numbers
forge = ForgeCode.from_openai(api_key="your-api-key", model="gpt-4o") # Initialize with OpenAI
result = forge.run(
prompt="sum two numbers", # Goal
args={"a": 3, "b": 2}, # Arguments
schema_from={"sum": 5} # Schema for output
)
print(result) # {"sum": 5}
print(forge.get_code()) # View the generated code
Key Features
- Goal-oriented code generation: Specify what you want, not how to do it
- Schema validation: Ensure generated code produces output matching your specifications
- Execution environment: Safely execute generated code
- Caching: Remember successful solutions for faster repeated executions
- Iterative refinement: Automatically fix errors through multiple generation attempts
- Module passing: Provide access to specific modules or functions to the generated code
Real-World Use Cases
API Data Transformation
Fetch and transform data from external APIs with minimal code:
import urllib.request
import json
# API endpoint functions
def fetch_users():
with urllib.request.urlopen("https://jsonplaceholder.typicode.com/users") as response:
return json.loads(response.read().decode())
def fetch_posts():
with urllib.request.urlopen("https://jsonplaceholder.typicode.com/posts") as response:
return json.loads(response.read().decode())
def fetch_comments():
with urllib.request.urlopen("https://jsonplaceholder.typicode.com/comments") as response:
return json.loads(response.read().decode())
# Create a forge with access to these API functions
forge = ForgeCode(
prompt="Get all users along with their posts and each post's comments.",
modules={
"users": fetch_users,
"posts": fetch_posts,
"comments": fetch_comments
},
schema_from=[
{
"id": 1,
"name": "John Doe",
"posts": [
{
"id": 101,
"title": "Post Title",
"body": "Post content",
"comments": [
{
"id": 1001,
"name": "Commenter",
"email": "commenter@example.com",
"body": "Comment content"
}
]
}
]
}
]
)
enriched_data = forge.run()
Natural Language Data Query Interface
Create a dynamic query interface for your APIs:
def query_api(prompt):
"""Convert natural language into API calls"""
forge = ForgeCode(
prompt=prompt,
modules=api_modules, # Dictionary of API functions
schema={}, # Flexible schema
max_retries=5
)
return forge.run()
# Use natural language to query your API
print(query_api("Get all the comments for the first post"))
print(query_api("Get all incomplete todos for user with ID 3"))
Schema Transformation
Easily transform data structures with the builtin schema transformer:
from forgecode.builtins.schema_transform import schema
input_data = [
{"first_name": "Alice", "last_name": "Johnson", "year_of_birth": 1993, "location": "New York"},
{"first_name": "Bob", "last_name": "Smith", "year_of_birth": 1998, "location": "San Francisco"},
]
desired_output_example = [
{'fullname': 'John Doe', 'age': 30, 'location': 'Chicago'},
]
# Transform input data to match the desired output format
transformed_data = schema(input_data).to(desired_output_example)
Content Generation
Create personalized content by combining data sources:
forge = ForgeCode(
prompt="Create personalized email content for each user. Include a summary of their posts and comments.",
modules={
"fetch_users": fetch_users,
"fetch_posts": fetch_posts,
"fetch_comments": fetch_comments,
"summarize_llm": summarize, # Function using LLM to summarize content
},
schema_from=[
{'user_id': 1, 'name': 'John Doe', 'title': 'Email Subject', 'body': 'Email Body'},
],
)
personalized_emails = forge.run()
How It Works
- Define your goal: Provide a clear prompt describing what you want to achieve
- Specify constraints: Add schemas, arguments, or module access as needed
- Execute: ForgeCode generates code, executes it, and validates the output
- Iterative refinement: If execution fails, ForgeCode automatically retries with error context
- Caching: Successful code is stored for reuse in subsequent calls with the same inputs
Important Details
-
Code regeneration: ForgeCode uses a hash-based caching mechanism and regenerates code whenever any of these inputs change:
- Prompt text
- Arguments structure/schema
- Provided modules
- Output schema
-
Module idempotency: Modules provided to ForgeCode must be idempotent (produce the same output when called multiple times with the same input). This is critical because ForgeCode may run these modules multiple times during the iterative code refinement process.
Advanced Configuration
# Set global defaults
ForgeCode.set_default_llm(OpenAILLMClient(api_key="your-api-key"))
ForgeCode.set_default_model("gpt-4o")
ForgeCode.set_default_max_retries(5)
# Custom execution environment
from forgecode.core.execution_environment.execution_environment import ExecutionEnvironment
ForgeCode.set_default_exec_env(my_custom_environment)
# Custom persistence
from forgecode.core.persistence.code_persistence import CodePersistence
ForgeCode.set_default_code_persistence(my_custom_storage)
License
MIT
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file forgecode-0.1.1.tar.gz.
File metadata
- Download URL: forgecode-0.1.1.tar.gz
- Upload date:
- Size: 14.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/2.1.1 CPython/3.13.2 Darwin/23.6.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
94ff58eead6d4037db18e56b7fd1cc48bd8e3ac667365a48adef80cb01837404
|
|
| MD5 |
56cbf783eb65495c842db0f472b8555e
|
|
| BLAKE2b-256 |
6ad0b5b5f08e5c3719e48bf42a9527f2edbf2bc755f8cac85029d5363373e10e
|
File details
Details for the file forgecode-0.1.1-py3-none-any.whl.
File metadata
- Download URL: forgecode-0.1.1-py3-none-any.whl
- Upload date:
- Size: 16.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/2.1.1 CPython/3.13.2 Darwin/23.6.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
a87cbcfeeb3209b2a20b6ce69035b9913401b20888512cec2b8d344b72d6065e
|
|
| MD5 |
81c2b7ea71937b03487890f737a54d15
|
|
| BLAKE2b-256 |
b4f5329d351771be74a5979594c8812cf62d79ad8cff8122bbe8e1814be13958
|