model = $this->model ?? (string) config('agent.openai.model', 'gpt-4o-mini'); $this->temperature = $this->temperature ?? (float) config('agent.openai.temperature', 0.7); $this->topP = $this->topP ?? (float) config('agent.openai.top_p', 1.0); $this->includeUsage = $this->includeUsage ?? (bool) config('agent.openai.include_usage', false); } /** * Builds an OpenAI-compatible Chat Completions payload from AgentContext. * * @param array $options * @return array */ public function build(AgentContext $context, array $options = []): array { $payload = [ 'model' => (string) ($options['model'] ?? $this->model), 'messages' => $this->buildMessages($context), 'stream' => true, ]; if (array_key_exists('temperature', $options)) { $payload['temperature'] = (float) $options['temperature']; } else { $payload['temperature'] = (float) $this->temperature; } if (array_key_exists('top_p', $options)) { $payload['top_p'] = (float) $options['top_p']; } else { $payload['top_p'] = (float) $this->topP; } if (array_key_exists('max_tokens', $options)) { $payload['max_tokens'] = (int) $options['max_tokens']; } if (array_key_exists('stop', $options)) { $payload['stop'] = $options['stop']; } if (array_key_exists('stream_options', $options)) { $payload['stream_options'] = $options['stream_options']; } elseif ($this->includeUsage) { $payload['stream_options'] = ['include_usage' => true]; } if (array_key_exists('response_format', $options)) { $payload['response_format'] = $options['response_format']; } return $payload; } /** * @return array */ private function buildMessages(AgentContext $context): array { $messages = []; if ($context->systemPrompt !== '') { $messages[] = [ 'role' => 'system', 'content' => $context->systemPrompt, ]; } foreach ($context->messages as $message) { $role = $this->mapRole((string) ($message['role'] ?? '')); $content = $message['content'] ?? null; if (! $role || ! is_string($content) || $content === '') { continue; } $messages[] = [ 'role' => $role, 'content' => $content, ]; } return $messages; } private function mapRole(string $role): ?string { return match ($role) { Message::ROLE_USER => 'user', Message::ROLE_AGENT => 'assistant', Message::ROLE_SYSTEM => 'system', default => null, }; } }