Skip to content

Commit

Permalink
Validate maxTokens and limit conversation history to maxRecord.
Browse files Browse the repository at this point in the history
  • Loading branch information
huangzhhui committed Feb 6, 2025
1 parent cc3fc15 commit be4f2af
Showing 1 changed file with 5 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/Memory/MessageHistory.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ public function __construct(
protected int $maxTokens = 1000,
array $conversations = []
) {
// @todo validate $maxTokens
if ($maxTokens <= 0) {
throw new InvalidArgumentException('maxTokens must be greater than zero.');
}
}

public function setSystemMessage(MessageInterface $message, string|Stringable $conversationId): static
Expand All @@ -52,8 +54,9 @@ public function addMessages(array|MessageInterface $messages, string|Stringable

foreach ($messages as $message) {
$this->conversations[$conversationId][] = $message;
// Ensure the number of messages does not exceed maxRecord
if (count($this->conversations[$conversationId]) > $this->maxRecord) {
array_shift($this->conversations[$conversationId]);
$this->conversations[$conversationId] = array_slice($this->conversations[$conversationId], -$this->maxRecord);
}
}

Expand Down

0 comments on commit be4f2af

Please sign in to comment.