embeddings.mjs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
  2. import { APIResource } from "../resource.mjs";
  3. import * as Core from "../core.mjs";
  4. export class Embeddings extends APIResource {
  5. /**
  6. * Creates an embedding vector representing the input text.
  7. *
  8. * @example
  9. * ```ts
  10. * const createEmbeddingResponse =
  11. * await client.embeddings.create({
  12. * input: 'The quick brown fox jumped over the lazy dog',
  13. * model: 'text-embedding-3-small',
  14. * });
  15. * ```
  16. */
  17. create(body, options) {
  18. const hasUserProvidedEncodingFormat = !!body.encoding_format;
  19. // No encoding_format specified, defaulting to base64 for performance reasons
  20. // See https://github.com/openai/openai-node/pull/1312
  21. let encoding_format = hasUserProvidedEncodingFormat ? body.encoding_format : 'base64';
  22. if (hasUserProvidedEncodingFormat) {
  23. Core.debug('Request', 'User defined encoding_format:', body.encoding_format);
  24. }
  25. const response = this._client.post('/embeddings', {
  26. body: {
  27. ...body,
  28. encoding_format: encoding_format,
  29. },
  30. ...options,
  31. });
  32. // if the user specified an encoding_format, return the response as-is
  33. if (hasUserProvidedEncodingFormat) {
  34. return response;
  35. }
  36. // in this stage, we are sure the user did not specify an encoding_format
  37. // and we defaulted to base64 for performance reasons
  38. // we are sure then that the response is base64 encoded, let's decode it
  39. // the returned result will be a float32 array since this is OpenAI API's default encoding
  40. Core.debug('response', 'Decoding base64 embeddings to float32 array');
  41. return response._thenUnwrap((response) => {
  42. if (response && response.data) {
  43. response.data.forEach((embeddingBase64Obj) => {
  44. const embeddingBase64Str = embeddingBase64Obj.embedding;
  45. embeddingBase64Obj.embedding = Core.toFloat32Array(embeddingBase64Str);
  46. });
  47. }
  48. return response;
  49. });
  50. }
  51. }
  52. //# sourceMappingURL=embeddings.mjs.map