marvin智能家居:AI驱动的家庭自动化系统

marvin智能家居:AI驱动的家庭自动化系统

【免费下载链接】marvin ✨ Build AI interfaces that spark joy 【免费下载链接】marvin 项目地址: https://gitcode.com/gh_mirrors/ma/marvin

智能家居的痛点与marvin解决方案

你是否曾梦想过回家时灯光自动亮起、温度恰好适宜、音乐根据你的心情播放?传统智能家居系统往往停留在简单的设备控制层面,而marvin智能家居平台通过AI Agent(智能代理)技术,实现了真正的场景化、个性化家庭自动化体验。本文将详细介绍如何使用marvin构建具有自主决策能力的智能家居系统,让你的家庭真正理解并满足你的需求。

读完本文后,你将能够:

  • 使用marvin Agent构建智能家庭控制中枢
  • 实现设备间的联动与场景自动化
  • 让系统通过记忆学习家庭成员的生活习惯
  • 处理复杂的多步骤家庭任务
  • 通过自然语言与智能家居系统交互

marvin智能家居系统架构

marvin智能家居系统采用分层架构设计,将AI能力与家庭自动化完美结合:

mermaid

核心组件说明

组件功能描述marvin实现方式
家庭控制Agent系统核心决策者,协调所有智能家居活动marvin.Agent类,配置特定指令与工具
场景管理器处理预设场景(如"电影模式"、"离家模式")marvin.Task类,定义场景触发条件与执行步骤
用户记忆系统存储用户习惯、偏好和历史交互marvin.Memory类,配置向量存储后端
设备集成层连接各类智能家居硬件设备自定义工具函数,通过API控制设备
自然语言接口提供语音/文本交互能力marvin内置NLP能力,支持结构化输出

快速开始:安装与基础配置

系统要求

  • Python 3.10或更高版本
  • 智能家居设备(支持API控制)
  • 网络连接
  • LLM服务API密钥(默认使用OpenAI)

安装marvin

使用Python包管理器安装marvin:

pip install marvin

或使用uv(推荐,更快的包管理工具):

uv add marvin

配置LLM服务

设置OpenAI API密钥(默认配置):

export OPENAI_API_KEY="你的API密钥"

如需使用其他LLM提供商(如DeepSeek、智谱等),请参考marvin的多模型配置文档。

克隆marvin智能家居项目

git clone https://gitcode.com/gh_mirrors/ma/marvin
cd marvin/examples

构建你的第一个智能家庭Agent

创建家庭控制中枢

以下代码创建一个基础的家庭控制Agent,能够理解并执行简单的家庭控制指令:

from marvin import Agent
from pydantic import BaseModel

# 定义设备状态模型
class DeviceState(BaseModel):
    device_type: str
    name: str
    status: str
    value: float | None = None

# 定义简单的设备控制工具
def turn_on_device(device_name: str) -> DeviceState:
    """打开指定设备"""
    print(f"🔌 打开设备: {device_name}")
    return DeviceState(
        device_type=device_name.split("_")[0],
        name=device_name,
        status="on",
        value=100.0 if "light" in device_name else None
    )

def turn_off_device(device_name: str) -> DeviceState:
    """关闭指定设备"""
    print(f"🔌 关闭设备: {device_name}")
    return DeviceState(
        device_type=device_name.split("_")[0],
        name=device_name,
        status="off",
        value=0.0 if "light" in device_name else None
    )

def set_temperature(temp: float) -> DeviceState:
    """设置温度"""
    print(f"🌡️ 设置温度为: {temp}°C")
    return DeviceState(
        device_type="thermostat",
        name="main_thermostat",
        status="active",
        value=temp
    )

