Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file added examples/__init__.py
Empty file.
424 changes: 424 additions & 0 deletions examples/hmmv/end_to_end.py

Large diffs are not rendered by default.

64 changes: 30 additions & 34 deletions examples/simple_example/example.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,63 +12,61 @@
import asyncio
from dataclasses import dataclass
from manifold import (
Context, Spec, SpecResult, Agent, AgentOutput,
OrchestratorBuilder, create_context
Context,
Spec,
SpecResult,
Agent,
AgentOutput,
OrchestratorBuilder,
create_context,
)


# ─── SPECS ───────────────────────────────────────────────────────────────


class HasInputData(Spec):
"""Pre-condition: input_data must exist."""

@property
def rule_id(self) -> str:
return "has_input_data"

@property
def tags(self):
return ("precondition", "data")

def evaluate(self, context: Context, candidate=None) -> SpecResult:
if context.has_data("input_data"):
return SpecResult.ok(
self.rule_id,
"Input data is present",
tags=self.tags
)
return SpecResult.ok(self.rule_id, "Input data is present", tags=self.tags)
return SpecResult.fail(
self.rule_id,
"Missing input_data",
suggested_fix="Provide 'input_data' in initial context",
tags=self.tags
tags=self.tags,
)


class OutputNotEmpty(Spec):
"""Post-condition: output must not be empty."""

@property
def rule_id(self) -> str:
return "output_not_empty"

@property
def tags(self):
return ("postcondition", "output")

def evaluate(self, context: Context, candidate=None) -> SpecResult:
if candidate and len(str(candidate)) > 0:
return SpecResult.ok(
self.rule_id,
f"Output produced: {len(str(candidate))} chars",
tags=self.tags
self.rule_id, f"Output produced: {len(str(candidate))} chars", tags=self.tags
)
return SpecResult.fail(
self.rule_id,
"Output is empty or None",
suggested_fix="Ensure agent produces non-empty output",
tags=self.tags
tags=self.tags,
)


Expand All @@ -77,23 +75,23 @@ def evaluate(self, context: Context, candidate=None) -> SpecResult:

class DataProcessorAgent(Agent):
"""Simple agent that processes input data."""

@property
def agent_id(self) -> str:
return "data_processor"

async def execute(self, context: Context, input_data=None) -> AgentOutput:
"""Process the input data."""
# Get input from context
raw_data = context.get_data("input_data", "")

# Simple processing: uppercase and add suffix
processed = f"{raw_data.upper()} - PROCESSED"

return AgentOutput(
output=processed,
delta={"processed_data": processed},
cost=0.001 # Minimal cost for demo
cost=0.001, # Minimal cost for demo
)


Expand All @@ -102,12 +100,12 @@ async def execute(self, context: Context, input_data=None) -> AgentOutput:

async def main():
"""Run the example workflow."""

print("=" * 60)
print("Manifold Simple Example - Data Processing Workflow")
print("=" * 60)
print()

# Build orchestrator
print("Building orchestrator...")
orchestrator = (
Expand All @@ -120,13 +118,11 @@ async def main():
)
print("[OK] Orchestrator built")
print()

# Run workflow
print("Running workflow...")
result = await orchestrator.run(
initial_data={"input_data": "hello world"}
)

result = await orchestrator.run(initial_data={"input_data": "hello world"})

print()
print("=" * 60)
print("RESULTS")
Expand All @@ -137,13 +133,13 @@ async def main():
print(f"Total Retries: {result.total_retries}")
print(f"Duration: {result.duration_ms}ms")
print()

# Show final data
print("Final Context Data:")
for key, value in result.final_context.data.items():
print(f" {key}: {value}")
print()

# Show trace
print("Execution Trace:")
for i, entry in enumerate(result.final_context.trace, 1):
Expand All @@ -155,7 +151,7 @@ async def main():
if entry.error:
print(f" - Error: {entry.error}")
print()

print("=" * 60)
print("Example completed successfully!")
print("=" * 60)
Expand Down
1 change: 1 addition & 0 deletions examples/sprite_generation/example.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ async def main():
# This assumes sprite_pipeline is installed
try:
from sprite_pipeline.providers.fast_hook_provider import FastHookProvider

hook_provider = FastHookProvider()
print("[OK] FastHookProvider initialized")
except ImportError:
Expand Down
64 changes: 25 additions & 39 deletions examples/sprite_generation/harness/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,9 @@ def agent_id(self) -> str:
def description(self) -> str:
return "Generates sprite images using GPT image models"

