function-result.php
70 lines
| 1 | <?php |
| 2 | |
| 3 | /** |
| 4 | * Value object representing the result of a function execution |
| 5 | */ |
| 6 | class Meow_MWAI_Data_FunctionResult { |
| 7 | public string $id; |
| 8 | public bool $success; |
| 9 | public $content; |
| 10 | public ?string $error; |
| 11 | |
| 12 | private function __construct( string $id, bool $success, $content, ?string $error = null ) { |
| 13 | $this->id = $id; |
| 14 | $this->success = $success; |
| 15 | $this->content = $content; |
| 16 | $this->error = $error; |
| 17 | } |
| 18 | |
| 19 | /** |
| 20 | * Create a successful result |
| 21 | */ |
| 22 | public static function success( string $id, $content ): self { |
| 23 | return new self( $id, true, $content ); |
| 24 | } |
| 25 | |
| 26 | /** |
| 27 | * Create a failed result |
| 28 | */ |
| 29 | public static function failure( string $id, string $error ): self { |
| 30 | return new self( $id, false, null, $error ); |
| 31 | } |
| 32 | |
| 33 | /** |
| 34 | * Get content as string |
| 35 | */ |
| 36 | public function get_content_string(): string { |
| 37 | if ( $this->error ) { |
| 38 | return 'Error: ' . $this->error; |
| 39 | } |
| 40 | return is_string( $this->content ) ? $this->content : json_encode( $this->content ); |
| 41 | } |
| 42 | |
| 43 | /** |
| 44 | * Format for OpenAI Responses API |
| 45 | */ |
| 46 | public function to_responses_api_format(): array { |
| 47 | return [ |
| 48 | 'type' => 'function_call_output', |
| 49 | 'call_id' => $this->id, |
| 50 | 'output' => $this->get_content_string() |
| 51 | ]; |
| 52 | } |
| 53 | |
| 54 | /** |
| 55 | * Format for Anthropic API |
| 56 | */ |
| 57 | public function to_anthropic_format(): array { |
| 58 | return [ |
| 59 | 'type' => 'tool_result', |
| 60 | 'tool_use_id' => $this->id, |
| 61 | 'content' => [ |
| 62 | [ |
| 63 | 'type' => 'text', |
| 64 | 'text' => $this->get_content_string() |
| 65 | ] |
| 66 | ] |
| 67 | ]; |
| 68 | } |
| 69 | } |
| 70 |