# 创建家庭控制Agent
home_agent = Agent(
    name="家庭控制助手",
    description="管理和控制智能家居设备的AI助手",
    instructions="""
    你是一个智能家庭控制助手,负责管理用户的智能家居设备。
    遵循以下原则:
    1. 安全第一,避免任何可能导致危险的操作
    2. 节能优先,在不影响用户体验的情况下节约能源
    3. 精确执行用户指令,必要时请求澄清
    4. 学习用户习惯,提供个性化建议
    """,
    tools=[turn_on_device, turn_off_device, set_temperature]
)

# 测试基本功能
if __name__ == "__main__":
    # 打开客厅灯光
    response = home_agent.run("请打开客厅灯", result_type=DeviceState)
    print(f"结果: {response}")
    
    # 设置温度
    response = home_agent.run("把温度调到24度", result_type=DeviceState)
    print(f"结果: {response}")

代码解析

  1. 设备状态模型:使用Pydantic的DeviceState类定义统一的设备状态表示方式

  2. 设备控制工具

    • turn_on_device: 打开指定设备
    • turn_off_device: 关闭指定设备
    • set_temperature: 调节温度
  3. 家庭控制Agent

    • 配置名称和描述,明确Agent身份
    • 提供详细指令,指导Agent行为
    • 附加设备控制工具,赋予实际操作能力

运行结果

执行上述代码将产生类似以下输出:

🔌 打开设备: 客厅灯
结果: device_type='客厅' name='客厅灯' status='on' value=100.0
🌡️ 设置温度为: 24°C
结果: device_type='thermostat' name='main_thermostat' status='active' value=24.0

高级应用:场景自动化与记忆系统

实现场景模式

通过marvin的Task功能,可以创建复杂的场景自动化:

from marvin import Task, Agent
from datetime import datetime

# 创建场景管理Agent
scene_manager = Agent(
    name="场景管理器",
    instructions="管理家庭中的各种场景模式,协调多个设备的协同工作"
)

# 定义"电影模式"任务
class MovieModeTask(Task):
    def __init__(self):
        super().__init__(
            instructions="""
            激活电影模式:
            1. 将灯光调暗至20%亮度
            2. 关闭主灯,打开氛围灯
            3. 将温度调至22°C
            4. 打开电视和音响系统
            5. 拉上窗帘
            """,
            agent=scene_manager,
            tools=[
                turn_on_device, 
                turn_off_device, 
                set_temperature,
                set_light_brightness,
                control_curtain
            ]
        )

# 温度调节工具(扩展)
def set_light_brightness(device_name: str, brightness: int) -> DeviceState:
    """设置灯光亮度(0-100)"""
    print(f"💡 调整{device_name}亮度至{brightness}%")
    return DeviceState(
        device_type="light",
        name=device_name,
        status="on" if brightness > 0 else "off",
        value=brightness
    )

# 窗帘控制工具
def control_curtain(action: str) -> str:
    """控制窗帘,action为"open"或"close" """
    print(f"窗帘: {action}")
    return f"窗帘已{action}"

# 激活电影模式
if __name__ == "__main__":
    movie_task = MovieModeTask()
    result = movie_task.run()
    print("电影模式激活结果:", result)

添加用户记忆系统

使用marvin的Memory功能,让系统记住用户习惯:

from marvin import Memory, Agent
import asyncio

# 创建用户偏好记忆
user_preferences = Memory(
    key="user_preferences",
    instructions="""
    存储用户的智能家居偏好,包括:
    - 喜欢的温度设置(按时间段)
    - 常用的灯光亮度
    - 偏好的场景模式及触发时间
    - 设备命名习惯
    """
)

# 创建带记忆的家庭Agent
memory_agent = Agent(
    name="记忆型家庭助手",
    memories=[user_preferences],
    instructions="""
    使用提供的记忆系统记住用户偏好,
    根据时间、用户行为自动调整设备设置。
    """
)

# 存储用户偏好示例
async def store_preferences():
    await user_preferences.add("用户喜欢晚上7点后自动开启电影模式")
    await user_preferences.add("用户卧室温度偏好:白天24°C,晚上21°C")
    await user_preferences.add("用户喜欢客厅灯光亮度:白天80%,晚上30%")

