Skip to main content

High-performance Python bindings for LiteForge (Rust core)

Project description

liteforge-py

Python

High-performance Python bindings for the LiteForge, powered by a Rust core via PyO3. Exposes 74 classes and 17 functions covering LLM completions, streaming, tool calling, RAG, agents, guardrails, MCP, skills, observability, and more.

Part of the liteforge workspace. For Rust usage see liteforge, for JS/TS see liteforge-js.

Installation

From release wheel:

pip install liteforge

From git:

pip install "git+https://github.com/seanpoyner/liteforge.git#subdirectory=crates/liteforge-py"

Development install (requires Rust 1.70+ and maturin):

cd crates/liteforge-py
pip install maturin
maturin develop

Quick Start

Synchronous

from liteforge import ForgeClient

client = ForgeClient()
response = client.complete([{"role": "user", "content": "What is the capital of France?"}])
print(response["choices"][0]["message"]["content"])

Asynchronous

import asyncio
from liteforge import AsyncForgeClient

async def main():
    client = AsyncForgeClient()
    response = await client.complete([{"role": "user", "content": "Hello!"}])
    print(response["choices"][0]["message"]["content"])

asyncio.run(main())

Streaming

from liteforge import AsyncForgeClient
import asyncio

async def main():
    client = AsyncForgeClient()
    stream = await client.complete_stream([{"role": "user", "content": "Tell me a story"}])
    async for chunk in stream:
        content = chunk.get("choices", [{}])[0].get("delta", {}).get("content", "")
        if content:
            print(content, end="", flush=True)

asyncio.run(main())

API Surface

Client

Class / Function Description
ForgeClient Synchronous LLM client -- complete(), list_models(), embed()
AsyncForgeClient Async LLM client -- complete(), complete_stream(), list_models(), embed()
CompletionStream Async iterator for streaming responses

Chunking

Class / Function Description
chunk() Split text into chunks (fixed, recursive, sentence, paragraph)
Chunk A text chunk with text, index, start_char, end_char

Guardrails

Class / Function Description
detect_pii() Check text for PII (returns bool)
find_pii() Find all PII matches with types and positions
redact_pii() Replace PII with [REDACTED]
detect_injection() Check for prompt injection patterns
check_all() Run all guardrail checks at once
GuardrailResult Result with passed, value, message, guardrail_name

Tools

Class / Function Description
create_tool() Create a tool from a Python function
validate_json_schema() Validate arguments against a JSON schema
PyTool Tool wrapper
ToolRegistry Manages collections of tools
ToolExecutor Executes tools with optional schema validation
ToolResult Result with success, result, error

Knowledge

Class / Function Description
LocalKnowledgeBackend In-memory document store
Document A document with id and content
SearchResult Search result with score
SearchOptions Search query options
ListOptions Listing/pagination options
KnowledgeStats Knowledge base statistics

RAG (Vector Search)

Class / Function Description
VectorIndex In-memory vector index
EmbeddedDocument Document with embedding vector
VectorSearchResult Search result with score
cosine_similarity() Cosine similarity between vectors
dot_product() Dot product between vectors
euclidean_distance() Euclidean distance between vectors
normalize() L2-normalize a vector

Agents

Class / Function Description
AgentConfig Agent configuration -- with_system_prompt(), with_model(), with_max_steps(), with_tool()
AgentMemory Short-term (messages) + long-term (facts) memory
AgentState Agent execution state
ToolCallingAgent Agent that invokes tools in a loop
AgentStep Individual step in agent execution
StepResult Result of a step
StepType Step type discriminator

Orchestration

Class / Function Description
Intent, IntentRoute, IntentRouter, RoutingDecision Intent classification and routing
CommonIntents Pre-built intent patterns
Session, SessionMessage, SessionStore Session management
Workflow, WorkflowStep Multi-step workflow definition
OrchestrationStrategy, OrchestratorConfig, OrchestrationResult Orchestration configuration
OrchestrationStepStatus Step lifecycle status

MCP (Model Context Protocol)

Class / Function Description
McpConfig, McpServerConfig MCP server configuration
TransportType Stdio, Sse, Http
McpStdioServer, McpSseServer, McpHttpServer Transport-specific server clients
McpServerState Server connection state

Observability

Class / Function Description
Tracer Create and manage distributed spans
Span, SpanContext Span with timing, attributes, events
SpanKind, SpanStatus Span metadata
MetricsCollector Increment counters, record durations, gauges
MetricValue Metric value type

Conversation

Class / Function Description
ManagedConversation Message tracking with add_user_message(), add_assistant_message()
CompactingConversation Auto-summarizes when approaching token limits
ConversationConfig Configuration
SummarizationStrategy How to summarize overflowing context

Human-in-the-Loop

