83 lines
3.1 KiB
Python
83 lines
3.1 KiB
Python
"""
|
|
@provider MockProvider (swarm/providers/mock_provider.py)
|
|
@purpose Deterministic offline provider for zero-cost testing and CI validation.
|
|
"""
|
|
import time
|
|
import json
|
|
from typing import Type, TypeVar, List, Dict, Tuple
|
|
from pydantic import BaseModel
|
|
from swarm.providers.base import BaseLLMProvider, TokenUsage
|
|
|
|
T = TypeVar("T", bound=BaseModel)
|
|
|
|
|
|
class MockProvider(BaseLLMProvider):
|
|
def __init__(self, latency_ms: int = 15):
|
|
self.latency_ms = latency_ms
|
|
|
|
async def generate_structured(
|
|
self,
|
|
prompt: str,
|
|
schema: Type[T],
|
|
system_prompt: str = ""
|
|
) -> Tuple[T, TokenUsage]:
|
|
start = time.perf_counter()
|
|
|
|
# Build mock data corresponding to schema fields
|
|
mock_data = {}
|
|
for field_name, field_info in schema.model_fields.items():
|
|
field_type = field_info.annotation
|
|
|
|
# Simple heuristic mapping for typical simulation schemas
|
|
if field_name == "archetype_id":
|
|
mock_data[field_name] = "ARCH-001"
|
|
elif field_name == "decisions" or "list" in str(field_type).lower():
|
|
mock_data[field_name] = []
|
|
elif field_type in (int,):
|
|
mock_data[field_name] = 42
|
|
elif field_type in (float,):
|
|
mock_data[field_name] = 0.185
|
|
elif field_type in (bool,):
|
|
mock_data[field_name] = True
|
|
elif field_type in (dict,):
|
|
mock_data[field_name] = {"mock_key": "mock_value"}
|
|
else:
|
|
mock_data[field_name] = f"Simulated observation for {field_name}"
|
|
|
|
# If schema has a custom mock generator method or validator
|
|
instance = schema.model_validate(mock_data)
|
|
|
|
elapsed_ms = int((time.perf_counter() - start) * 1000) + self.latency_ms
|
|
usage = TokenUsage(
|
|
prompt_tokens=len(prompt.split()) * 2,
|
|
completion_tokens=45,
|
|
total_tokens=len(prompt.split()) * 2 + 45,
|
|
latency_ms=elapsed_ms,
|
|
model_name="mock-deterministic",
|
|
estimated_cost_usd=0.0
|
|
)
|
|
return instance, usage
|
|
|
|
async def chat(
|
|
self,
|
|
messages: List[Dict[str, str]],
|
|
system_prompt: str = ""
|
|
) -> Tuple[str, TokenUsage]:
|
|
start = time.perf_counter()
|
|
last_user_msg = messages[-1]["content"] if messages else "Hello"
|
|
|
|
reply = (
|
|
f"[Simulated Persona Response]: Based on my budget constraints and repair priorities, "
|
|
f"regarding '{last_user_msg}': I decided to compare prices first because I value genuine OEM parts "
|
|
f"over a small discount, but I appreciate the transparent warranty option."
|
|
)
|
|
elapsed_ms = int((time.perf_counter() - start) * 1000) + self.latency_ms
|
|
usage = TokenUsage(
|
|
prompt_tokens=sum(len(m["content"].split()) for m in messages) * 2,
|
|
completion_tokens=len(reply.split()) * 2,
|
|
total_tokens=120,
|
|
latency_ms=elapsed_ms,
|
|
model_name="mock-deterministic",
|
|
estimated_cost_usd=0.0
|
|
)
|
|
return reply, usage
|