Spring AI 是 Spring 生态中用于简化 AI 应用开发的框架,让开发者能轻松集成大语言模型。今天的 Demo 将基于阿里云的 DashScope 平台,创建一个专业的心理咨询师智能体。
首先,我们需要创建一个 Spring 项目。推荐使用 IDEA 开发工具:
在项目的 pom.xml 文件中,添加以下两个核心依赖:
<dependency> <groupId>com.alibaba.cloud.ai</groupId> <artifactId>spring-ai-alibaba-agent-framework</artifactId> <version>1.1.0.0-M5</version></dependency><dependency> <groupId>com.alibaba.cloud.ai</groupId> <artifactId>spring-ai-alibaba-starter-dashscope</artifactId> <version>1.1.0.0-M5</version></dependency>
这两个依赖分别提供了智能体框架和 DashScope 模型的支持。
在 com.jackson.aiagent 包下创建 AgentExample.java 文件:
package com.jackson.aiagent;//
导入必要的类public class AgentExample { public static void main(String[] args) throws Exception { // 1. 创建模型实例(记得替换成你自己的API Key)
DashScopeApi dashScopeApi basketzhibo.com = DashScopeApi.builder()
.apiKey("sk-309xxxxxxxxxxxxxxxxxxxxxxxx")
.build(); ChatModel chatModel = DashScopeChatModel.builder()
.dashScopeApi(dashScopeApi)
.build(); // 2. 创建智能体角色
ReactAgent agent = ReactAgent.builder()
.name("智能心理咨询师")
.model(chatModel)
.instruction("你是一名10年经验的资深心理咨询师.")
.build(); // 3. 与智能体对话
var response = agent.call("抑郁症有些什么症状?该如何缓解?");
System.out.println(response.getText());
}
}
代码编写完成后,直接运行 main 方法。你会看到控制台输出类似以下内容:

