|
| 1 | +"""Brook API proposal, "An agent Workflow publishes its turns". |
| 2 | +
|
| 3 | +The Workflow creates its two Streams, turns and token deltas, and hands out the turns Stream |
| 4 | +through a ``stream`` query. It publishes each turn with an awaited ``publish``, and passes the |
| 5 | +tokens Stream to the model Activity in its one input object. A create is create-or-get, so the |
| 6 | +run after continue-as-new gets the same Streams. It closes both Streams before it returns, since |
| 7 | +a run's end doesn't close a Stream. |
| 8 | +""" |
| 9 | + |
| 10 | +from __future__ import annotations |
| 11 | + |
| 12 | +import uuid |
| 13 | +from dataclasses import dataclass, field |
| 14 | +from datetime import timedelta |
| 15 | + |
| 16 | +from temporalio import activity, common, workflow |
| 17 | +from temporalio.client import Client |
| 18 | +from temporalio.worker import Worker |
| 19 | + |
| 20 | + |
| 21 | +@dataclass |
| 22 | +class Turn: |
| 23 | + kind: str |
| 24 | + text: str = "" |
| 25 | + |
| 26 | + |
| 27 | +@common.defn(name="turns") |
| 28 | +class Turns(common.StreamDefinition[Turn]): ... |
| 29 | + |
| 30 | + |
| 31 | +@common.defn(name="tokens") |
| 32 | +class Tokens(common.StreamDefinition[str]): ... |
| 33 | + |
| 34 | + |
| 35 | +@dataclass |
| 36 | +class Reply: |
| 37 | + text: str |
| 38 | + tool_calls: list[str] = field(default_factory=list) |
| 39 | + |
| 40 | + |
| 41 | +@dataclass |
| 42 | +class CallModelInput: |
| 43 | + messages: list[str] |
| 44 | + tokens: common.ActivityStream[str] |
| 45 | + |
| 46 | + |
| 47 | +@activity.defn |
| 48 | +async def call_model(input: CallModelInput) -> Reply: |
| 49 | + await input.tokens.publish(*input.messages[-1].split()) |
| 50 | + if len(input.messages) == 1: |
| 51 | + return Reply("", tool_calls=["search"]) |
| 52 | + return Reply("the answer") |
| 53 | + |
| 54 | + |
| 55 | +@activity.defn |
| 56 | +async def run_tool(call: str) -> str: |
| 57 | + return f"{call} result" |
| 58 | + |
| 59 | + |
| 60 | +@workflow.defn |
| 61 | +class Agent: |
| 62 | + @workflow.query |
| 63 | + def stream(self) -> common.WorkflowStream[Turn]: |
| 64 | + # The handle makes no call, so a reader can get it before the create. |
| 65 | + return workflow.stream_handle(Turns) |
| 66 | + |
| 67 | + @workflow.run |
| 68 | + async def run(self, messages: list[str]) -> str: |
| 69 | + # Create-or-get, so a retry or the run after continue-as-new gets the same Streams. |
| 70 | + turns = await workflow.create_stream(Turns, retention=timedelta(days=1)) |
| 71 | + tokens = await workflow.create_stream(Tokens, retention=timedelta(days=1)) |
| 72 | + while True: |
| 73 | + if workflow.info().is_continue_as_new_suggested(): |
| 74 | + workflow.continue_as_new(messages) |
| 75 | + # The publish is one Local Activity. History keeps its offset, not the Turn. |
| 76 | + await turns.publish(Turn("model")) |
| 77 | + reply = await workflow.execute_activity( |
| 78 | + call_model, |
| 79 | + CallModelInput(messages, common.ActivityStream.from_handle(tokens)), |
| 80 | + start_to_close_timeout=timedelta(minutes=5), |
| 81 | + ) |
| 82 | + if not reply.tool_calls: |
| 83 | + await turns.publish(Turn("done", reply.text)) |
| 84 | + # A run's end doesn't close the Streams, so the Workflow closes them. |
| 85 | + await turns.close(result=reply.text) |
| 86 | + await tokens.close() |
| 87 | + return reply.text |
| 88 | + for call in reply.tool_calls: |
| 89 | + messages.append( |
| 90 | + await workflow.execute_activity( |
| 91 | + run_tool, call, start_to_close_timeout=timedelta(minutes=5) |
| 92 | + ) |
| 93 | + ) |
| 94 | + |
| 95 | + |
| 96 | +async def main(client: Client, task_queue: str) -> list[common.Record | common.Closed]: |
| 97 | + async with Worker( |
| 98 | + client, |
| 99 | + task_queue=task_queue, |
| 100 | + workflows=[Agent], |
| 101 | + activities=[call_model, run_tool], |
| 102 | + ): |
| 103 | + handle = await client.start_workflow( |
| 104 | + Agent.run, |
| 105 | + ["find it"], |
| 106 | + id=f"agent-{uuid.uuid4()}", |
| 107 | + task_queue=task_queue, |
| 108 | + ) |
| 109 | + await handle.result() |
| 110 | + # The Workflow hands out its turns Stream, and the client reads it as a ClientStream. |
| 111 | + stream = await handle.query("stream", result_type=common.ClientStream[Turn]) |
| 112 | + return [ |
| 113 | + item |
| 114 | + async for item in stream.subscribe() |
| 115 | + if isinstance(item, (common.Record, common.Closed)) |
| 116 | + ] |
0 commit comments