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 https://github.com/seanpoyner/liteforge/releases/latest/download/liteforge-py3-none-any.whl

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.2.tar.gz (267.7 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.2-cp312-cp312-win_amd64.whl (3.7 MB view details)

Uploaded CPython 3.12Windows x86-64

liteforge-0.2.2-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.2-cp312-cp312-macosx_11_0_arm64.whl (3.9 MB view details)

Uploaded CPython 3.12macOS 11.0+ ARM64

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

Uploaded CPython 3.11Windows x86-64

liteforge-0.2.2-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.2-cp311-cp311-macosx_11_0_arm64.whl (3.9 MB view details)

Uploaded CPython 3.11macOS 11.0+ ARM64

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

Uploaded CPython 3.10Windows x86-64

liteforge-0.2.2-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.2-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.2.tar.gz.

File metadata

  • Download URL: liteforge-0.2.2.tar.gz
  • Upload date:
  • Size: 267.7 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.2.tar.gz
Algorithm Hash digest
SHA256 6a1c8d51450d449a6e96ac2cbece51427974364379a21fe5d9f3c43f97ba918a
MD5 34a9fd2eb05b3ed5e5ccaff57e7e86d1
BLAKE2b-256 29e1021220ff53d77822db9f596d5194aac536d8c33337df5917bfb1544028d0

See more details on using hashes here.

Provenance

The following attestation bundles were made for liteforge-0.2.2.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.2-cp312-cp312-win_amd64.whl.

File metadata

  • Download URL: liteforge-0.2.2-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.2-cp312-cp312-win_amd64.whl
Algorithm Hash digest
SHA256 20cde37f30d67dd2fb51a66d72db4817dc48efc3fc8b359dac2a5cec3102aff5
MD5 c67906bca804db1fe2f67b8c5f57d9ee
BLAKE2b-256 a03e2a79751f802117bafdd977aa6791056248f3a400c647b47748babb7902ab

See more details on using hashes here.

Provenance

The following attestation bundles were made for liteforge-0.2.2-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.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for liteforge-0.2.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 bf108699d058a223556dafa59888d7701b045f887b6765e8dcbcbe624f596430
MD5 cb5bd068a38a13672bc0b41b9dccd964
BLAKE2b-256 27477d6a8e56432638bec9678784a930769b4aa712143afb0737152a68a11ab6

See more details on using hashes here.

Provenance

The following attestation bundles were made for liteforge-0.2.2-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.2-cp312-cp312-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for liteforge-0.2.2-cp312-cp312-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 b81359dda084f09104a65c71b4438603dde673ca709320af3de12f09186810c2
MD5 5f4ca4fff30f284aafdde74ba36c9cf8
BLAKE2b-256 e47c116a9fe40f1c7b4e7925af6d5969febc11b53b668915450581b23918c324

See more details on using hashes here.

Provenance

The following attestation bundles were made for liteforge-0.2.2-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.2-cp311-cp311-win_amd64.whl.

File metadata

  • Download URL: liteforge-0.2.2-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.2-cp311-cp311-win_amd64.whl
Algorithm Hash digest
SHA256 5a7366b003d757d5580f595db3e73dd1f44c535dfd6b4f0070c4e7a06d39e36e
MD5 273d29b24886abc18e32151dbeb3d7ac
BLAKE2b-256 b4e6f2defe1b7b929f326f1c5d3cc88d25d0cd3d93f8eaf812d84de47ad48baa

See more details on using hashes here.

Provenance

The following attestation bundles were made for liteforge-0.2.2-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.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for liteforge-0.2.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 b7e2f41b1660cf49085c49399e340ed5bd5fd41244c7a99a8b759a178885cba0
MD5 df4d4832aa5047dec5bc6d373589b9e3
BLAKE2b-256 dfd2df10cd8c8eb13ac2bb5e845814efbee01393c9daf26d54eacbb8d99dc898

See more details on using hashes here.

Provenance

The following attestation bundles were made for liteforge-0.2.2-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.2-cp311-cp311-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for liteforge-0.2.2-cp311-cp311-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 494620607bc5f93925ad41e1a12760a4790fff423da21267d336f1791224b4c2
MD5 30b306f6e8d53596a183fbaf9f3dae2e
BLAKE2b-256 42bd614c2ffc9145b3c3af6516a4ca714bf315458af9a5e16eb8b82ee923569f

See more details on using hashes here.

Provenance

The following attestation bundles were made for liteforge-0.2.2-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.2-cp310-cp310-win_amd64.whl.

File metadata

  • Download URL: liteforge-0.2.2-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.2-cp310-cp310-win_amd64.whl
Algorithm Hash digest
SHA256 6af8d00c811a9ec80ac7c15cdb14771f2b258c29559fd8c4fce25918bf54ad34
MD5 19943884461d6ca880882568dffd4df0
BLAKE2b-256 0c00cb4787e2ddfe1cf3e3582500084f45ad4480116409f1caf166893d56c249

See more details on using hashes here.

Provenance

The following attestation bundles were made for liteforge-0.2.2-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.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for liteforge-0.2.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 60c3ecff12a498d6c949906bc5f4dd56323736c9b4589933827fac40cbb19433
MD5 03c239452bcea8f9a9c146a0ab5f1255
BLAKE2b-256 58a99218f05233c3b42b88ced4f6d16e17e0cf970ae29ecf8196ba9b2680e160

See more details on using hashes here.

Provenance

The following attestation bundles were made for liteforge-0.2.2-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.2-cp310-cp310-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for liteforge-0.2.2-cp310-cp310-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 c88a0d56db175e2beeec0ebe13ea1e26470af13ba5d796bfaa506247a4ac7fb5
MD5 67facdbdf5a15781067b1e0aecfe9203
BLAKE2b-256 9e2200dc75809bcc8e6ee342538c545d614da279bb7a21d4ee29b3cb5720fbca

See more details on using hashes here.

Provenance

The following attestation bundles were made for liteforge-0.2.2-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