websocket.js 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. "use strict";
  2. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  3. if (k2 === undefined) k2 = k;
  4. var desc = Object.getOwnPropertyDescriptor(m, k);
  5. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
  6. desc = { enumerable: true, get: function() { return m[k]; } };
  7. }
  8. Object.defineProperty(o, k2, desc);
  9. }) : (function(o, m, k, k2) {
  10. if (k2 === undefined) k2 = k;
  11. o[k2] = m[k];
  12. }));
  13. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  14. Object.defineProperty(o, "default", { enumerable: true, value: v });
  15. }) : function(o, v) {
  16. o["default"] = v;
  17. });
  18. var __importStar = (this && this.__importStar) || function (mod) {
  19. if (mod && mod.__esModule) return mod;
  20. var result = {};
  21. if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  22. __setModuleDefault(result, mod);
  23. return result;
  24. };
  25. Object.defineProperty(exports, "__esModule", { value: true });
  26. exports.OpenAIRealtimeWebSocket = void 0;
  27. const index_1 = require("../../index.js");
  28. const error_1 = require("../../error.js");
  29. const Core = __importStar(require("../../core.js"));
  30. const internal_base_1 = require("./internal-base.js");
  31. class OpenAIRealtimeWebSocket extends internal_base_1.OpenAIRealtimeEmitter {
  32. constructor(props, client) {
  33. super();
  34. const dangerouslyAllowBrowser = props.dangerouslyAllowBrowser ??
  35. client?._options?.dangerouslyAllowBrowser ??
  36. (client?.apiKey.startsWith('ek_') ? true : null);
  37. if (!dangerouslyAllowBrowser && Core.isRunningInBrowser()) {
  38. throw new error_1.OpenAIError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\n\nYou can avoid this error by creating an ephemeral session token:\nhttps://platform.openai.com/docs/api-reference/realtime-sessions\n");
  39. }
  40. client ?? (client = new index_1.OpenAI({ dangerouslyAllowBrowser }));
  41. this.url = (0, internal_base_1.buildRealtimeURL)(client, props.model);
  42. props.onURL?.(this.url);
  43. // @ts-ignore
  44. this.socket = new WebSocket(this.url.toString(), [
  45. 'realtime',
  46. ...((0, internal_base_1.isAzure)(client) ? [] : [`openai-insecure-api-key.${client.apiKey}`]),
  47. 'openai-beta.realtime-v1',
  48. ]);
  49. this.socket.addEventListener('message', (websocketEvent) => {
  50. const event = (() => {
  51. try {
  52. return JSON.parse(websocketEvent.data.toString());
  53. }
  54. catch (err) {
  55. this._onError(null, 'could not parse websocket event', err);
  56. return null;
  57. }
  58. })();
  59. if (event) {
  60. this._emit('event', event);
  61. if (event.type === 'error') {
  62. this._onError(event);
  63. }
  64. else {
  65. // @ts-expect-error TS isn't smart enough to get the relationship right here
  66. this._emit(event.type, event);
  67. }
  68. }
  69. });
  70. this.socket.addEventListener('error', (event) => {
  71. this._onError(null, event.message, null);
  72. });
  73. if ((0, internal_base_1.isAzure)(client)) {
  74. if (this.url.searchParams.get('Authorization') !== null) {
  75. this.url.searchParams.set('Authorization', '<REDACTED>');
  76. }
  77. else {
  78. this.url.searchParams.set('api-key', '<REDACTED>');
  79. }
  80. }
  81. }
  82. static async azure(client, options = {}) {
  83. const token = await client._getAzureADToken();
  84. function onURL(url) {
  85. if (client.apiKey !== '<Missing Key>') {
  86. url.searchParams.set('api-key', client.apiKey);
  87. }
  88. else {
  89. if (token) {
  90. url.searchParams.set('Authorization', `Bearer ${token}`);
  91. }
  92. else {
  93. throw new Error('AzureOpenAI is not instantiated correctly. No API key or token provided.');
  94. }
  95. }
  96. }
  97. const deploymentName = options.deploymentName ?? client.deploymentName;
  98. if (!deploymentName) {
  99. throw new Error('No deployment name provided');
  100. }
  101. const { dangerouslyAllowBrowser } = options;
  102. return new OpenAIRealtimeWebSocket({
  103. model: deploymentName,
  104. onURL,
  105. ...(dangerouslyAllowBrowser ? { dangerouslyAllowBrowser } : {}),
  106. }, client);
  107. }
  108. send(event) {
  109. try {
  110. this.socket.send(JSON.stringify(event));
  111. }
  112. catch (err) {
  113. this._onError(null, 'could not send data', err);
  114. }
  115. }
  116. close(props) {
  117. try {
  118. this.socket.close(props?.code ?? 1000, props?.reason ?? 'OK');
  119. }
  120. catch (err) {
  121. this._onError(null, 'could not close the connection', err);
  122. }
  123. }
  124. }
  125. exports.OpenAIRealtimeWebSocket = OpenAIRealtimeWebSocket;
  126. //# sourceMappingURL=websocket.js.map