# 自定义智能体
# 概述
本教程旨在指导用户如何通过Groovy脚本来创建自定义智能体,以执行文本生成、知识库查询、多线程处理大文本内容整合、JSON数据处理、Markdown报告生成、语音文件生成及上传至七牛云存储等任务。以下将提供具体的代码示例供参考。
# 术语和缩略语
- AIP: alinesno-infrastructure-platform 的简称。
- GParsPool: Groovy并行系统提供的工具之一,用于实现并行计算。
- R: 响应对象,通常包含操作的结果或状态信息。
- Qiniu: 七牛云,提供云存储和数据加速服务的中国云计算公司。
# 你将获取
- 如何编写Groovy脚本来创建智能体。
- 如何与外部API和服务交互。
- 处理大量文本数据的方法。
- 生成Markdown格式报告的技巧。
- 结合自然语言处理技术生成语音文件,并将其上传到云端存储。
# 集成方式
以下的qianWenLLM不再使用,使用新的modelAdapterLLM模型类,使用示例如下:
# 接口方法说明的示例
processStreamSingle: 一次对话内容,并会保存对话结果,如下示例:
processStreamSingle() 只为单个对话内容返回准备,即一次内容对话后直接返回结果,如下:
import com.alinesno.infra.smart.assistant.api.ModelNodeDto import com.agentsflex.core.llm.Llm import com.agentsflex.core.message.AiMessage import com.agentsflex.llm.deepseek.DeepseekLlm import com.agentsflex.llm.deepseek.DeepseekLlmConfig // 创建对象 def modelNode = new ModelNodeDto(UUID.randomUUID().toString() , false) modelAdapterLLM.setNode(modelNode) def config = new DeepseekLlmConfig( endpoint: "https://dashscope.aliyuncs.com/compatible-mode/v1", apiKey: secretKey?.qwen_key, model: "deepseek-r1" ) Llm llm = new DeepseekLlm(config) def prompt = expertService.clearMessage(taskInfo.getText()) def output = modelAdapterLLM.processStreamSingle(llm , role , prompt , taskInfo) return "操作成功"processStream: 流程对话,不会返回结果,但是会出现流程节点过程
import com.alinesno.infra.smart.assistant.api.ModelNodeDto import com.agentsflex.core.llm.Llm import com.agentsflex.core.message.AiMessage import com.agentsflex.llm.deepseek.DeepseekLlm import com.agentsflex.llm.deepseek.DeepseekLlmConfig // --->>>>>>>>>>>>>>>>>>>>>>>>>>>>> 第1步 --->>>>>>>>>>>>>>> // 创建对象 def modelNodeStep1 = new ModelNodeDto(UUID.randomUUID().toString() , false) modelAdapterLLM.setNode(modelNodeStep1) modelAdapterLLM.eventModelMessage('第1个节点任务' , 'start') def config = new DeepseekLlmConfig( endpoint: "https://dashscope.aliyuncs.com/compatible-mode/v1", apiKey: secretKey?.qwen_key, model: "deepseek-r1" ) Llm llm = new DeepseekLlm(config) def prompt = expertService.clearMessage(taskInfo.getText()) def outputStep1 = modelAdapterLLM.processStream(llm , role , prompt , taskInfo) modelAdapterLLM.eventModelMessage('第1个节点任务' , 'end') // --->>>>>>>>>>>>>>>>>>>>>>>>>>>>> 第2步 --->>>>>>>>>>>>>>> // 创建对象 def modelNodeStep2 = new ModelNodeDto(UUID.randomUUID().toString() ,false) modelAdapterLLM.setNode(modelNodeStep2) modelAdapterLLM.eventModelMessage('第2个节点任务' , 'start') def outputStep2 = modelAdapterLLM.processStream(llm , role , prompt , taskInfo) modelAdapterLLM.eventModelMessage('第2个节点任务' , 'end') // --->>>>>>>>>>>>>>>>>>>>>>>>>>>>> 第3步 --->>>>>>>>>>>>>>> // 合并内容输出 modelAdapterLLM.outputContent(outputStep1 + "\r\n" + outputStep2) return "操作成功"
# 示例返回Groovy脚本(JSON)
import groovy.json.JsonOutput
def jsonObject = [message: "Hello, World!"]
def jsonString = JsonOutput.toJson(jsonObject)
log.info(jsonString)
return jsonString
# 示例返回Markdown脚本
def generateMarkdownReport(title, content) {
"""
# $title
$content
## Summary
- This is a simple report.
- It contains a title and some content.
- Below is a list of items.
### List of Items
- Item 1
- Item 2
- Item 3
---
Generated on: ${new Date()}
"""
}
def reportTitle = "Monthly Sales Report"
def reportContent = """
This month's sales have been outstanding. We've seen a 20% increase in revenue compared to last month. Here are the key points:
- Total Revenue: \$50,000
- Number of Sales: 1,200
- Average Sale Value: \$41.67
"""
def markdownReport = generateMarkdownReport(reportTitle, reportContent)
log.info(markdownReport)
return markdownReport
# 生成语音并上传到七牛
import groovy.json.JsonSlurper
import java.nio.file.*
// JSON字符串解析...
def jsonData = jsonSlurper.parseText(jsonString)
// 生成mp3文件并记录文件名
jsonData.eachWithIndex { entry, index ->
def speaker = entry.speaker
def content = entry.content
def voice = (speaker == '男') ? 'longshuo' : 'longxiaochun'
def filename = "${speaker}_${index}.mp3"
def mp3File = genMp3(content, filename, voice)
mp3Files << mp3File
}
// 合并mp3文件
def finalOutput = "E:\\final_dialogue.mp3"
if (combine(finalOutput, mp3Files)) {
println "最终的对话音频文件已生成: $finalOutput"
} else {
println "合并MP3文件失败"
}
// 生成MP3文件的方法
def genMp3(String text, String filename, String voice) {
File file = qianWenAuditLLM.generateAudit(voice, text)
log.debug("Generating MP3 for: text:{} , filename:{}", text, filename)
return file.getAbsolutePath()
}
// 合并MP3文件的方法
def combine(String outFile, List<String> inFiles) throws Exception {
FileOutputStream fos = new FileOutputStream(outFile, true)
inFiles.each { file ->
FileInputStream fis = new FileInputStream(file)
byte[] buf = new byte[1024 * 1024]
int len
while ((len = fis.read(buf)) != -1) {
fos.write(buf, 0, len)
}
fis.close()
}
fos.close()
return true
}
// 上传文件到七牛
def ossUrl = expertService.uploadFile(finalOutput)
log.debug("ossUrl = {}", ossUrl)
return ossUrl
# 文件上传
def ossUrl = expertService.uploadFile('/home/root/libs/jna-4.5.1.jar')
log.debug("ossUrl = {}", ossUrl)
return ossUrl
# 网页解析
@Grapes(
@Grab(group='org.jsoup', module='jsoup', version='1.15.3')
)
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.select.Elements
Document doc = Jsoup.connect("https://www.baidu.com").get()
println("Page title: " + doc.title())
Elements links = doc.select("a[href]")
links.each { link ->
println("Link: " + link.attr("href"))
println("Text: " + link.text())
}
contextMap.put("title-111", doc.title())
return doc.title()
# 注意事项
- 在实际部署前,请确保所有依赖项已正确安装且版本兼容。
- 对于敏感数据的操作,请采取适当的安全措施。
- 并行处理时要注意资源消耗,避免服务器性能过度消耗。
- 使用第三方服务时,请遵守相应的服务条款及隐私政策。
- 在复杂逻辑或大量数据处理时,建议先在测试环境中验证脚本的功能性和稳定性。