Skip to content

Commit 13b0ad6

Browse files
committed
fix chat history management
1 parent e5d4fd0 commit 13b0ad6

File tree

2 files changed

+12
-6
lines changed

2 files changed

+12
-6
lines changed

src/Agent/Nodes/ChatNode.php

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -41,19 +41,18 @@ public function __invoke(AIInferenceEvent $event, AgentState $state): StopEvent|
4141
$lastMessage = $chatHistory->getLastMessage();
4242

4343
$this->emit('inference-start', new InferenceStart($lastMessage));
44-
4544
$response = $this->inference($event, $chatHistory->getMessages());
46-
4745
$this->emit('inference-stop', new InferenceStop($lastMessage, $response));
4846

49-
// Add the response to chat history
50-
$this->addToChatHistory($state, $response);
51-
52-
// If the response is a tool call, route to tool execution
47+
// If the response is a tool call, route to the tool node.
48+
// It will be responsible to add the tool call message to the chat history.
5349
if ($response instanceof ToolCallMessage) {
5450
return new ToolCallEvent($response, $event);
5551
}
5652

53+
// Add the final response to chat history (after tool loop)
54+
$this->addToChatHistory($state, $response);
55+
5756
return new StopEvent();
5857
}
5958

src/Agent/Nodes/ToolNode.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
use Generator;
88
use NeuronAI\Agent\AgentState;
9+
use NeuronAI\Agent\ChatHistoryHelper;
910
use NeuronAI\Agent\Events\ToolCallEvent;
1011
use NeuronAI\Chat\Messages\Stream\Chunks\ToolCallChunk;
1112
use NeuronAI\Chat\Messages\Stream\Chunks\ToolResultChunk;
@@ -23,6 +24,8 @@
2324
*/
2425
class ToolNode extends Node
2526
{
27+
use ChatHistoryHelper;
28+
2629
public function __construct(
2730
protected int $maxTries = 10
2831
) {
@@ -34,6 +37,10 @@ public function __construct(
3437
*/
3538
public function __invoke(ToolCallEvent $event, AgentState $state): Generator
3639
{
40+
// Adding the tool call message to the chat history here allows the middleware to hook
41+
// the ToolNode before the tool call is added to the history.
42+
$this->addToChatHistory($state, $event->toolCallMessage);
43+
3744
$toolCallResult = yield from $this->executeTools($event->toolCallMessage, $state);
3845

3946
// Only carry the tool result message as the next turn in the conversation

0 commit comments

Comments
 (0)