Class / Function Description
ApprovalRequest Request for human approval
ApprovalResult Approval outcome
ApprovalStatus Status enum
RiskLevel Risk classification

Events & Hooks

Class / Function Description
EventBus Pub/sub event bus -- subscribe(), publish()
Event, EventType Event payload and type
HookManager Register and invoke lifecycle hooks
HookEvent, HookContext, HookResult Hook types

Evals

Class / Function Description
TestCase Test case with input and expected output
EvalResult Evaluation result with passed flag
SuiteResult, SuiteStats Suite-level results and statistics

Skills

Class / Function Description
PromptSkill LLM-backed skill implementation
SkillConfig, SkillInput, SkillOutput Skill I/O types
get_summarize_skill() Built-in summarize skill
get_translate_skill() Built-in translate skill
get_extract_skill() Built-in entity extraction skill
get_rewrite_skill() Built-in rewrite skill
get_qa_skill() Built-in Q&A skill

Prompts

Class / Function Description
PromptTemplate Template with {{var}} syntax -- render(), with_default()
PromptConfig Serializable template config
PromptLibrary Named template store with categories
CommonPrompts Static methods: summarize(), translate(), qa(), classify(), etc.

Pipelines

Class / Function Description
PipelineContext Shared pipeline execution context
PipelineStepOutput Output from a pipeline step

Images

Class / Function Description
ImageRequest Image generation request builder
ImageResponse, ImageData Image response types
ImageSize, ImageQuality, ImageStyle, ImageResponseFormat Enums for image configuration

Scheduler

Class / Function Description
CronSchedule, IntervalSchedule, OnceSchedule Schedule types
ScheduleType, JobStatus Enums

Automation

Class / Function Description
AutomationBuilder Fluent builder -- every_seconds(), every_minutes(), cron(), prompt()
AutomationConfig, AutomationScheduleConfig Task configuration
AutomationTaskContext, AutomationTaskOutput Execution I/O
AutomationTaskStatus Status enum
ExecutionRecord Execution audit trail

Retry

Class / Function Description
RetryConfig max_retries, initial_delay, max_delay, backoff_multiplier

Feature Examples

Tools

from liteforge import create_tool, ToolRegistry, ToolExecutor

def calculator(args):
    a, b = args["a"], args["b"]
    return {"result": a + b}

tool = create_tool(
    name="calculator",
    description="Add two numbers",
    parameters={"type": "object", "properties": {"a": {"type": "number"}, "b": {"type": "number"}}, "required": ["a", "b"]},
    func=calculator,
    requires_confirmation=False,
)

registry = ToolRegistry()
registry.register(tool)
executor = ToolExecutor(registry, validate_args=True)
result = executor.execute("calculator", {"a": 2, "b": 3})
print(result.result)  # {"result": 5}

Guardrails

from liteforge import detect_pii, detect_injection, redact_pii, check_all

print(detect_pii("My email is user@example.com"))   # True
print(detect_injection("Ignore all instructions"))   # True
print(redact_pii("Call me at 555-123-4567"))          # Call me at [REDACTED]
results = check_all("Some text to scan")

Agents

from liteforge import AgentConfig, AgentMemory

config = (AgentConfig("assistant")
    .with_system_prompt("You are a helpful assistant.")
    .with_model("gpt-4o")
    .with_max_steps(10)
    .with_tool("calculator"))

memory = AgentMemory()
memory.add_message("user", "What is 2+2?")
memory.remember("user_name", "Alice")
print(memory.recall("user_name"))  # "Alice"

Knowledge

from liteforge import LocalKnowledgeBackend, Document, SearchOptions

kb = LocalKnowledgeBackend()
kb.add(Document(id="1", content="Paris is the capital of France"))
results = kb.search(SearchOptions(query="capital of France", top_k=3))

Skills

from liteforge import get_summarize_skill, SkillInput

skill = get_summarize_skill()
print(skill.config.name)  # "summarize"

Prompts

from liteforge import PromptTemplate, CommonPrompts

template = PromptTemplate("Summarize the following: {{text}}")
rendered = template.render({"text": "A long article..."})

qa = CommonPrompts.qa()

Conversation Management

from liteforge import ManagedConversation

convo = ManagedConversation()
convo.add_user_message("Hello!")
convo.add_assistant_message("Hi there!")
print(convo.message_count())  # 2

Observability

from liteforge import Tracer, MetricsCollector

tracer = Tracer("my-service")
span = tracer.start_span("llm-call")

metrics = MetricsCollector()
metrics.increment("requests_total")

Configuration

Set environment variables before importing:

