50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298 | class LLMStep(BaseModel):
"""Invokes the language model and wraps the response in a `StepResult[LLMOutput]`.
Emits a `ToolCallingEvent` and routes to `"tool"` when the model requests
tool calls, or emits a `FinalAnswerEvent` and ends the loop otherwise.
Mirrors `ChatLLM`'s own `ainvoke`/`stream` split: `run()` is the whole-response
path via `.ainvoke()`, unchanged regardless of streaming; `stream()` is a
separate method that calls the LLM's `.stream()` API and also emits live
`ContentDeltaEvent`s as the model generates. Callers (the agent loop)
choose which method to invoke based on whether live streaming is safe and
wanted for that call — this class has no streaming flag of its own.
"""
model_config = ConfigDict(arbitrary_types_allowed=True)
name: str = "llm"
llm: SkipValidation[ChatLLM]
system_message: Message
serialized_tools: list[dict] = Field(default_factory=list)
response_format: type[BaseModel] | None = Field(default=None, exclude=True)
def _build_llm_input(self, state: State) -> list[Message]:
return [self.system_message, *state.messages]
def _generation_span(self, llm_input: list[Message], state: State):
return obs.span(
getattr(self.llm, "model", "llm"),
as_type="generation",
model=getattr(self.llm, "model", None),
input=llm_input,
metadata={
"message_count": len(state.messages),
"tool_count": len(self.serialized_tools),
"has_response_format": self.response_format is not None,
},
)
async def _finish(
self,
raw: str,
tool_calls: list[ToolCall],
reasoning: str | None,
stream_id: str | None,
):
"""Yields the optional `ReasoningEvent`, terminal event, and `StepResult`
shared by `run()` and `stream()` once a response has been fully collected.
"""
if reasoning:
yield ReasoningEvent(content=reasoning, stream_id=stream_id)
event, transition = _terminal_event(raw, tool_calls, stream_id=stream_id)
yield event
yield StepResult(
output=LLMOutput(raw=raw, tool_calls=tuple(tool_calls)),
transition=transition,
)
async def run(
self,
state: State,
ctx: InvocationContext | None,
):
llm_input: list[Message] = self._build_llm_input(state)
async with self._generation_span(llm_input, state) as span:
response: ChatLLMResponse = await self.llm.ainvoke(
llm_input,
ctx=ctx,
tools=self.serialized_tools or None,
response_format=self.response_format,
)
raw: str = response.message.content or ""
tool_calls: list[ToolCall] = response.tool_calls or []
update_payload: dict[str, object] = {
"output": raw,
"metadata": {
"tool_call_count": len(tool_calls),
},
}
response_model = getattr(response, "model", None)
if response_model is not None:
update_payload["model"] = response_model
usage_details = getattr(response, "usage", None)
if usage_details is not None:
update_payload["usage"] = usage_details
span.update(**update_payload)
reasoning = getattr(response, "reasoning", None)
async for item in self._finish(raw, tool_calls, reasoning, stream_id=None):
yield item
async def stream(
self,
state: State,
ctx: InvocationContext | None,
):
"""Live token-level counterpart to `run()`.
Calls the LLM's `.stream()` API, yielding `ContentDeltaEvent`s as
fragments arrive, then the same terminal event/`StepResult` sequence
as `run()` would produce for the same response, correlated via
`stream_id`.
"""
llm_input: list[Message] = self._build_llm_input(state)
stream_id = str(uuid4())
async with self._generation_span(llm_input, state) as span:
raw, tool_calls, reasoning = "", [], None
async for (
delta_event,
raw_frag,
reasoning_frag,
tool_call,
) in self._stream_deltas(llm_input, ctx, stream_id):
if delta_event is not None:
yield delta_event
raw += raw_frag
if reasoning_frag:
reasoning = (reasoning or "") + reasoning_frag
if tool_call is not None:
tool_calls.append(tool_call)
# ChatLLMStreamChunk carries no usage/model fields, unlike
# ChatLLMResponse, so those span attributes are unavailable here.
span.update(output=raw, metadata={"tool_call_count": len(tool_calls)})
async for item in self._finish(raw, tool_calls, reasoning, stream_id=stream_id):
yield item
async def _stream_deltas(
self,
llm_input: list[Message],
ctx: InvocationContext | None,
stream_id: str,
):
"""Consume the LLM's stream, yielding (delta_event, raw, reasoning, tool_call) tuples.
`raw`/`reasoning` are the fragment to accumulate for this chunk (usually
empty); `tool_call` is a finished `ToolCall` once its argument stream
closes (detected by a change of tool-call index or end of stream), None
otherwise. Fan-in for the final index happens in `stream()` once the
loop below and this generator both finish.
"""
reasoning_started = False
content_started = False
tool_frags: dict[int, _ToolCallFragment] = {}
# Some providers tag every parallel tool call with the same provider-reported index instead of incrementing it, delivering each as one complete chunk (its own id + full arguments). This dict maps those provider indices to the next available index for our own use, so we can yield a separate `ContentDeltaEvent` for each tool call.
resolved_index_for: dict[int, int] = {}
next_resolved_index = 0
async for chunk in self.llm.stream(
messages=llm_input,
ctx=ctx,
tools=self.serialized_tools or None,
response_format=self.response_format,
):
if chunk.reasoning_delta:
yield (
ContentDeltaEvent(
target_kind="reasoning",
delta=chunk.reasoning_delta,
stream_id=stream_id,
is_first=not reasoning_started,
),
"",
chunk.reasoning_delta,
None,
)
reasoning_started = True
if chunk.delta.delta:
yield (
ContentDeltaEvent(
target_kind="content",
delta=chunk.delta.delta,
stream_id=stream_id,
is_first=not content_started,
),
chunk.delta.delta,
"",
None,
)
content_started = True
if chunk.tool_calls:
provider_idx = chunk.tool_calls["index"]
incoming_id = chunk.tool_calls.get("id")
if provider_idx not in resolved_index_for:
idx = next_resolved_index
next_resolved_index += 1
resolved_index_for[provider_idx] = idx
else:
idx = resolved_index_for[provider_idx]
existing_frag = tool_frags.get(idx)
if (
existing_frag is not None
and existing_frag.id is not None
and incoming_id
and incoming_id != existing_frag.id
):
idx = next_resolved_index
next_resolved_index += 1
resolved_index_for[provider_idx] = idx
frag: _ToolCallFragment = tool_frags.setdefault(
idx, _ToolCallFragment()
)
is_first_frag = frag.id is None and bool(incoming_id)
if chunk.tool_calls.get("id"):
frag.id = chunk.tool_calls["id"]
if chunk.tool_calls.get("name"):
frag.name = chunk.tool_calls["name"]
args_delta = chunk.tool_calls.get("arguments") or ""
frag.arguments += args_delta
yield (
ContentDeltaEvent(
target_kind="tool_calling",
delta=args_delta,
stream_id=stream_id,
is_first=is_first_frag,
tool_call_index=idx,
tool_call_id=frag.id if is_first_frag else None,
tool_call_name=frag.name if is_first_frag else None,
),
"",
"",
None,
)
for frag in tool_frags.values():
yield (
None,
"",
"",
ToolCall(
id=frag.id or "",
function=ToolFunction(
name=frag.name or "", arguments=frag.arguments
),
),
)
|