history[] = $message; } public function getMessages(): array { return $this->history; } /** * @throws Exception */ public function setHistory(array $history): void { // foreach ($history as $h) { // // 转换 // $role = match ($h['role']) { // 'user' => ChatEnum::Human, // 'assistant' => ChatEnum::Assistant, // 'system' => ChatEnum::System, // 'tool' => ChatEnum::Tool, // default => throw new Exception('Unknown role: '.$h['role']), // }; // // $this->history[] = match ($role) { // ChatEnum::Human => new HumanMessage($h['content']), // ChatEnum::Assistant => new AIMessage($h['content']), // ChatEnum::System => new SystemMessage($h['content']), // ChatEnum::Tool => new ToolMessage($h['content']), // ChatEnum::AssistantChunk => throw new \Exception('To be implemented'), // }; // } $this->history = $history; // dd($this->history); } public function clearHistory(): void { $this->history = []; } public function getForApi(): array { $history = []; foreach ($this->history as $h) { // map roles $role = match ($h->role) { // ChatEnum::Human => 'user', // ChatEnum::Assistant => 'assistant', // ChatEnum::System => 'system', // ChatEnum::Tool => 'tool', ChatEnum::AssistantToolCall => ChatEnum::Assistant, default => $h->role, }; $a = [ 'role' => $role->value, 'content' => $h->content, ]; if (isset($h->tool_calls)) { $a['tool_calls'] = $h->tool_calls; } $history[] = $a; } return $history; } }