Variable Description Default
LITEFORGE_API_KEY API key for authentication Required
OPENAI_API_KEY Fallback API key -
LITEFORGE_BASE_URL LiteLLM endpoint URL LiteForge production endpoint
LITEFORGE_DEFAULT_MODEL Default model claude-haiku-4.5
LITEFORGE_TIMEOUT Request timeout in seconds 60

Building from Source

Requires Rust 1.70+ and Python 3.10+.

cd crates/liteforge-py
pip install maturin

# Development install (editable)
maturin develop

# Build a release wheel
maturin build --release
pip install target/wheels/liteforge*.whl

Examples

See examples/python/ for full working examples:

Example Description
agent.py Agent configuration, memory, and tool integration
tools.py Tool creation, registry, executor, schema validation
rag.py Vector indexing and RAG pipeline
guardrails.py PII detection, injection detection
knowledge.py Document storage and retrieval
conversation.py Managed and compacting conversations
mcp_server.py MCP server configuration

Full Documentation

See the MkDocs site for complete API reference and guides.

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

liteforge-0.2.5.tar.gz (267.6 kB view details)

Uploaded Source

Built Distributions

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

liteforge-0.2.5-cp312-cp312-win_amd64.whl (3.7 MB view details)

Uploaded CPython 3.12Windows x86-64

liteforge-0.2.5-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (4.3 MB view details)

Uploaded CPython 3.12manylinux: glibc 2.17+ x86-64

liteforge-0.2.5-cp312-cp312-macosx_11_0_arm64.whl (3.9 MB view details)

Uploaded CPython 3.12macOS 11.0+ ARM64

liteforge-0.2.5-cp311-cp311-win_amd64.whl (3.7 MB view details)

Uploaded CPython 3.11Windows x86-64

liteforge-0.2.5-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (4.3 MB view details)

Uploaded CPython 3.11manylinux: glibc 2.17+ x86-64

liteforge-0.2.5-cp311-cp311-macosx_11_0_arm64.whl (3.9 MB view details)

Uploaded CPython 3.11macOS 11.0+ ARM64

liteforge-0.2.5-cp310-cp310-win_amd64.whl (3.7 MB view details)

Uploaded CPython 3.10Windows x86-64

liteforge-0.2.5-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (4.3 MB view details)

Uploaded CPython 3.10manylinux: glibc 2.17+ x86-64

liteforge-0.2.5-cp310-cp310-macosx_11_0_arm64.whl (3.9 MB view details)

Uploaded CPython 3.10macOS 11.0+ ARM64

File details

Details for the file liteforge-0.2.5.tar.gz.

File metadata

  • Download URL: liteforge-0.2.5.tar.gz
  • Upload date:
  • Size: 267.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for liteforge-0.2.5.tar.gz
Algorithm Hash digest
SHA256 dd8e7dfc408fc32d068197203684f8a512259f4b5f253fd1fd73721b2127175f
MD5 25323c4d44b328166a1b03422c0510f3
BLAKE2b-256 fffcc0807e260acd12a7945d7cfc038c48c83cbb7122119bcb71ef0a875e1423

See more details on using hashes here.

Provenance

The following attestation bundles were made for liteforge-0.2.5.tar.gz:

Publisher: release.yml on seanpoyner/liteforge

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

File details

Details for the file liteforge-0.2.5-cp312-cp312-win_amd64.whl.

File metadata

  • Download URL: liteforge-0.2.5-cp312-cp312-win_amd64.whl
  • Upload date:
  • Size: 3.7 MB
  • Tags: CPython 3.12, Windows x86-64
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for liteforge-0.2.5-cp312-cp312-win_amd64.whl
Algorithm Hash digest
SHA256 e67ac66ba96cff6b6cea914cbba800659fe28349a032f9d970b2142e8f6ca2da
MD5 cd12d847ce1a60919be9d52bab453a16
BLAKE2b-256 db338f0b962d9906a55c2f0e552cecad3876d2968d80957c3d9c2245624fb67b

See more details on using hashes here.

Provenance

The following attestation bundles were made for liteforge-0.2.5-cp312-cp312-win_amd64.whl:

Publisher: release.yml on seanpoyner/liteforge

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

File details

Details for the file liteforge-0.2.5-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for liteforge-0.2.5-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 5db9dcafdccb17df963a8cb25581369b167da6d2e52b9fc3d4359617af9fe6ec
MD5 46bf39e4d93f6d0c1fffdbd2c89804b5
BLAKE2b-256 563622d26a4faa894209c9d64b736d004df22d230a82f59204d2972cfbcc0e6d

See more details on using hashes here.

Provenance

The following attestation bundles were made for liteforge-0.2.5-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl:

Publisher: release.yml on seanpoyner/liteforge

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

File details