# 让Agent使用记忆回答问题
async def demonstrate_memory_use():
    await store_preferences()
    
    # 询问用户偏好
    response = await memory_agent.arun(
        "用户的卧室温度偏好是什么?",
        result_type=str
    )
    print("用户卧室温度偏好:", response)
    
    # 根据时间自动调整
    current_hour = datetime.now().hour
    if current_hour >= 19:  # 晚上7点后
        response = await memory_agent.arun(
            "根据当前时间和用户偏好,应该执行什么操作?",
            result_type=str
        )
        print("建议操作:", response)

# 运行示例
if __name__ == "__main__":
    asyncio.run(demonstrate_memory_use())

运行上述代码,系统将能够记住并应用用户偏好,输出类似:

用户卧室温度偏好: 用户卧室温度偏好:白天24°C,晚上21°C
建议操作: 开启电影模式

设备集成指南

marvin智能家居系统可以与各类智能设备集成,以下是常见设备类型的集成方法:

智能照明系统

# 飞利浦Hue灯光控制示例
import requests

def control_hue_light(light_id: int, on: bool, brightness: int = 100):
    """控制Philips Hue智能灯"""
    hue_bridge_ip = "你的Hue桥接器IP"
    api_key = "你的Hue API密钥"
    
    url = f"http://{hue_bridge_ip}/api/{api_key}/lights/{light_id}/state"
    payload = {
        "on": on,
        "bri": brightness if on else 0
    }
    
    response = requests.put(url, json=payload)
    return f"灯 {light_id} {'已打开' if on else '已关闭'}"

# 将此函数添加到Agent的工具列表中

温控系统集成

# Nest温控器集成示例
import nest_thermostat  # 假设使用第三方库

def get_current_temperature():
    """获取当前温度"""
    thermostat = nest_thermostat.NestThermostat(
        access_token="你的Nest访问令牌"
    )
    return thermostat.get_temperature()

def set_nest_temperature(temp_c: float):
    """设置Nest温控器温度"""
    thermostat = nest_thermostat.NestThermostat(
        access_token="你的Nest访问令牌"
    )
    thermostat.set_temperature(temp_c)
    return f"温度已设置为{temp_c}°C"

# 将这些函数添加到Agent的工具列表中

安防系统集成

# 智能门锁集成示例
def lock_door(lock_id: str) -> str:
    """锁定智能门锁"""
    # 实际实现将调用门锁API
    print(f"锁定门锁: {lock_id}")
    return f"门锁 {lock_id} 已锁定"

def unlock_door(lock_id: str) -> str:
    """解锁智能门锁"""
    # 实际实现将调用门锁API
    print(f"解锁门锁: {lock_id}")
    return f"门锁 {lock_id} 已解锁"

def check_door_status(lock_id: str) -> str:
    """检查门锁状态"""
    # 实际实现将调用门锁API
    return f"门锁 {lock_id} 状态: 已锁定"  # 假设返回锁定状态

多Agent协作:构建智能家居团队

对于复杂的智能家居系统,可以创建多个专业Agent协同工作:

from marvin import Agent, Team

# 创建专业Agent
security_agent = Agent(
    name="安防Agent",
    instructions="监控家庭安全系统,处理门锁、摄像头和警报",
    tools=[lock_door, unlock_door, check_door_status]
)

comfort_agent = Agent(
    name="舒适度Agent",
    instructions="管理温度、湿度和空气质量,确保最佳居住环境",
    tools=[set_temperature, get_current_temperature]
)

entertainment_agent = Agent(
    name="娱乐Agent",
    instructions="管理音视频设备,处理媒体播放和场景切换",
    tools=[turn_on_device, turn_off_device]
)

# 创建家庭协调Agent
coordinator_agent = Agent(
    name="家庭协调者",
    instructions="协调所有家庭Agent,作为用户的主要交互点",
    delegates=[security_agent, comfort_agent, entertainment_agent]
)

