|
| 1 | +"""Streams API proposal, "An agent Workflow publishes its turns". |
| 2 | +
|
| 3 | +The Workflow creates its two Streams, turns and token deltas, under ids of its choice, and hands |
| 4 | +out the turns Stream's ref through a ``stream`` query. It publishes each turn with an awaited |
| 5 | +``publish``, and passes the tokens ref to the model Activity in its one input object. A run |
| 6 | +after continue-as-new gets the earlier run's refs and creates nothing. It closes both Streams |
| 7 | +before it returns, since 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, streams, workflow |
| 17 | +from temporalio.client import BufferedPublisher, Client |
| 18 | +from temporalio.worker import Worker |
| 19 | + |
| 20 | +MINUTE = timedelta(minutes=1) |
| 21 | + |
| 22 | +Message = str |
| 23 | + |
| 24 | + |
| 25 | +@dataclass |
| 26 | +class Turn: |
| 27 | + kind: str |
| 28 | + text: str | None = None |
| 29 | + |
| 30 | + |
| 31 | +@dataclass |
| 32 | +class Reply: |
| 33 | + text: str |
| 34 | + tool_calls: list[str] = field(default_factory=list) |
| 35 | + |
| 36 | + |
| 37 | +@dataclass |
| 38 | +class CallModelInput: |
| 39 | + messages: list[Message] |
| 40 | + tokens: streams.StreamRef[str] # the ref that the Workflow passes |
| 41 | + |
| 42 | + |
| 43 | +@activity.defn |
| 44 | +async def call_model(input: CallModelInput) -> Reply: |
| 45 | + stream = activity.client().to_stream(input.tokens) # writes as this attempt |
| 46 | + async with BufferedPublisher(stream) as tokens: # batches deltas |
| 47 | + for delta in input.messages[-1].split(): |
| 48 | + tokens.publish(delta) |
| 49 | + if len(input.messages) == 1: |
| 50 | + return Reply("", tool_calls=["search"]) |
| 51 | + return Reply("the answer") |
| 52 | + |
| 53 | + |
| 54 | +@activity.defn |
| 55 | +async def run_tool(call: str) -> Message: |
| 56 | + return f"{call} result" |
| 57 | + |
| 58 | + |
| 59 | +@dataclass |
| 60 | +class AgentInput: |
| 61 | + session_id: str |
| 62 | + messages: list[Message] |
| 63 | + # The run before Continue-as-New sets the refs. |
| 64 | + turns: streams.StreamRef[Turn] | None = None |
| 65 | + tokens: streams.StreamRef[str] | None = None |
| 66 | + |
| 67 | + |
| 68 | +@workflow.defn |
| 69 | +class Agent: |
| 70 | + def __init__(self) -> None: |
| 71 | + self._turns: workflow.WorkflowStream[Turn] | None = None # run creates it |
| 72 | + |
| 73 | + @workflow.query |
| 74 | + def stream(self) -> streams.StreamRef[Turn] | None: # one way to hand it out |
| 75 | + return self._turns.ref if self._turns else None # None before the create |
| 76 | + |
| 77 | + @workflow.run |
| 78 | + async def run(self, input: AgentInput) -> str: |
| 79 | + messages = input.messages |
| 80 | + # A Workflow creates only standalone Streams, under an id of its choice. A run after |
| 81 | + # Continue-as-New gets the earlier run's refs and creates nothing. |
| 82 | + if input.turns and input.tokens: |
| 83 | + self._turns = turns = workflow.to_stream(input.turns) |
| 84 | + tokens = workflow.to_stream(input.tokens) |
| 85 | + else: |
| 86 | + self._turns = turns = await workflow.create_stream[Turn]( |
| 87 | + f"{input.session_id}-turns" |
| 88 | + ) # the default Retention |
| 89 | + # Token deltas matter only to live readers, so they get a short Retention. |
| 90 | + tokens = await workflow.create_stream[str]( |
| 91 | + f"{input.session_id}-tokens", retention=timedelta(hours=1) |
| 92 | + ) |
| 93 | + while True: |
| 94 | + if workflow.info().is_continue_as_new_suggested(): |
| 95 | + workflow.continue_as_new( # forward the refs, so the next run keeps the Streams |
| 96 | + AgentInput(input.session_id, messages, turns.ref, tokens.ref) |
| 97 | + ) |
| 98 | + await turns.publish(Turn("model")) # one Local Activity |
| 99 | + reply = await workflow.execute_activity( |
| 100 | + call_model, |
| 101 | + CallModelInput(messages, tokens.ref), |
| 102 | + start_to_close_timeout=MINUTE, |
| 103 | + ) |
| 104 | + if not reply.tool_calls: |
| 105 | + await turns.publish(Turn("done", reply.text)) |
| 106 | + await turns.close() # the done Turn carries the reply |
| 107 | + await tokens.close() |
| 108 | + return reply.text |
| 109 | + for call in reply.tool_calls: |
| 110 | + messages.append( |
| 111 | + await workflow.execute_activity( |
| 112 | + run_tool, call, start_to_close_timeout=MINUTE |
| 113 | + ) |
| 114 | + ) |
| 115 | + |
| 116 | + |
| 117 | +async def main(client: Client, task_queue: str) -> list[streams.Record[Turn]]: |
| 118 | + async with Worker( |
| 119 | + client, |
| 120 | + task_queue=task_queue, |
| 121 | + workflows=[Agent], |
| 122 | + activities=[call_model, run_tool], |
| 123 | + ): |
| 124 | + session_id = f"session-{uuid.uuid4()}" |
| 125 | + handle = await client.start_workflow( |
| 126 | + Agent.run, |
| 127 | + AgentInput(session_id, ["find it"]), |
| 128 | + id=session_id, |
| 129 | + task_queue=task_queue, |
| 130 | + ) |
| 131 | + await handle.result() |
| 132 | + # The Workflow hands out its turns ref, and the query's client reads the Stream. |
| 133 | + ref = await handle.query(Agent.stream) |
| 134 | + assert ref is not None |
| 135 | + stream = client.to_stream(ref, payload_type=Turn) |
| 136 | + return [r async for r in stream.subscribe() if isinstance(r, streams.Record)] |
0 commit comments