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.3.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.3-cp312-cp312-win_amd64.whl (3.7 MB view details)

Uploaded CPython 3.12Windows x86-64

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

Uploaded CPython 3.12macOS 11.0+ ARM64

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

Uploaded CPython 3.11Windows x86-64

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

Uploaded CPython 3.11macOS 11.0+ ARM64

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

Uploaded CPython 3.10Windows x86-64

liteforge-0.2.3-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.3-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.3.tar.gz.

File metadata

  • Download URL: liteforge-0.2.3.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.3.tar.gz
Algorithm Hash digest
SHA256 478df4b7273b683a98bdfc2de94e18e817975da4b4095a9ed9a3781c71c9cc60
MD5 ac8077feed753761b343347d638aa843
BLAKE2b-256 f4e1199bcf427f76b07bf9284dbc5f90b1d2ab4efcc41a45d46a0a3175594b69

See more details on using hashes here.

Provenance

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

File metadata

  • Download URL: liteforge-0.2.3-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.3-cp312-cp312-win_amd64.whl
Algorithm Hash digest
SHA256 b9834cc31c58551655d8121a5ec7803d399f7b167fa9616439b90da8fe54d95e
MD5 f3f53dfc8c42847110ef73b69e0c57f5
BLAKE2b-256 fa14e82cf184f84353a73609915ed0ffbc9d3004f361efb2ae377e868d41519b

See more details on using hashes here.

Provenance

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

File metadata

File hashes

Hashes for liteforge-0.2.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 1fe255ed7c053c370fbc336e729d04a39d6fc9fb64b47cd4002b865aa0484ad2
MD5 2a4ce26adf3a0b1ef6063778886e165d
BLAKE2b-256 a6faeb6ce5e6acc7a75c2b97bb3eda3a0afca664e2e2090f7d6ce8a0197fecc4

See more details on using hashes here.

Provenance

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

File metadata

File hashes

Hashes for liteforge-0.2.3-cp312-cp312-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 4cd033a0e28781f7cddf516b53aefdd082cf13514f2e6067c33c6dd094242b69
MD5 8fe3ac42c1cc1a9f41d4b5f0cf31a248
BLAKE2b-256 ff2fe454f50a46a6a81ed0ac0602cdbc38b83e53b2e6dd7d5ea26a26daad2358

See more details on using hashes here.

Provenance

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

File metadata

  • Download URL: liteforge-0.2.3-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.3-cp311-cp311-win_amd64.whl
Algorithm Hash digest
SHA256 3a698c544001d59a35fa0715245bae6a280c7a298e832e0b0513d410f062c736
MD5 a91c13de2bc6e17706c58232ee7d26f2
BLAKE2b-256 e62e9877bc39eb6e10ccd1b2fdb51c46fed5931cb3435716aff25977c3c696b3

See more details on using hashes here.

Provenance

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

File metadata

File hashes

Hashes for liteforge-0.2.3-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 d3e45944562b96a85ccdd036d90d91a9ac95fa51b3d21394c9927e77ec830ace
MD5 e965df3f997e528e6bb0e2aaa7a401b2
BLAKE2b-256 f3eed356b8fac5850f53d66d1b904c5f6f1526514d12825d67ddcec5e5236eed

See more details on using hashes here.

Provenance

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

File metadata

File hashes

Hashes for liteforge-0.2.3-cp311-cp311-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 3ab5bf011f5730b458a1e8af8d31cfc8b74e9207596e544958e65881ebcf42e9
MD5 16e963099110f5e95a141499490f0010
BLAKE2b-256 aef2b6638c1383c3f31f3ed77e911b6c9cc4c02692e694d838c6054e39114522

See more details on using hashes here.

Provenance

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

File metadata

  • Download URL: liteforge-0.2.3-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.3-cp310-cp310-win_amd64.whl
Algorithm Hash digest
SHA256 0088313161812162d6ed442a0fdb40fea6bbea8caff212d9d2452cc94caca107
MD5 04aa710982165fac7f154e14eb9e08af
BLAKE2b-256 0a8348fab115ea285a9afba59b6614f0b8e9ee4b1cd35a9dc7aa6ba74be0bdea

See more details on using hashes here.

Provenance

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

File metadata

File hashes

Hashes for liteforge-0.2.3-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 49fe4818ccea844442d3eda9143161cfbbc25702f4569115c4b08dbcf71f5e2c
MD5 0e1b77bde86429248c23997bb24ca5a2
BLAKE2b-256 0183d4745ac9aeccd3c017dbf8fa9d18b53186c6ceea1bf688b54b402298d1d8

See more details on using hashes here.

Provenance

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

File metadata

File hashes

Hashes for liteforge-0.2.3-cp310-cp310-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 14ac7b41f15b9b3fa78ac8d3a30dbecabe71605ffb98e0fadb299d111aa7e0d8
MD5 dea219214ea3080eb89804d29b0b032a
BLAKE2b-256 76789d61fbe506ffcb29744be29608d94323b69870702d8672e7d4d0b5a71e79

See more details on using hashes here.

Provenance

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