大家好,我是技術(shù)UP主小傅哥。
?? 從22年至今,小傅哥已經(jīng)帶著大家做了5個AI類項目,包括;(22年)問答助手、(23年)OpenAI應(yīng)用(含支付、敏感詞過濾)、(24年)AI 代碼自動評審、(25年)Ai Agent 智能體、(25年)Ai MCP Gateway 網(wǎng)關(guān)。
這些項目也都是結(jié)合這,AI 這一年最新的技術(shù)動向和應(yīng)用方向,而做的設(shè)計和落地。所以,每次小傅哥都給大家講了,接下來 AI 將影響的一些場景,也都陸續(xù)的發(fā)生了。就像,24年11月發(fā)布 MCP 協(xié)議后,我給大家說,所有互聯(lián)網(wǎng)企業(yè)都將大量的落地 MCP 服務(wù),并開始 Ai Agent 智能體實現(xiàn)(別看市面有 dify、扣子,各個且用還是要做自己的業(yè)務(wù)智能體)。
隨后,25年年初,小傅哥就帶著大家開始了 RAG、MCP、Ai Agent 智能體的開發(fā),并告訴大家,以后 Ai Agent 智能體也會出標(biāo)準(zhǔn)的框架,讓開發(fā)更加容易。這不,谷歌的 ADK 就來了。并且這哥們????還定義A2A協(xié)議。這會讓不是那么大型的互聯(lián)網(wǎng)公司,也會具備 Ai Agent 智能體開發(fā)的能力。
接下來的幾年,所有的業(yè)務(wù)項目,都會以 Ai Agent 智能體翻一遍,程序員新增的崗位和工作量仍然會很多。因為在咱們這,你做的越快,你就得做的越多!
接下來,小傅哥就帶著大家做一下 Google ADK 搭建 AI Agent。如果你感興趣 AI 類項目,還可以在文末獲取全部實戰(zhàn)項目源碼,深度積累此類技術(shù)內(nèi)容。文末有Google ADK 運行效果,交互式對話智能體,對 ELK 進(jìn)行巡檢分析。
一、官網(wǎng)資料
官網(wǎng):https://google./adk-docs/
搭建:https://google./adk-docs/get-started/
- ADK 以輕便化構(gòu)建 Ai Agent 智能體,解決智能體開發(fā)的復(fù)雜流程而設(shè)計。目前支持 Python、Java、Go 3種語言對應(yīng)的技術(shù)框架。
- 整個文檔完整的描述了,智能體的創(chuàng)建和運行、工具的調(diào)用(tools、function、mcp)、可觀測性以及 A2A 協(xié)議等。
- Agent Development Kit (ADK) is designed to empower developers to quickly build, manage, evaluate and deploy AI-powered agents. These quick start guides get you set up and running a simple agent in less than 20 minutes.
二、工程實踐
1. 前置說明
本次的 Ai Agent 實踐,是以 Google ADK 框架為基礎(chǔ),配和 Github system-prompts-and-models-of-ai-tools 開源提示詞項目中的 claude-code-system-prompt 作為必要描述。來實驗,ELK 系統(tǒng)日志智能分析場景。
- API Key:https://ai.v/gemini-api 需要申請開發(fā) API 秘鑰,是免費的。
- Docker 環(huán)境,本項目部署了一套 ELK 日志服務(wù),基于 Docker 部署,之后對 ELK 模擬寫入日志,讓 Ai Agent 智能體進(jìn)行分析。
如果暫時配置不了,可以在測試的時候去掉這部分 mcp 服務(wù)
2. 工程說明
- 工程地址:https://github.com/fuzhengwei/xfg-dev-tech-google-adk
- 這是一套引入了 Google ADK 0.1.0 版本的 Agent 最基礎(chǔ)智能體測試。如果需要擴(kuò)展,還要額外增加很多東西,可以參考 《Ai Agent 智能體項目》
2.1 YML 配置
server:
port: 8901
# 可申請API秘鑰;https://ai.v/gemini-api
google:
api:
base-url: https://generativelanguage.
key: AIzaSyDF6JnvFx7xWEsARS*******可以自己申請免費的
cloud:
project: xfg-google-adk
logging:
level:
root: info
config: classpath:logback-spring.xml
- 在
application-dev.yml 修改你的參數(shù)配置,配置你的 Google api key
2.2 ADK 單測
import com.google.adk.agents.LlmAgent;
import com.google.adk.events.Event;
import com.google.adk.models.Gemini;
import com.google.adk.runner.InMemoryRunner;
import com.google.adk.sessions.Session;
import com.google.genai.Client;
import com.google.genai.types.Content;
import com.google.genai.types.HttpOptions;
import com.google.genai.types.Part;
import io.reactivex.rxjava3.core.Flowable;
publicclass ApiTest {
/**
* 可申請免費測試api
* https://ai.v/gemini-api/docs/quickstart?hl=zh-cn#apps-script
*/
public static void main(String[] args) {
LlmAgent agent = LlmAgent.builder()
.name("test")
.description("test agent help user do work")
.model(Gemini.builder()
.apiClient(Client.builder()
.apiKey("AIzaSyDF6JnvFx7xWEsARSGosNmvTU3ZoCwo-mc")
.httpOptions(HttpOptions
.builder()
.baseUrl("https://generativelanguage.")
.timeout(500000)
.build())
.build())
.modelName("gemini-2.0-flash")
.build())
.build();
InMemoryRunner runner = new InMemoryRunner(agent);
Session session = runner
.sessionService()
.createSession("test", "xiaofuge")
.blockingGet();
Flowable<Event> events = runner.runAsync("xiaofuge", session.id(), Content.fromParts(Part.fromText("hi agent can you help me")));
System.out.print("\nAgent > ");
events.blockingForEach(event -> System.out.println(event.stringifyContent()));
}
}
Agent > Hi there! Yes, I'm here to help. To best assist you, could you tell me what you need help with? The more information you give me, the better I can understand your request and provide a useful response.
- 這是一套最基礎(chǔ)的 Ai Agent 智能體 ADK 的測試使用代碼。其實它的配置和調(diào)用與 Spring AI 框架是有類似之處的,基本上這類框架也都是這樣的使用模式。
- LlmAgent 提供了一整套構(gòu)建智能體的方式,可以設(shè)置客戶端(Gemini),并設(shè)置相關(guān)的 baseUrl、apiKey 參數(shù),以及模型和超時時間等。
- InMemoryRunner 的用途是把 Agent 放入一個記憶執(zhí)行里,讓一整個 Session 會話下的執(zhí)行都被記錄下,這樣才能記錄上下文。
- 之后就是放到響應(yīng)框架進(jìn)行之后和拿到最后結(jié)果啦。
2.3 Agent 智能體測試
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class AutoAgentTest {
@Value("${google.api.base-url}")
private String baseUrl;
@Value("${google.api.key}")
private String apiKey;
privatestaticfinal String USER_ID = "xiaofuge";
privatestaticfinal String NAME = "multi_tool_agent";
publicstatic BaseAgent agent;
@Before
public void init() {
List<McpTool> mcpTools = new ArrayList<>();
mcpTools.addAll(mcp_elk());
mcpTools.addAll(mcp_filesystem());
agent = LlmAgent.builder()
.name(NAME)
.model(Gemini.builder()
.apiClient(Client.builder()
.apiKey(apiKey)
.httpOptions(HttpOptions
.builder()
.baseUrl(baseUrl)
.timeout(500000)
.build())
.build())
.modelName("gemini-2.0-flash")
.build())
.description("You are an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.")
.instruction(
"""
You are an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
可以在這里復(fù)制全部提示詞;https://github.com/x1xhlol/system-prompts-and-models-of-ai-tools/blob/main/Claude%20Code/claude-code-system-prompt.txt
""")
.tools(mcpTools)
.build();
}
/**
* - 需要配置后,才能在單測控制臺輸入內(nèi)容
* IntelliJ IDEA Help -> Edit Custom VM Options -> -Deditable.java.test.console=true
* <br/>
* - <a href="https://ai.v/api">ai.v/api</a>
*/
@Test
public void test_agent() {
InMemoryRunner runner = new InMemoryRunner(agent);
Session session =
runner
.sessionService()
.createSession(NAME, USER_ID)
.blockingGet();
try (Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8)) {
while (true) {
System.out.print("\nYou > ");
String userInput = scanner.nextLine();
if ("quit".equalsIgnoreCase(userInput)) {
break;
}
Content userMsg = Content.fromParts(Part.fromText(userInput));
Flowable<Event> events = runner.runAsync(USER_ID, session.id(), userMsg);
System.out.print("\nAgent > ");
events.blockingForEach(event -> System.out.println(event.stringifyContent()));
}
}
}
private List<McpTool> mcp_elk() {
Map<String, String> env = new HashMap<>();
env.put("ES_HOST", "http://127.0.0.1:9200");
env.put("ES_API_KEY", "none");
ServerParameters mcp_elk = ServerParameters.builder("npx")
.args(List.of(
"-y",
"@awesome-ai/elasticsearch-mcp"
))
.env(env)
.build();
CompletableFuture<McpToolset.McpToolsAndToolsetResult> futureResult =
McpToolset.fromServer(mcp_elk, JsonBaseModel.getMapper());
McpToolset.McpToolsAndToolsetResult result = futureResult.join();
return result.getTools();
}
private List<McpTool> mcp_filesystem() {
ServerParameters mcp_filesystem = ServerParameters.builder("npx")
.args(List.of(
"-y",
"@modelcontextprotocol/server-filesystem",
"/Users/fuzhengwei/Desktop"
))
.build();
CompletableFuture<McpToolset.McpToolsAndToolsetResult> futureResult =
McpToolset.fromServer(mcp_filesystem, JsonBaseModel.getMapper());
McpToolset.McpToolsAndToolsetResult result = futureResult.join();
return result.getTools();
}
}
- AutoAgentTest 智能體,配置了兩個 mcp,mcp_elk、mcp_filesystem 服務(wù)。其實 AI Agent 智能體,都少不了 MCP 服務(wù)的加持,這樣才能讓這個大腦有手腳可以行動起來。
- init 初始化階段,instruction 配置了對應(yīng)的智能體提示詞,這部分很重要,有點像智能體的神經(jīng)。https://github.com/x1xhlol/system-prompts-and-models-of-ai-tools/blob/main/Claude%20Code/claude-code-system-prompt.txt - 可以選擇這里的提示詞配置到智能體進(jìn)行測試。
- 這部分也可以運行測試,之后會你可以進(jìn)行提問。注意,如果你沒有配置 elk,那么可以刪掉
mcpTools.addAll(mcp_elk()); 代碼。 - mcp_filesystem() 配置了,
/Users/fuzhengwei/Desktop 你需要修改為你的本地的有權(quán)限訪問的地址。
2.4 Agent 智能體服務(wù)
有了前面的案例測試基礎(chǔ),就可以把服務(wù)配置成對應(yīng)的接口,以及開發(fā)個簡單的頁面進(jìn)行對接驗證了。
2.4.1 服務(wù)接口
@Slf4j
@RestController
@RequestMapping("/trigger")
@CrossOrigin(origins = "*")
publicclass AgentController {
privatefinal AgentService agentService;
public AgentController(AgentService agentService) {
this.agentService = agentService;
}
@PostMapping(path = "/session", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public CreateSessionResponse createSession(@RequestBody CreateSessionRequest req) {
String sessionId = agentService.createOrGetSession(req.getUserId());
log.info("創(chuàng)建會話ID:{}", sessionId);
returnnew CreateSessionResponse(sessionId);
}
@PostMapping(path = "/chat", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ChatResponse chat(@RequestBody ChatRequest req) {
String sessionId = req.getSessionId();
if (sessionId == null || sessionId.isEmpty()) {
sessionId = agentService.createOrGetSession(req.getUserId());
}
log.info("使用會話ID:{}", sessionId);
List<String> outputs = agentService.chat(req.getUserId(), sessionId, req.getMessage());
returnnew ChatResponse(sessionId, String.join("\n", outputs));
}
}
- 這里就是把單測的服務(wù),包裝成接口。詳細(xì)的部分可以直接看工程代碼。
2.4.2 頁面對接
三、功能測試
1. 部署 elk 日志服務(wù)
- 整個 Ai Agent 案例,配置了 ELK 作為日志分析的基礎(chǔ),所以最好配置下。
- 這里也有云服務(wù)器的部署操作,也可以參考教程來部署。教程:https:///md/road-map/docker-install.html
- 注意配置完成后,要執(zhí)行
elk-blacklist-data.sh 模擬的寫入進(jìn)去一些日志,這樣才能用于分析使用。
2. 啟動服務(wù)訪問頁面
- 以上演示了,使用 Ai Agent 進(jìn)行 ELK 日志分析,通過對話可以看到,最終我們可以拿到系統(tǒng)的日志數(shù)據(jù)。
- 你還可以嘗試配置其他的 MCP 服務(wù),之后驗證各種場景功能。擔(dān)任如果你希望更細(xì)化的做 Ai Agent,還是要看下 《Ai Agent 智能體項目》 這樣可以更細(xì)膩的做出這樣的系統(tǒng),以及對應(yīng)的可視化編排操作。