# 或者创建一个团队
home_team = Team(
    name="智能家居团队",
    members=[
        coordinator_agent,
        security_agent,
        comfort_agent,
        entertainment_agent
    ]
)

# 使用团队处理复杂请求
def process_complex_request():
    # 用户离家请求,需要多个Agent协作
    response = coordinator_agent.run("我要出门了,请准备系统")
    print("离家准备结果:", response)

if __name__ == "__main__":
    process_complex_request()

上述代码将创建一个智能家居团队,能够协同处理复杂请求。当用户说"我要出门了",系统会自动协调安防Agent(锁门)、舒适度Agent(调整温度)和娱乐Agent(关闭所有设备)。

实际应用场景与示例代码

场景1:早晨唤醒流程

from marvin import Task, Agent
from datetime import time

# 创建唤醒流程任务
wake_up_task = Task(
    instructions="""
    执行早晨唤醒流程:
    1. 早上7:00逐渐打开卧室窗帘
    2. 7:05 逐渐调亮卧室灯光(5分钟内从0%到70%)
    3. 7:10 播放早间新闻或用户喜欢的音乐
    4. 7:15 调节浴室温度至25°C
    """,
    tools=[control_curtain, set_light_brightness, play_media, set_temperature]
)

# 定时触发
def schedule_wake_up():
    current_time = datetime.now().time()
    wake_up_time = time(7, 0)  # 早上7点
    
    if current_time >= wake_up_time and current_time < time(7, 30):
        result = wake_up_task.run()
        print("唤醒流程结果:", result)

if __name__ == "__main__":
    schedule_wake_up()

场景2:节能模式自动激活

from marvin import Agent, Task
from pydantic import BaseModel

class EnergySavingState(BaseModel):
    """节能状态模型"""
    activated: bool
    devices_turned_off: list[str]
    temperature_adjusted: bool
    savings_estimate: str

# 创建节能Agent
energy_agent = Agent(
    name="节能Agent",
    instructions="监控家庭能源使用,在无人时自动激活节能模式",
    tools=[turn_off_device, set_temperature, check_occupancy]
)

# 定义节能任务
energy_saving_task = Task(
    instructions="""
    当检测到家中无人时:
    1. 关闭所有非必要照明
    2. 将温度调整至节能水平(夏季28°C,冬季18°C)
    3. 关闭娱乐设备和其他非必要电器
    4. 保留冰箱、安防系统等必要设备运行
    """,
    agent=energy_agent,
    result_type=EnergySavingState
)

# 检测是否有人在家
def check_occupancy() -> bool:
    """检查家中是否有人"""
    # 实际实现可能通过运动传感器、手机位置等数据
    return False  # 假设家中无人

# 运行节能模式
def run_energy_saving():
    if not check_occupancy():
        result = energy_saving_task.run()
        print("节能模式激活结果:", result)

if __name__ == "__main__":
    run_energy_saving()

场景3:语音控制接口

from marvin import Agent
import speech_recognition as sr
from gtts import gTTS
import os

# 创建语音交互Agent
voice_agent = Agent(
    name="语音助手",
    instructions="将语音指令转换为智能家居操作,并提供语音反馈"
)

# 语音识别函数
def listen_command() -> str:
    """监听并识别语音指令"""
    recognizer = sr.Recognizer()
    
    with sr.Microphone() as source:
        print("请说出您的指令...")
        audio = recognizer.listen(source)
    
    try:
        command = recognizer.recognize_google(audio, language="zh-CN")
        print(f"识别到指令: {command}")
        return command
    except sr.UnknownValueError:
        return "抱歉,我没有听懂您的指令"
    except sr.RequestError:
        return "抱歉,语音识别服务不可用"

# 语音合成函数
def speak_response(text: str):
    """将文本转换为语音"""
    tts = gTTS(text=text, lang="zh-CN")
    tts.save("response.mp3")
    os.system("mpg123 response.mp3")  # 使用适当的播放器

