首页
/ 使用Kotlin和ARC框架构建任务管理AI代理

使用Kotlin和ARC框架构建任务管理AI代理

2025-06-09 16:18:00作者:余洋婵Anita

项目概述

本文将介绍如何使用Kotlin语言结合ARC框架构建一个智能任务管理代理。这个代理能够理解自然语言指令,帮助用户添加、删除和列出任务,展示了现代AI代理开发的基本模式。

技术栈介绍

核心组件

  1. Kotlin语言:JetBrains开发的现代JVM语言,兼具面向对象和函数式编程特性
  2. ARC框架:一个用于构建AI代理的开源框架
  3. LangChain4J:Java/Kotlin版的LangChain实现,提供与大型语言模型(LLM)交互的能力
  4. OpenAI GPT-4:作为底层语言模型提供自然语言理解能力

环境配置

依赖管理

首先需要配置项目依赖,确保可以访问必要的库:

%useLatestDescriptors
%use coroutines
@file:DependsOn("org.eclipse.lmos:arc-langchain4j-client:0.122.0-M2")
@file:DependsOn("dev.langchain4j:langchain4j-open-ai:1.0.0-beta1")

API密钥设置

使用OpenAI服务需要配置API密钥:

val openAiApiKey = System.getenv("OPENAI_API_KEY") ?: "YOUR-OPENAI-API-KEY"

模型配置

配置与GPT-4模型的连接:

import dev.langchain4j.model.openai.OpenAiChatModel
import org.eclipse.lmos.arc.agents.llm.ChatCompleter
import org.eclipse.lmos.arc.client.langchain4j.LangChainClient
import org.eclipse.lmos.arc.client.langchain4j.LangChainConfig

val chatProvider : (String?) -> ChatCompleter = {
    LangChainClient(
        languageModel = LangChainConfig(
            modelName = "gpt-4",            // 使用GPT-4模型
            url = null,                     // 默认OpenAI端点
            apiKey = openAiApiKey,          // API密钥
            credentialId = null,
            credentialSecret = null,
        ),
        clientBuilder = { config, _ ->
            OpenAiChatModel.builder()
                .modelName(config.modelName)
                .apiKey(config.apiKey)
                .build()
        }
    )
}

代理设计

核心架构

任务管理代理的设计包含以下几个关键部分:

  1. 代理定义:名称、描述和系统提示
  2. 输入过滤器:快速拒绝与任务无关的请求
  3. 工具连接:定义代理可以调用的功能
val agentBuilder = DSLAgents
    .init(chatProvider)
    .apply {
        define {
            agent {
                name = "task-manager"
                description = "Helps the user manage their tasks: add, remove, list tasks."
                
                prompt {
                    """
                    You are a Task Manager Agent.
                    Your goal is to help the user manage their tasks:
                    they can add tasks, remove tasks, or list tasks.

                    # Instructions
                    - If user wants to add a new task, call the 'add_task' function with the task description.
                    - If user wants to remove a task, call the 'remove_task' function with the exact task name.
                    - If user wants to see all tasks, call the 'list_tasks' function.
                    - If the user asks anything that is not related to tasks, respond with "I only handle tasks."
                    """.trimIndent()
                }

                filterInput {
                    val text = message.lowercase()
                    if (!text.contains("task") && !text.contains("list") && !text.contains("add") && !text.contains("remove")) {
                        breakWith("I only handle tasks.")
                    }
                }

                tools {
                    +"add_task"
                    +"remove_task"
                    +"list_tasks"
                }
            }
        }

功能实现

定义代理可以调用的三个核心功能:

  1. 添加任务:将新任务添加到列表中
  2. 删除任务:从列表中移除指定任务
  3. 列出任务:显示当前所有任务
defineFunctions {
    val tasks = mutableListOf<String>()

    function(
        name = "add_task",
        description = "Add a task to the list",
        params = types(string("description", "The description of the new task."))
    ) { (description) ->
        tasks.add(description as String)
        "Task '$description' added. Now you have ${tasks.size} task(s)."
    }

    function(
        name = "remove_task",
        description = "Remove a task by its exact name",
        params = types(string("description", "The task to remove."))
    ) { (description) ->
        val removed = tasks.removeIf { it.equals(description as? String, ignoreCase = true) }
        if (removed) "Task '$description' removed."
        else "No such task found: '$description'."
    }

    function(
        name = "list_tasks",
        description = "List all tasks currently stored",
        params = types()
    ) {
        if (tasks.isEmpty()) {
            "No tasks found."
        } else {
            "Here are your tasks:\n" + tasks.joinToString("\n") { "- $it" }
        }
    }
}

对话测试

测试场景

我们设计了一系列测试对话来验证代理的功能:

val messages = listOf(
    "Hi, I'm new here. Can you help me organize my tasks?",
    "I need to add a task: Buy groceries for dinner",
    "Add another task: Complete the quarterly report by Friday",
    "Add task: Schedule team meeting for next week",
    "Can you show me all my current tasks?",
    "I finished buying groceries - please remove that task",
    "What tasks do I still have pending?",
    "Could you tell me today's weather forecast?"
)

预期行为

  1. 能够理解并执行任务管理相关指令
  2. 对于非任务相关的请求(如天气查询),应礼貌拒绝
  3. 保持任务列表的状态一致性

结果可视化

HTML生成

为了方便查看对话结果,我们实现了一个简单的HTML生成器:

fun generateMinimalHtml(exchanges: List<Pair<String, String?>>): String {
    val sb = StringBuilder()
    // HTML结构和样式定义
    // ...
    exchanges.forEachIndexed { index, (userMessage, agentReply) ->
        // 添加用户消息和代理回复
        // ...
    }
    // 闭合HTML标签
    // ...
    return sb.toString()
}

技术要点解析

  1. 状态管理:使用可变列表mutableListOf在内存中维护任务状态
  2. 输入过滤:通过filterInput提前拦截无关请求,减少不必要的模型调用
  3. 工具绑定:将Kotlin函数暴露给AI代理作为可调用工具
  4. 对话管理:通过Conversation对象维护对话上下文

扩展思路

  1. 持久化存储:可将任务列表保存到数据库或文件系统
  2. 多用户支持:为不同用户维护独立的任务列表
  3. 任务分类:添加优先级、标签等元数据
  4. 提醒功能:集成日历系统设置任务提醒

总结

本文展示了如何使用Kotlin和ARC框架构建一个功能完整的任务管理AI代理。通过这个示例,开发者可以学习到:

  1. AI代理的基本架构设计
  2. 自然语言指令到具体功能的映射
  3. 对话状态的管理技巧
  4. 实际业务功能的集成方法

这种模式可以扩展到各种业务场景,如客服系统、智能助手等,是现代AI应用开发的典型范例。

登录后查看全文
热门项目推荐