AI知识库

53AI知识库

学习大模型的前沿技术与行业应用场景


用 AI Agent 实现智能家居助理
发布日期:2024-05-08 17:08:26 浏览次数: 1892


AI Agent 是什么?

AI Agent(智能代理)是一种能够自动完成任务、学习和适应环境的智慧系统。人工神经网络和由此发展出来的深度学习技术,是模仿动物大脑神经系统的杰作,从90年代的边缘技术路线成为了今天AI的主流方向。而AI Agent则是通过一个简化的模仿生物的架构来感知外部环境、作出决策,进而与环境进行互动。AI Agent已经演化为人工智能领域的一个重要分支,它们透过自主性、创造力和协作能力,是大语言模型(LLM)落地的一个重要方向。

AI Agent 可以做什么?

如果用生物体做一个比喻的话,LLM(大语言模型)就相当于动物的大脑,能思考、能听懂人话、能回答问题,但没有眼耳鼻子等感受器官、也没有手脚。而AI Agent则是一个完整的生物体,既有大脑(LLM)进行思考、能感知环境的变化、也能用调用手脚(Function)对环境作出应对和改变。

AI Agent 的工作流程

我们以一个智能家居助理案例来演示一下简单的 AI Agent 的工作流程:

  • 对话(Chat):接收人类指令

  • 规划(Planning):规划需要获取什么感应器,或调用什么功能

  • 感知(Percetion):调用感应器获取环境信息

  • 执行(Action):调用功能,改变环境或执行动作

  • 反馈(Feedback):反馈感应器获取的信息或执行结果

流程图如下:

技术介绍

Mistral AI 是大语言模型领域的主要玩家之一,其发布的 Mistral Large 模型,直接对标 OpenAI 的 ChatGPT 4。尽管在参数数量上不及 GPT-4,Mistral-Large 在关键性能方面却能与 GPT-4 媲美,可以说是当前业内的前三。并且对于中国用户,非常友好,可以很方便的注册和调用其 API。在其官方博客中,Mistral Large 在多个常用基准测试中成绩优异,参考下图:

实现原理:通过一个 web 用户界面,用户可以通过自然语言与 LLM(大语言模型)对话。LLM 接收到用户的信息后,检查开发者预先定义的函数库,通过对函数的自然语言描述匹配到合适的函数,把自然语言转化为调用的函数及其参数,并执行函数,获取函数的返回值。最后把结果以自然语言生成后,反馈给用户。由此形成一个完全基于自然语言的沟通、能够通过设备状态感知环境,并能够执行命令改变设备或环境状态的人工智能代理。借助 Mistral AI 的多语言能力,系统支持英文、法文、德文、西班牙文甚至中文(稍比西欧语言弱)的沟通。

代码实现