这个 Demo 虽然简单,但已经包含了 AI 智能体的核心要素。你可以尝试:
通过这个教程,我们见证了 Spring AI 的强大之处——用极简的代码实现智能对话功能。作为 AI 新手,这是一个完美的起点。未来你可以在此基础上探索更复杂的 AI 应用场景。
动手试试吧! 在评论区分享你的第一个智能体作品,遇到问题随时提问哦~
本文基于技术文档整理,适合 AI 入门学习。实际开发中请参考官方最新文档。
# https://github.com/elapouya/python-docx-template/blob/master/tests/dynamic_table.py from docxtpl import DocxTemplate import os # data: https://github.com/elapouya/python-docx-template/blob/master/tests/templates/dynamic_table_tpl.docx tpl = DocxTemplate ( "templates/dynamic_table_tpl.docx" ) context = { "col_labels" : [ "fruit" ,footzhibo.com "vegetable" , "stone" , "thing" ] , "tbl_contents" : [ { "label" : "yellow" , "cols" : [ "banana" , "capsicum" , "pyrite" , "taxi" ] } , { "label" : "red" , "cols" : [ "apple" , "tomato" , "cinnabar" , "doubledecker" ] } , { "label" : "green" ,nbc-sports.cn "cols" : [ "guava" , "cucumber" , "aventurine" , "card" ] } , ] , } tpl . render ( context ) os . makedirs ( "output" , exist_ok = True )
# https://github.com/elapouya/python-docx-template/blob/master/tests/horizontal_merge.py from docxtpl import DocxTemplate import os # data: https://github.com/elapouya/python-docx-template/blob/master/tests/templates/horizontal_merge_tpl.docx tpl = DocxTemplate ( "templates/horizontal_merge_tpl.docx" ) tpl . render ( {footzhibo.com } ) os . makedirs ( "output" , exist_ok = True ) tpl . save ( "output/horizontal_merge.docx" )
下示例展示了如何实现表格单元格的垂直合并效果:
# https://github.com/elapouya/python-docx-template/blob/master/tests/vertical_merge.py from docxtpl import DocxTemplate # data: https://github.com/elapouya/python-docx-template/blob/master/tests/templates/vertical_merge_tpl.docxtpl = DocxTemplate ( "templates/vertical_merge_tpl.docx" )context = { "items" : [ { "desc" : cantaitech.com "Python interpreters" , "qty" : 2 , "price" : "FREE" } , { "desc" : "Django projects" , "qty" : 5403 , "price" : "FREE" } , { "desc" :livesoccerzb.com "Guido" , "qty" : 1 , "price" : "100,000,000.00" } , ] , "total_price" : "100,000,000.00" , "category" : "Book" , }
{{r rich_text_var}},其中的r表示富文本。在代码中使用RichText类时,还可通过以下标记控制文本格式:
\n;\a;\f。以下为生成富文本Word文档的示例:
# https://github.com/elapouya/python-docx-template/blob/master/tests/richtext.pyfrom docxtpl import DocxTemplate, RichText# data: https://github.com/elapouya/python-docx-template/blob/master/tests/templates/richtext_tpl.docxtpl = DocxTemplate("templates/richtext_tpl.docx")rt = RichText()# 向富文本对象中添加内容,依次演示不同的文本格式设置rt.add("a rich text", style="myrichtextstyle") # 使用自定义样式rt.add(" with ") rt.add("some italic", italic=True) # 斜体文本rt.add(" and ")rt.add("some violet", color="#ff00ff") # 紫色文本(十六进制颜色码)rt.add(" and ")rt.add("some striked", strike=True) # 删除线文本rt.add(" and ")rt.add("some Highlighted", highlight="#ffff00") # 黄色高亮文本rt.add(" and ")rt.add("some small", size=14) # 小字号文本(14磅)rt.add(" or ")rt.add("big", size=60) # 大字号文本(60磅)rt.add(" text.")rt.add("\nYou can add an hyperlink, here to ")# 添加带超链接的文本,build_url_id 用于创建URL标识并关联到指定链接rt.add("bing", url_id=tpl.build_url_id("http://bing.com"))rt.add("\nEt voilà ! ")# 演示换行符效果rt.add("\n1st line")rt.add("\n2nd line")rt.add("\n3rd line")# \a 用于创建新段落rt.add("\aA new paragraph : <cool>\a")# \f 用于插入分页符rt.add("--- A page break here (see next page) ---\f")# 循环演示不同类型的下划线样式for ul in [
"single", # 单下划线
"double", # 双下划线
"thick", # 粗下划线
"dotted", # 点下划线
"dash", # 短划线下划线
"dotDash", # 点划线下划线
"dotDotDash", # 双点划线下划线
"wave", # 波浪线下划线]:
rt.add("\nUnderline : " + ul + " \n", underline=ul)# 演示不同字体的设置rt.add("\nFonts :\n", underline=True)rt.add("Arial\n", font="Arial") rt.add("Courier New\n", font="Courier New") rt.add("Times New Roman\n", font="Times New Roman") # 演示上标和下标文本rt.add("\n\nHere some")rt.add("superscript", superscript=True) # 上标文本rt.add(" and some")rt.add("subscript", subscript=True) # 下标文本# 创建一个新的富文本对象,并将之前创建的rt对象嵌入其中,实现富文本嵌套rt_embedded = RichText("an example of ")rt_embedded.add(rt)# 构建渲染上下文,将嵌套的富文本对象赋值给模板中的 "example" 变量context = {
"example": rt_embedded,}# 将上下文数据渲染到Word模板中
rtp
=
RichTextParagraph
(
)
# 创建富文本对象,用于设置文本的字符样式
rt
=
RichText
(
)
# 向富文本段落中添加文本,并指定自定义样式myrichparastyle
rtp
.
add
(
"The rich text paragraph function allows paragraph styles to be added to text"
,
parastyle
=
"myrichparastyle"
,
)
# 添加文本并使用内置段落样式IntenseQuote
rtp
.
add
(
"Any built in paragraph style can be used"
,
parastyle
=
"IntenseQuote"
)
# 添加文本并使用自定义样式createdStyle
rtp
.
add
(
"or you can add your own,remenzhibo.com unlocking all style options"
,
parastyle
=
"createdStyle"
)
# 添加文本并使用默认普通段落样式normal
rtp
.
add
(
"To use,zuqiu2026.cn just create a style in your template word doc with the formatting you want "
"and call it in the code."
,
parastyle
=
"normal"
,
)
# 演示不同列表样式的使用
rtp
.
add
(
"This allows for the use of"
)
rtp
.
add
(
"custom bullet\apoints"
,
parastyle
=
"SquareBullet"
)
# 方形项目符号样式
rtp
.
add
(
"Numbered Bullet Points"
,
parastyle
=
"BasicNumbered"
)
# 数字编号样式
rtp
.
add
(
"and Alpha Bullet Points."
,
parastyle
=
"alphaBracketNumbering"
)
# 字母编号样式
# 演示文本对齐方式的设置
rtp
.
add
(
"You can"
,
parastyle
=
"normal"
)
# 默认左对齐
rtp
.
add
(
"set the"
,
parastyle
=
"centerAlign"
)
# 应用自定义样式居中对齐
rtp
.
add
(
"text alignment"
,
parastyle
=
"rightAlign"
)
# 应用自定义样式右对齐
# 演示行间距样式:紧凑行间距
rtp
.
add
(
"as well as the spacing between lines of text.basketzhibo.com Like this for example, "
"this text has very tight spacing between the lines.\aIt also has no space between "
"paragraphs of the same style."
,
parastyle
=
"TightLineSpacing"
,
)
# 演示行间距样式:宽行间距
rtp
.
add
(
"Unlike this one, which has extra large spacing between lines for when you want to "
"space things out a bit or 5gzbw.com just write a little less."
,
parastyle
=
"WideLineSpacing"
,
)
# 演示段落背景色样式:绿色背景
rtp
.
add
(
"You can also set the background colour of a line."
,
parastyle
=
"LineShadingGreen"
)
# 构建富文本字符串,演示字符级样式
rt
.
add
(
"This works with "
)
rt
.
add
(
"Rich "
,
bold
=
True
)
# 加粗
rt
.
add
(
"Text "
,
italic
=
True
)
# 斜体
rt
.
add
(
"Strings"
,
underline
=ttkq-24.com
"single"
)
# 单下划线
rt
.
add
(
" too."
)
# 将富文本对象添加到富文本段落中,并指定方形项目符号样式
rtp
.
add
(
rt
,
parastyle
=
"SquareBullet"
)
# 构建渲染上下文,将富文本段落对象绑定到模板中的example变量
context
=
{
"example"
:
rtp
,
}
# 将上下文数据渲染到 Word 模板中
tpl
.
render
(
context
)
from docx . shared import Mm import jinja2 # data: https://github.com/elapouya/python-docx-template/blob/master/tests/templates/inline_image_tpl.docx tpl = DocxTemplate ( "templates/inline_image_tpl.docx" ) # 定义渲染模板所需的上下文数据 context =yixue5.com { # 只设置宽或者高,则图片自适应变化 "myimage" : InlineImage ( tpl , "templates/python_logo.png" , width = Mm ( 20 ) ) , # 手动指定宽高度 "myimageratio" : InlineImage ( tpl , "templates/python_jpeg.jpg" , width = Mm ( 30 ) , height = Mm ( 60 ) ) , # 定义图片+描述 "frameworks" : [ { "image" : InlineImage ( tpl , "templates/django.png" , height = Mm ( 10 ) ) , "desc" : xiqinhb.com "The web framework for perfectionists with deadlines" , } , { "image" : InlineImage ( tpl , "templates/zope.png" , height = Mm ( 10 ) ) , "desc" : "Zope is a leading Open Source Application Server " "and Content Management Framework" , } , { "image" : InlineImage ( tpl , "templates/pyramid.png" , height = Mm ( 10 ) ) , "desc" : "Pyramid is a lightweight Python web framework aimed at taking " "small web apps c20paper.com into big web apps." , } , { "image" : InlineImage ( tpl , "templates/bottle.png" , height = Mm ( 10 ) ) , "desc" : "Bottle is a fast, simple and lightweight WSGI micro web-framework " "for Python" , } , { "image" : InlineImage ( tpl ,chengyiwl.com "templates/tornado.png" , height = Mm ( 10 ) ) , "desc" : "Tornado is a Python web framework and asynchronous networking " "library." , } , ] , } # autoescape是否开启自动转义,把模板变量中的特殊字符转换成无害的HTM实体 jinja_env = jinja2 . Environment ( autoescape = True ) # 使用上下文数据和自定义的jinja2环境渲染Word模板
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70048957/viewspace-3109050/ ,如需转载,请注明出处,否则将追究法律责任。