Here's a comprehensive implementation of a Pydantic AI agent for Home Assistant using DSPy and synthetic data generation:
python Copy code
from pydantic import BaseModel, Field
from typing import Literal, Optional, List, Tuple
import dspy
import requests
import json
import random
from faker import Faker
# --------------------------
# Pydantic Data Models
# --------------------------
class HomeAssistantCommand(BaseModel):
entity_id: str = Field(..., description="Home Assistant entity identifier")
domain: str = Field(..., description="Domain of the entity (light, switch, etc.)")
action: Literal["turn_on", "turn_off", "set_value"] = Field(..., description="Action to perform")
parameters: Optional[dict] = Field(None, description="Additional parameters for the action")
class UserQuery(BaseModel):
text: str = Field(..., description="Natural language input from user")
context: Optional[dict] = Field(None, description="Additional context for the query")
# --------------------------
# Home Assistant Client
# --------------------------
class HomeAssistantClient:
def __init__(self, base_url: str, token: str):
self.base_url = base_url.rstrip('/')
self.headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
self._validate_connection()
def _validate_connection(self):
"""Check if connection to Home Assistant is valid"""
try:
response = requests.get(f"{self.base_url}/api/", headers=self.headers)
response.raise_for_status()
except requests.exceptions.RequestException as e:
raise ConnectionError(f"Failed to connect to Home Assistant: {str(e)}")
def execute(self, command: HomeAssistantCommand) -> dict:
"""Execute a Home Assistant command"""
service = f"{command.domain}.{command.action}"
url = f"{self.base_url}/api/services/{service}"
payload = {"entity_id": command.entity_id}
if command.parameters:
payload.update(command.parameters)
response = requests.post(url, headers=self.headers, json=payload)
response.raise_for_status()
return response.json()
# --------------------------
# Synthetic Data Generator
# --------------------------
class SyntheticDataGenerator:
def __init__(self):
self.faker = Faker()
self.domains = ["light", "switch", "climate", "cover"]
self.actions = ["turn_on", "turn_off", "set_value"]
self.common_entities = {
"light": ["living_room", "kitchen", "bedroom", "bathroom"],
"switch": ["garage_door", "outdoor_lights", "security_system"],
"climate": ["thermostat", "ac_unit"],
"cover": ["garage_door", "blinds"]
}
def generate_command_variations(self, base_command: str, entity_type: str) -> List[Tuple[str, HomeAssistantCommand]]:
"""Generate multiple natural language variations for a command"""
variations = []
base_entity = f"{entity_type}.{random.choice(self.common_entities[entity_type])}"
# Create 3-5 variations for each command
for _ in range(random.randint(3, 5)):
query = self._generate_query(base_command, base_entity)
cmd = self._create_command(base_entity, entity_type, base_command)
variations.append((query, cmd))
return variations
def _generate_query(self, base_command: str, entity_id: str) -> str:
"""Generate a natural language query using Faker"""
templates = {
"turn_on": [
"Turn on the {entity}",
"Activate {entity}",
"Switch on {entity}",
"Enable {entity}"
],
"turn_off": [
"Turn off {entity}",
"Deactivate {entity}",
"Shut down {entity}",
"Disable {entity}"
],
"set_value": [
"Set {entity} to {value}",
"Adjust {entity} to {value}",
"Change {entity} setting to {value}",
"Configure {entity} as {value}"
]
}
if base_command == "set_value":
value = random.choice([20, 50, 75, 100]) if "light" in entity_id else random.randint(18, 30)
query = random.choice(templates[base_command]).format(
entity=entity_id.split('.')[-1].replace('_', ' ').title(),
value=value
)
return query
return random.choice(templates[base_command]).format(
entity=entity_id.split('.')[-1].replace('_', ' ').title()
)
def _create_command(self, entity_id: str, domain: str, action: str) -> HomeAssistantCommand:
"""Create a Pydantic command from components"""
if action == "set_value":
return HomeAssistantCommand(
entity_id=entity_id,
domain=domain,
action=action,
parameters={"brightness": random.randint(0, 255)} if domain == "light" else {"temperature": random.randint(18, 30)}
)
return HomeAssistantCommand(
entity_id=entity_id,
domain=domain,
action=action
)
def generate_dataset(self, samples=100) -> List[Tuple[str, HomeAssistantCommand]]:
"""Generate a full synthetic dataset"""
dataset = []
for _ in range(samples):
domain = random.choice(self.domains)
base_command = random.choice(self.actions)
variations = self.generate_command_variations(base_command, domain)
dataset.extend(variations)
return dataset
# --------------------------
# DSPy Optimization Setup
# --------------------------
class HomeAssistantModule(dspy.Module):
"""DSPy module for Home Assistant command generation"""
def __init__(self):
super().__init__()
self.prog = dspy.Predict("user_query -> command: HomeAssistantCommand")
def forward(self, user_query: str) -> HomeAssistantCommand:
return self.prog(user_query=user_query).command
def create_optimal_prompt(train_set):
"""Optimize prompt using DSPy teleprompter"""
# Configure DSPy with a suitable LLM
dspy.configure(lm=dspy.LM('gpt-3.5-turbo'))
# Create training examples
trainset = [dspy.Example(user_query=q, command=c) for q, c in train_set]
# Set up teleprompter
teleprompter = dspy.Teleprompter()
optimized_module = teleprompter.compile(HomeAssistantModule, trainset=trainset)
return optimized_module
# --------------------------
# Main Agent Implementation
# --------------------------
class HomeAssistantAgent:
def __init__(self, ha_client: HomeAssistantClient, dspy_module: dspy.Module):
self.ha_client = ha_client
self.dspy_module = dspy_module
def process_query(self, query: str) -> dict:
"""Process a natural language query and execute command"""
# Generate command using DSPy module
prediction = self.dspy_module(user_query=query)
command = prediction.command
# Validate command structure
if not isinstance(command, HomeAssistantCommand):
raise ValueError("Invalid command structure generated")
# Execute command
return self.ha_client.execute(command)
# --------------------------
# Example Usage
# --------------------------
if __name__ == "__main__":
# Configuration
HA_URL = "http://your-home-assistant-instance:8123"
HA_TOKEN = "your-long-lived-access-token"
# Initialize components
ha_client = HomeAssistantClient(HA_URL, HA_TOKEN)
generator = SyntheticDataGenerator()
# Generate synthetic dataset
synthetic_data = generator.generate_dataset(samples=50)
# Create and optimize DSPy module
dspy_module = create_optimal_prompt(synthetic_data)
# Initialize agent
agent = HomeAssistantAgent(ha_client, dspy_module)
# Test query
test_query = "Turn on the living room lights"
result = agent.process_query(test_query)
print(f"Executed command: {result}")