$turn['role'], 'content' => $turn['content'], ]; } $body = [ 'model' => $this->resolve_model( $options ), 'max_tokens' => $this->max_tokens( $options ), 'temperature' => $this->temperature( $options ), 'messages' => $payload_messages, ]; if ( '' !== $system ) { $body['system'] = $system; } if ( ! empty( $options['tools'] ) ) { $body['tools'] = $this->format_tools( $options['tools'] ); if ( 'required' === ( $options['tool_choice'] ?? '' ) ) { $body['tool_choice'] = [ 'type' => 'any' ]; } } $headers = [ 'x-api-key' => sanitize_text_field( (string) $this->config['api_key'] ), 'anthropic-version' => self::API_VERSION, ]; $result = $this->post_json( self::ENDPOINT, $headers, $body ); if ( ! $result['ok'] ) { return [ 'text' => '', 'tool_calls' => [], 'usage' => [], 'error' => $result['error'], 'raw' => $result['data'] ]; } return $this->normalize_chat( $result['data'] ); } /** * @param array $tools * @return array */ protected function format_tools( array $tools ): array { $out = []; foreach ( $tools as $tool ) { $out[] = [ 'name' => $tool['name'], 'description' => $tool['description'] ?? '', 'input_schema' => self::params_to_json_schema( $tool['params'] ?? [] ), ]; } return $out; } /** * @param mixed $data * @return array */ protected function normalize_chat( $data ): array { $text = ''; $tool_calls = []; foreach ( (array) ( $data['content'] ?? [] ) as $block ) { $btype = $block['type'] ?? ''; if ( 'text' === $btype ) { $text .= (string) ( $block['text'] ?? '' ); } elseif ( 'tool_use' === $btype ) { $tool_calls[] = [ 'name' => (string) ( $block['name'] ?? '' ), 'arguments' => self::decode_arguments( $block['input'] ?? [] ), ]; } } return [ 'text' => $text, 'tool_calls' => $tool_calls, 'usage' => $data['usage'] ?? [], 'error' => null, 'raw' => $data, ]; } }