1+ package com .baeldung .google .adk ;
2+
3+ import com .google .adk .agents .BaseAgent ;
4+ import com .google .adk .runner .InMemoryRunner ;
5+ import com .google .adk .sessions .Session ;
6+ import com .google .genai .types .Content ;
7+ import com .google .genai .types .Part ;
8+ import org .springframework .stereotype .Service ;
9+
10+ import java .util .UUID ;
11+ import java .util .concurrent .ConcurrentHashMap ;
12+ import java .util .concurrent .ConcurrentMap ;
13+
14+ @ Service
15+ class AgentService {
16+
17+ private final InMemoryRunner runner ;
18+ private final ConcurrentMap <String , Session > inMemorySessionCache = new ConcurrentHashMap <>();
19+
20+ AgentService (BaseAgent baseAgent ) {
21+ this .runner = new InMemoryRunner (baseAgent );
22+ }
23+
24+ UserResponse interact (UserRequest request ) {
25+ UUID userId = request .userId () != null ? request .userId () : UUID .randomUUID ();
26+ UUID sessionId = request .sessionId () != null ? request .sessionId () : UUID .randomUUID ();
27+
28+ String cacheKey = userId + ":" + sessionId ;
29+ Session session = inMemorySessionCache .computeIfAbsent (cacheKey , key ->
30+ runner .sessionService ()
31+ .createSession (runner .appName (), userId .toString (), null , sessionId .toString ())
32+ .blockingGet ()
33+ );
34+
35+ Content userMessage = Content .fromParts (Part .fromText (request .question ()));
36+ StringBuilder answerBuilder = new StringBuilder ();
37+ runner .runAsync (userId .toString (), session .id (), userMessage )
38+ .blockingForEach (event -> {
39+ String content = event .stringifyContent ();
40+ if (content != null && !content .isBlank ()) {
41+ answerBuilder .append (content );
42+ }
43+ });
44+
45+ return new UserResponse (userId , sessionId , answerBuilder .toString ());
46+ }
47+ }
0 commit comments