# 语音交互循环
def voice_interaction_loop():
    print("智能家居语音控制已启动...")
    while True:
        command = listen_command()
        if "退出" in command:
            speak_response("再见!")
            break
        
        response = voice_agent.run(command)
        print("系统响应:", response)
        speak_response(response)

if __name__ == "__main__":
    voice_interaction_loop()

系统优化与最佳实践

性能优化

  1. 减少API调用

    • 缓存设备状态,避免重复查询
    • 批量处理设备控制指令
  2. 优化提示词

    • 为特定设备创建专用指令模板
    • 使用结构化输出减少解析开销
  3. 本地处理

    • 简单规则逻辑在本地执行,无需调用LLM
    • 仅复杂决策使用AI能力

安全最佳实践

  1. 权限控制

    • 为不同用户设置不同控制权限
    • 敏感操作(如门锁)需二次确认
  2. 隐私保护

    • 本地处理语音指令,仅必要数据上传
    • 定期清理敏感记忆数据
  3. 系统防护

    • 为API调用添加超时和重试机制
    • 实现异常检测,防止异常指令执行

系统扩展建议

  1. 模块化设计

    • 每个设备类型创建独立工具模块
    • 使用配置文件管理设备列表,避免硬编码
  2. 日志与监控

    • 记录所有设备状态变化
    • 监控系统性能和响应时间
    • 设置异常警报机制
  3. 用户体验改进

    • 实现渐进式学习,随使用优化系统行为
    • 添加手动覆盖选项,在AI决策错误时允许用户纠正

故障排除与常见问题

设备控制失败

  • 检查网络连接:确保设备和控制中枢在线
  • 验证API密钥:确认设备API凭证有效
  • 检查权限:确保marvin有权限控制设备
  • 查看日志:检查marvin和设备日志,定位具体错误

Agent决策不符合预期

  • 优化指令:提供更明确的Agent指令
  • 调整模型:尝试更强大的LLM模型(如从gpt-3.5-turbo升级到gpt-4)
  • 增加示例:在指令中提供示例,明确期望行为
  • 细化工具描述:确保工具函数描述清晰,包含参数说明

记忆系统不工作

  • 检查存储配置:确认向量数据库配置正确
  • 验证记忆添加:确保信息被正确添加到记忆中
  • 调整检索参数:可能需要调整记忆检索的相似度阈值
  • 检查记忆大小:过大的记忆可能导致检索精度下降

总结与未来展望

marvin智能家居系统展示了AI Agent技术在家庭自动化中的强大潜力。通过结合LLM的自然语言理解能力、任务规划能力和长期记忆系统,我们可以构建真正智能、个性化的家居体验。

已实现功能回顾

  • 自然语言控制智能家居设备
  • 基于用户习惯的个性化自动化
  • 多设备协同场景模式
  • 自主决策能力与任务规划
  • 长期记忆与学习能力

未来发展方向

  1. 更深入的上下文理解:结合更多传感器数据(如用户情绪、健康状态)优化决策
  2. 多模态交互:整合视觉输入(摄像头),实现更丰富的环境理解
  3. 能源优化:通过AI预测和调整,进一步降低家庭能源消耗
  4. 健康集成:结合健康监测设备,创建促进健康生活的家居环境
  5. 社区共享:允许用户分享场景配置和自动化规则

marvin智能家居系统不仅是一个控制工具,更是一个能够理解、学习和适应家庭成员需求的AI助手。通过持续进化,未来的智能家居系统将真正成为我们生活中的得力伙伴,让科技无缝融入日常生活,创造更舒适、安全、高效的居住环境。

要开始构建你的marvin智能家居系统,只需安装marvin包并参考本文提供的示例代码。随着你的系统扩展,记得查看marvin官方文档以获取更多高级功能和最佳实践指南。

【免费下载链接】marvin ✨ Build AI interfaces that spark joy 【免费下载链接】marvin 项目地址: https://gitcode.com/gh_mirrors/ma/marvin

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值