使用Kotlin和ARC框架构建任务管理AI代理
2025-06-09 21:41:03作者:余洋婵Anita
项目概述
本文将介绍如何使用Kotlin语言结合ARC框架构建一个智能任务管理代理。这个代理能够理解自然语言指令,帮助用户添加、删除和列出任务,展示了现代AI代理开发的基本模式。
技术栈介绍
核心组件
- Kotlin语言:JetBrains开发的现代JVM语言,兼具面向对象和函数式编程特性
- ARC框架:一个用于构建AI代理的开源框架
- LangChain4J:Java/Kotlin版的LangChain实现,提供与大型语言模型(LLM)交互的能力
- 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()
}
)
}
代理设计
核心架构
任务管理代理的设计包含以下几个关键部分:
- 代理定义:名称、描述和系统提示
- 输入过滤器:快速拒绝与任务无关的请求
- 工具连接:定义代理可以调用的功能
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"
}
}
}
功能实现
定义代理可以调用的三个核心功能:
- 添加任务:将新任务添加到列表中
- 删除任务:从列表中移除指定任务
- 列出任务:显示当前所有任务
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?"
)
预期行为
- 能够理解并执行任务管理相关指令
- 对于非任务相关的请求(如天气查询),应礼貌拒绝
- 保持任务列表的状态一致性
结果可视化
HTML生成
为了方便查看对话结果,我们实现了一个简单的HTML生成器:
fun generateMinimalHtml(exchanges: List<Pair<String, String?>>): String {
val sb = StringBuilder()
// HTML结构和样式定义
// ...
exchanges.forEachIndexed { index, (userMessage, agentReply) ->
// 添加用户消息和代理回复
// ...
}
// 闭合HTML标签
// ...
return sb.toString()
}
技术要点解析
- 状态管理:使用可变列表
mutableListOf在内存中维护任务状态 - 输入过滤:通过
filterInput提前拦截无关请求,减少不必要的模型调用 - 工具绑定:将Kotlin函数暴露给AI代理作为可调用工具
- 对话管理:通过
Conversation对象维护对话上下文
扩展思路
- 持久化存储:可将任务列表保存到数据库或文件系统
- 多用户支持:为不同用户维护独立的任务列表
- 任务分类:添加优先级、标签等元数据
- 提醒功能:集成日历系统设置任务提醒
总结
本文展示了如何使用Kotlin和ARC框架构建一个功能完整的任务管理AI代理。通过这个示例,开发者可以学习到:
- AI代理的基本架构设计
- 自然语言指令到具体功能的映射
- 对话状态的管理技巧
- 实际业务功能的集成方法
这种模式可以扩展到各种业务场景,如客服系统、智能助手等,是现代AI应用开发的典型范例。
登录后查看全文
热门项目推荐
Kimi-K2.5Kimi K2.5 是一款开源的原生多模态智能体模型,它在 Kimi-K2-Base 的基础上,通过对约 15 万亿混合视觉和文本 tokens 进行持续预训练构建而成。该模型将视觉与语言理解、高级智能体能力、即时模式与思考模式,以及对话式与智能体范式无缝融合。Python00
GLM-4.7-FlashGLM-4.7-Flash 是一款 30B-A3B MoE 模型。作为 30B 级别中的佼佼者,GLM-4.7-Flash 为追求性能与效率平衡的轻量化部署提供了全新选择。Jinja00
new-apiAI模型聚合管理中转分发系统,一个应用管理您的所有AI模型,支持将多种大模型转为统一格式调用,支持OpenAI、Claude、Gemini等格式,可供个人或者企业内部管理与分发渠道使用。🍥 A Unified AI Model Management & Distribution System. Aggregate all your LLMs into one app and access them via an OpenAI-compatible API, with native support for Claude (Messages) and Gemini formats.JavaScript01
idea-claude-code-gui一个功能强大的 IntelliJ IDEA 插件,为开发者提供 Claude Code 和 OpenAI Codex 双 AI 工具的可视化操作界面,让 AI 辅助编程变得更加高效和直观。Java00
KuiklyUI基于KMP技术的高性能、全平台开发框架,具备统一代码库、极致易用性和动态灵活性。 Provide a high-performance, full-platform development framework with unified codebase, ultimate ease of use, and dynamic flexibility.Kotlin06
ebook-to-mindmapepub、pdf 拆书 AI 总结TSX00
项目优选
收起
deepin linux kernel
C
27
11
OpenHarmony documentation | OpenHarmony开发者文档
Dockerfile
515
3.7 K
本项目是CANN提供的数学类基础计算算子库,实现网络在NPU上加速计算。
C++
874
546
Ascend Extension for PyTorch
Python
317
362
暂无简介
Dart
759
182
React Native鸿蒙化仓库
JavaScript
299
347
openEuler内核是openEuler操作系统的核心,既是系统性能与稳定性的基石,也是连接处理器、设备与服务的桥梁。
C
334
156
🎉 (RuoYi)官方仓库 基于SpringBoot,Spring Security,JWT,Vue3 & Vite、Element Plus 的前后端分离权限管理系统
Vue
1.31 K
734
Nop Platform 2.0是基于可逆计算理论实现的采用面向语言编程范式的新一代低代码开发平台,包含基于全新原理从零开始研发的GraphQL引擎、ORM引擎、工作流引擎、报表引擎、规则引擎、批处理引引擎等完整设计。nop-entropy是它的后端部分,采用java语言实现,可选择集成Spring框架或者Quarkus框架。中小企业可以免费商用
Java
12
1
华为昇腾面向大规模分布式训练的多模态大模型套件,支撑多模态生成、多模态理解。
Python
110
128