|
1 | 1 | import os |
2 | 2 | import json |
3 | 3 | import re |
| 4 | +import uuid |
4 | 5 | from typing import List |
5 | 6 |
|
6 | 7 | import httpx |
|
11 | 12 | from slack_bolt.adapter.starlette.async_handler import AsyncSlackRequestHandler |
12 | 13 | from google.genai import types |
13 | 14 | from google.adk.agents import Agent |
| 15 | +from google.adk.events.event import Event |
14 | 16 | from google.adk.runners import InMemoryRunner |
15 | 17 | from google.adk.tools import google_search |
16 | 18 |
|
@@ -63,6 +65,36 @@ async def _build_content_from_event(event: dict) -> types.Content: |
63 | 65 | return types.Content(role="user", parts=parts) |
64 | 66 |
|
65 | 67 |
|
| 68 | +async def _populate_session_from_thread( |
| 69 | + *, |
| 70 | + session, |
| 71 | + client, |
| 72 | + channel: str, |
| 73 | + thread_ts: str, |
| 74 | + current_ts: str, |
| 75 | +) -> None: |
| 76 | + """Populate an ADK session with existing Slack thread history.""" |
| 77 | + resp = await client.conversations_replies(channel=channel, ts=thread_ts) |
| 78 | + for m in resp.get("messages", []): |
| 79 | + if m.get("ts") == current_ts: |
| 80 | + continue |
| 81 | + if m.get("bot_id"): |
| 82 | + content = types.Content( |
| 83 | + role="model", |
| 84 | + parts=[types.Part.from_text(text=m.get("text", ""))], |
| 85 | + ) |
| 86 | + author = "model" |
| 87 | + else: |
| 88 | + content = await _build_content_from_event(m) |
| 89 | + author = "user" |
| 90 | + event_obj = Event( |
| 91 | + invocation_id=str(uuid.uuid4()), |
| 92 | + author=author, |
| 93 | + content=content, |
| 94 | + ) |
| 95 | + await session_service.append_event(session=session, event=event_obj) |
| 96 | + |
| 97 | + |
66 | 98 | root_agent = Agent( |
67 | 99 | name="slack_bot_agent", |
68 | 100 | model=MODEL_NAME, |
@@ -100,6 +132,18 @@ async def handle_mention(body, say, client, logger, ack): |
100 | 132 | except Exception: |
101 | 133 | pass |
102 | 134 |
|
| 135 | + session = await session_service.get_session( |
| 136 | + app_name=APP_NAME, user_id=user_id, session_id=thread_ts |
| 137 | + ) |
| 138 | + if session and not session.events: |
| 139 | + await _populate_session_from_thread( |
| 140 | + session=session, |
| 141 | + client=client, |
| 142 | + channel=event["channel"], |
| 143 | + thread_ts=thread_ts, |
| 144 | + current_ts=event["ts"], |
| 145 | + ) |
| 146 | + |
103 | 147 | try: |
104 | 148 | reply_text = "" |
105 | 149 | async for ev in runner.run_async( |
|
0 commit comments