|
| 1 | +import asyncio |
| 2 | + |
| 3 | +from google.adk import Agent |
| 4 | +from google.adk.runners import InMemoryRunner |
| 5 | +from google.adk.utils.context_utils import Aclosing |
| 6 | +from google.genai import types |
| 7 | +from temporalio import workflow |
| 8 | +from temporalio.contrib.google_adk_agents import TemporalModel |
| 9 | + |
| 10 | + |
| 11 | +# @@@SNIPSTART google-adk-agents-chatbot-agent-workflow |
| 12 | +@workflow.defn |
| 13 | +class ChatbotAgentWorkflow: |
| 14 | + def __init__(self) -> None: |
| 15 | + self._ready = False |
| 16 | + self._runner: InMemoryRunner | None = None |
| 17 | + self._session_id: str | None = None |
| 18 | + |
| 19 | + @workflow.run |
| 20 | + async def run(self) -> str: |
| 21 | + agent = Agent( |
| 22 | + name="chatbot_agent", |
| 23 | + model=TemporalModel("gemini-2.5-flash"), |
| 24 | + instruction="You are a helpful assistant.", |
| 25 | + ) |
| 26 | + |
| 27 | + # The plugin points ADK's session-id generation at workflow.uuid4(), so |
| 28 | + # creating a session here is replay-safe. |
| 29 | + self._runner = InMemoryRunner(agent=agent, app_name="chatbot_app") |
| 30 | + session = await self._runner.session_service.create_session( |
| 31 | + app_name="chatbot_app", user_id="user" |
| 32 | + ) |
| 33 | + self._session_id = session.id |
| 34 | + self._ready = True |
| 35 | + |
| 36 | + # Block forever to stay alive serving update turns; the client |
| 37 | + # terminates the workflow when the user quits. |
| 38 | + return await asyncio.Future() |
| 39 | + |
| 40 | + @workflow.update |
| 41 | + async def message(self, message: str) -> str: |
| 42 | + # An update can arrive before run() has created the runner and session, |
| 43 | + # so wait until they are ready before using them. |
| 44 | + await workflow.wait_condition(lambda: self._ready) |
| 45 | + assert self._runner is not None and self._session_id is not None |
| 46 | + |
| 47 | + final_text = "" |
| 48 | + async with Aclosing( |
| 49 | + self._runner.run_async( |
| 50 | + user_id="user", |
| 51 | + session_id=self._session_id, |
| 52 | + new_message=types.Content( |
| 53 | + role="user", parts=[types.Part(text=message)] |
| 54 | + ), |
| 55 | + ) |
| 56 | + ) as agen: |
| 57 | + async for event in agen: |
| 58 | + if event.content and event.content.parts: |
| 59 | + for part in event.content.parts: |
| 60 | + if part.text: |
| 61 | + final_text = part.text |
| 62 | + |
| 63 | + return final_text |
| 64 | + |
| 65 | + @message.validator |
| 66 | + def validate_message(self, message: str) -> None: |
| 67 | + pass |
| 68 | + |
| 69 | + |
| 70 | +# @@@SNIPEND |
0 commit comments