async def execute(self, context: Context, input_data: dict[str, Any] | None = None) -> AgentOutput:
async def execute(
self, context: Context, input_data: dict[str, Any] | None = None
) -> AgentOutput:
"""
Generate sprite image.

Expand All @@ -54,17 +56,11 @@ async def execute(self, context: Context, input_data: dict[str, Any] | None = No
gen_size = context.get_data("gen_size", "1024x1024")

if not prompt:
return AgentOutput(
output=None,
delta={},
cost=0.0
)
return AgentOutput(output=None, delta={}, cost=0.0)

# Create image generation request
request = HookRequest(
task_type=HookTaskType.GENERATE_IMAGE,
prompt_text=prompt,
gen_size=gen_size
task_type=HookTaskType.GENERATE_IMAGE, prompt_text=prompt, gen_size=gen_size
)

# Call hook provider
Expand All @@ -74,34 +70,30 @@ async def execute(self, context: Context, input_data: dict[str, Any] | None = No
artifact = response.artifacts[0]

return AgentOutput(
output={
"width": artifact.width,
"height": artifact.height,
"status": "ok"
},
output={"width": artifact.width, "height": artifact.height, "status": "ok"},
delta={
"generated_image": {
"width": artifact.width,
"height": artifact.height,
"size_bytes": len(artifact.png_bytes)
"size_bytes": len(artifact.png_bytes),
},
"image_bytes": artifact.png_bytes
"image_bytes": artifact.png_bytes,
},
cost=0.04 # Approximate GPT image generation cost
cost=0.04, # Approximate GPT image generation cost
)

elif response.status == "content_policy":
return AgentOutput(
output={"status": "content_policy", "error": response.error_message},
delta={"error": response.error_message},
cost=0.0
cost=0.0,
)

else:
return AgentOutput(
output={"status": "error", "error": response.error_message},
delta={"error": response.error_message},
cost=0.0
cost=0.0,
)


Expand All @@ -123,7 +115,9 @@ def agent_id(self) -> str:
def description(self) -> str:
return "Builds optimized prompts for sprite generation"

async def execute(self, context: Context, input_data: dict[str, Any] | None = None) -> AgentOutput:
async def execute(
self, context: Context, input_data: dict[str, Any] | None = None
) -> AgentOutput:
"""
Build sprite generation prompt.

Expand All @@ -140,16 +134,10 @@ async def execute(self, context: Context, input_data: dict[str, Any] | None = No
global_style = context.get_data("global_style", "Pixel Art")

if not spec:
return AgentOutput(
output="",
delta={},
cost=0.0
)
return AgentOutput(output="", delta={}, cost=0.0)

request = HookRequest(
task_type=HookTaskType.BUILD_PROMPT,
spec=spec,
global_style=global_style
task_type=HookTaskType.BUILD_PROMPT, spec=spec, global_style=global_style
)

response = await self._provider.run(request)
Expand All @@ -158,13 +146,11 @@ async def execute(self, context: Context, input_data: dict[str, Any] | None = No
return AgentOutput(
output=response.text_output,
delta={"prompt_text": response.text_output},
cost=0.0 # Prompt building is lightweight
cost=0.0, # Prompt building is lightweight
)

return AgentOutput(
output="",
delta={"error": response.error_message or "Prompt build failed"},
cost=0.0
output="", delta={"error": response.error_message or "Prompt build failed"}, cost=0.0
)


Expand All @@ -186,7 +172,9 @@ def agent_id(self) -> str:
def description(self) -> str:
return "Builds grid-specific generation briefs"

async def execute(self, context: Context, input_data: dict[str, Any] | None = None) -> AgentOutput:
async def execute(
self, context: Context, input_data: dict[str, Any] | None = None
) -> AgentOutput:
"""
Build generation brief with grid constraints.

Expand All @@ -208,22 +196,20 @@ async def execute(self, context: Context, input_data: dict[str, Any] | None = No
task_type=HookTaskType.BUILD_BRIEF,
spec=spec,
global_style=global_style,
prompt_text=prompt_text
prompt_text=prompt_text,
)

response = await self._provider.run(request)

if response.status == "ok" and response.text_output:
return AgentOutput(
output=response.text_output,
delta={"brief_text": response.text_output},
cost=0.0
output=response.text_output, delta={"brief_text": response.text_output}, cost=0.0
)

return AgentOutput(
output=prompt_text, # Fallback to base prompt
delta={"brief_text": prompt_text},
cost=0.0
cost=0.0,
)


Expand All @@ -241,5 +227,5 @@ def create_sprite_agents(hook_provider: Any) -> dict[str, Agent]:
return {
"prompt_builder": PromptBuilderAgent(hook_provider),
"brief_builder": BriefBuilderAgent(hook_provider),
"sprite_generator": SpriteGenerationAgent(hook_provider)
"sprite_generator": SpriteGenerationAgent(hook_provider),
}
Loading