Talk is cheap, show me the code. 本文示例代码使用 Python 语言,使用 Flash 作为 Web 框架,LLM 模型使用 Mistral AI 的 API (你也可以使用 OpenAI API,基本没有区别)实现。如对上述技术毫无概念,请自行 Google。

  • 首先,我们需要一个数据库存储和记录家居区域、设备及其状态,这里简单化的用 JSON 文件实现:

  1. {

  2. 1: {'zone': 'kitchen', 'devices': {'light': True, 'door': False}},

  3. 2: {'zone': 'outdoor', 'devices': {'light': True, 'camera': True}},

  4. }

  • 初始化 Mistral AI 服务接口:

  1. def __init__(self):

  2. current_app.logger.info(Config.MISTRALAI_KEY)

  3. self.client = MistralClient(api_key=Config.MISTRALAI_KEY)

  4. self.assistant_name = 'IT Administrator Assistant'

  5. self.model_id= 'mistral-large-latest'

  6. self.instruction= 'You are an IT administrator. You are responsible for managing user permissions. You have a list of users and their permissions. You can get the permissions of a user by their username, update the permissions of a user by their username, and get the user ID based on the username. You can use the following functions: getPermissionsByUsername, updatePermissionsByUsername, getUserIdByUsername.'

  7. self.discussion = []

  • 定义AI助理的功能

  1. def define_function__list_available_zones(self):

  2. function = {

  3. "type": "function",

  4. "function": {

  5. "name": "list_available_zones",

  6. "description": "List the available zones of the house.",

  7. "parameters": {

  8. "type": "object"

  9. }

  10. }

  11. }

  12. return function

  13. def define_function__list_device_status_by_zone(self):

  14. function = {

  15. "type": "function",

  16. "function": {

  17. "name": "list_device_status_by_zone",

  18. "description": "List the status of devices in a specific zone.",

  19. "parameters": {

  20. "type": "object",

  21. "properties": {

  22. "zone": {"type": "string", "description": "The zone to list the device status for. Can be 'kitchen' or 'outdoor'."}

  23. },

  24. "required": ["zone"]

  25. }

  26. }

  27. }

  28. return function

  29. def define_function__update_zone_device_status(self):

  30. function = {

  31. "type": "function",

  32. "function": {

  33. "name": "update_zone_status",

  34. "description": "Update the status of a device in a specific zone.",

  35. "parameters": {

  36. "type": "object",

  37. "properties": {

  38. "zone": {"type": "string", "description": "The zone to update the status for. Can be 'kitchen' or 'outdoor'."},

  39. "device": {"type": "string", "description": "The device to update the status for. Can be 'light', 'door', or 'camera'."},

  40. },

  41. "required": ["zone", "device"]

  42. }

  43. }

  44. }

  45. return function

  • 实现设备的功能

  1. def list_available_zones(self):

  2. """

  3. Return the list of available zones.

  4. """

  5. return [info['zone'] for info in self.domotic_data.values()]

  6. def list_device_status_by_zone(self, target_zone):

  7. """

  8. Return the list of devices in a specific zone.

  9. """

  10. for zone_id, info in self.domotic_data.items():

  11. if info['zone'] == target_zone:

  12. return info['devices']

  13. return None

  14. def update_zone_status(self, target_zone, device):

  15. """

  16. Update the status of a device in a specific zone.

  17. """

  18. for zone_id, info in self.domotic_data.items():

  19. if info['zone'] == target_zone:

  20. if device in info['devices']:

  21. info['devices'][device] = not info['devices'][device]

  22. return info['devices']

  23. return None

  • 运行 AI 助理

  1. def run_assistant(self, message):

  2. # 把用户提问消息追加到对话消息列表末尾

  3. current_app.logger.info(f'Running assistant: {message}')

  4. self.discussion.append(ChatMessage(role="user", content=message))

  5. # 执行 LLM 客户端的 chat() 函数,在 tools 参数中添加可用函数

  6. ai_response = self.client.chat(

  7. model=self.model_id,

  8. messages=self.discussion,

  9. tools=[

  10. self.define_function__list_available_zones(),

  11. self.define_function__list_device_status_by_zone(),

  12. self.define_function__update_zone_device_status()

  13. ],

  14. tool_choice="auto"

  15. )

  16. # 把 LLM 生成的中间回复追加到对话消息末尾

  17. self.discussion.append(ai_response.choices[0].message)

  18. # 检查 LLM 生成的回复消息是否有函数调用

  19. tool_calls = ai_response.choices[0].message.tool_calls

  20. # 如有

  21. if tool_calls:

  22. current_app.logger.info(f'Tool calls found: {tool_calls}')

  23. # 执行函数调用,获取函数的输出,并已把函数的返回追加对话消息的末尾

  24. self.generate_tool_outputs(tool_calls)

  25. current_app.logger.info(f'Discussion after tool call: {self.discussion}')

  26. # 执行 LLM 补充函数返回结果,形成自然语言的回答

  27. ai_response = self.client.chat(

  28. model=self.model_id,

  29. messages=self.discussion

  30. )

  31. current_app.logger.info(f'Assistant response after tool call: {ai_response.choices[0].message}')

  32. self.discussion.append(ChatMessage(role="assistant", content=ai_response.choices[0].message.content))

  33. # 把回答返回给用户

  34. current_app.logger.info(f'Assistant response: {ai_response.choices[0].message.content}')

  35. return ai_response.choices[0].message.content

效果截图

  • 列出区域


  • 列出厨房设备

  • 关闭厨房灯



  • 关闭厨房门




  • 列出厨房设备状态






总结

通过调用 Mistral AI(其实用 OpenAI 的效果也类似),非常快速实现了一个实现自然语言感知和控制家居设备的 AI Agent。例子非常简单,但稍加扩展即可实现一个真实的智能家居系统。



53AI,企业落地应用大模型首选服务商

产品:大模型应用平台+智能体定制开发+落地咨询服务

承诺:先做场景POC验证,看到效果再签署服务协议。零风险落地应用大模型,已交付160+中大型企业

联系我们

售前咨询
186 6662 7370
预约演示
185 8882 0121

微信扫码

与创始人交个朋友

回到顶部

 
扫码咨询