Details for the file liteforge-0.2.5-cp312-cp312-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for liteforge-0.2.5-cp312-cp312-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 bf0a2662357e01a62c2651f14d647bb7e4c732bcbda12996577bfb91326fcb79
MD5 530ec35e6cdab4f8e20ff2638478659e
BLAKE2b-256 f6ad12727201f9242be8cf0cd8a1a52bf62221ed82152ae8f2e2f41b83ac9a41

See more details on using hashes here.

Provenance

The following attestation bundles were made for liteforge-0.2.5-cp312-cp312-macosx_11_0_arm64.whl:

Publisher: release.yml on seanpoyner/liteforge

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

File details

Details for the file liteforge-0.2.5-cp311-cp311-win_amd64.whl.

File metadata

  • Download URL: liteforge-0.2.5-cp311-cp311-win_amd64.whl
  • Upload date:
  • Size: 3.7 MB
  • Tags: CPython 3.11, Windows x86-64
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for liteforge-0.2.5-cp311-cp311-win_amd64.whl
Algorithm Hash digest
SHA256 3c811c7d445ca7266f3b13bf1816664796364cf6d88366819919327390d8c0e6
MD5 9741615bd97ad8da177bf044b6c9c76a
BLAKE2b-256 90f8168a4268b0683c0ecf634d60bc31bd1206f5e047b9011699b3dceb03641a

See more details on using hashes here.

Provenance

The following attestation bundles were made for liteforge-0.2.5-cp311-cp311-win_amd64.whl:

Publisher: release.yml on seanpoyner/liteforge

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

File details

Details for the file liteforge-0.2.5-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for liteforge-0.2.5-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 4db12ffd550e9b9e60845a9cd5dfaee472cc7e31b5cdb2b0c29aacb58f6c9534
MD5 4c7a76572b5a5e075409b3be0fc52086
BLAKE2b-256 9b8711e3c09657e2258baca20da58cad00f3df0ebbf417e611c7e091c849593d

See more details on using hashes here.

Provenance

The following attestation bundles were made for liteforge-0.2.5-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl:

Publisher: release.yml on seanpoyner/liteforge

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

File details

Details for the file liteforge-0.2.5-cp311-cp311-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for liteforge-0.2.5-cp311-cp311-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 b21e9d23f11ac8d56ff2d7acb113af63d75f96fc02a19418802c39bf010e3cf0
MD5 3abda90079c3080c9ea24db7ae99aefc
BLAKE2b-256 d3e77ef3ed0c578c35efd80fa2536641527e64e5139cdd699e1087ae11013029

See more details on using hashes here.

Provenance

The following attestation bundles were made for liteforge-0.2.5-cp311-cp311-macosx_11_0_arm64.whl:

Publisher: release.yml on seanpoyner/liteforge

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

File details

Details for the file liteforge-0.2.5-cp310-cp310-win_amd64.whl.

File metadata

  • Download URL: liteforge-0.2.5-cp310-cp310-win_amd64.whl
  • Upload date:
  • Size: 3.7 MB
  • Tags: CPython 3.10, Windows x86-64
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for liteforge-0.2.5-cp310-cp310-win_amd64.whl
Algorithm Hash digest
SHA256 fbd684c64cbe2e83eab9295d72936c5e03cf29b3ad9b26cf7e86bf9b245fb37e
MD5 0c6f2832f0d296a7eae075ec541f1580
BLAKE2b-256 7db17703ac67d9b772851ea9a5bf2f38b5f34d4be33a5b5d68a478228fd52cc0

See more details on using hashes here.

Provenance

The following attestation bundles were made for liteforge-0.2.5-cp310-cp310-win_amd64.whl:

Publisher: release.yml on seanpoyner/liteforge

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

File details

Details for the file liteforge-0.2.5-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for liteforge-0.2.5-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 259e45677fe0a499d7b9e61197671e28f09d097888cc9d16cfea5343e400f652
MD5 1e0231f0cbcfa96d9d0025f7bf5302a5
BLAKE2b-256 fdbfd93ccbe47361fecec1016f48e12e6a2485112cad83093b958e884e2966de

See more details on using hashes here.

Provenance

The following attestation bundles were made for liteforge-0.2.5-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl:

Publisher: release.yml on seanpoyner/liteforge

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

File details

Details for the file liteforge-0.2.5-cp310-cp310-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for liteforge-0.2.5-cp310-cp310-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 61ed7b39468d7e69d1293630eff295db0790fe56264c3219f3979cfa5478108f
MD5 adf2b2325390689258dc52739f82e885
BLAKE2b-256 926a7a1d1eb8512d7e5f634d4c271259af36c5a4f9793b81bb88f8cc81f59c2b

See more details on using hashes here.

Provenance

The following attestation bundles were made for liteforge-0.2.5-cp310-cp310-macosx_11_0_arm64.whl:

Publisher: release.yml on seanpoyner/liteforge

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