openai-php / client

⚡️ OpenAI PHP is a supercharged community-maintained PHP API client that allows you to interact with OpenAI API.
MIT License
4.75k stars 491 forks source link

Embeddings\CreateResponse::Fake() creates 2 dimensional vector and unable to replace #122

Closed bcalik closed 1 year ago

bcalik commented 1 year ago

The code below is faking an embedding service, and everything works fine except that the final embedding is created as a 2-dimensional embedding instead of 1536. (text-embedding-ada-002 have 1536 dimensions)

The reason behind this is that the CreateResponseFixture only has a 2-dimensional embedding, and the Fakeable@buildAttributes method uses an approach that only replaces what is given in the Fixture.

So even if you add an array of 1536, it still generates a 2-dimensional array.

use OpenAI\Laravel\Facades\OpenAI;
use OpenAI\Responses\Embeddings\CreateResponse;

OpenAI::fake([
    CreateResponse::fake([
        'object' => 'list',
        'data' => [
            [
                'object' => 'embedding',
                'index' => 0,
                'embedding' => [-0.021845803,0.0034769028,-0.020924518,...,0.006518404],
            ],
        ],
        'usage' => [
            'prompt_tokens' => 3,
            'total_tokens' => 3,
        ],
    ]),
]);

$response = OpenAI::embeddings()->create([
    'model' => 'text-embedding-ada-002',
    'input' => 'test',
]);

dd($response);

Outputs:

OpenAI\Responses\Embeddings\CreateResponse {#1732
  +object: "list"
  +embeddings: array:1 [
    0 => OpenAI\Responses\Embeddings\CreateResponseEmbedding {#1728
      +object: "embedding"
      +index: 0
      +embedding: array:2 [
        0 => -0.021845803
        1 => 0.0034769028
      ]
    }
  ]
  +usage: OpenAI\Responses\Embeddings\CreateResponseUsage {#1733
    +promptTokens: 3
    +totalTokens: 3
  }
}
gehrisandro commented 1 year ago

Thanks @bcalik for raising the issue. Going to have a look within the next days.

Otherwise feel free to PR a fix 🚀

gehrisandro commented 1 year ago

This has been fixed in the latest version: 0.5.3