websocket.mjs 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import { OpenAI } from "../../index.mjs";
  2. import { OpenAIError } from "../../error.mjs";
  3. import * as Core from "../../core.mjs";
  4. import { OpenAIRealtimeEmitter, buildRealtimeURL, isAzure } from "./internal-base.mjs";
  5. export class OpenAIRealtimeWebSocket extends OpenAIRealtimeEmitter {
  6. constructor(props, client) {
  7. super();
  8. const dangerouslyAllowBrowser = props.dangerouslyAllowBrowser ??
  9. client?._options?.dangerouslyAllowBrowser ??
  10. (client?.apiKey.startsWith('ek_') ? true : null);
  11. if (!dangerouslyAllowBrowser && Core.isRunningInBrowser()) {
  12. throw new 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");
  13. }
  14. client ?? (client = new OpenAI({ dangerouslyAllowBrowser }));
  15. this.url = buildRealtimeURL(client, props.model);
  16. props.onURL?.(this.url);
  17. // @ts-ignore
  18. this.socket = new WebSocket(this.url.toString(), [
  19. 'realtime',
  20. ...(isAzure(client) ? [] : [`openai-insecure-api-key.${client.apiKey}`]),
  21. 'openai-beta.realtime-v1',
  22. ]);
  23. this.socket.addEventListener('message', (websocketEvent) => {
  24. const event = (() => {
  25. try {
  26. return JSON.parse(websocketEvent.data.toString());
  27. }
  28. catch (err) {
  29. this._onError(null, 'could not parse websocket event', err);
  30. return null;
  31. }
  32. })();
  33. if (event) {
  34. this._emit('event', event);
  35. if (event.type === 'error') {
  36. this._onError(event);
  37. }
  38. else {
  39. // @ts-expect-error TS isn't smart enough to get the relationship right here
  40. this._emit(event.type, event);
  41. }
  42. }
  43. });
  44. this.socket.addEventListener('error', (event) => {
  45. this._onError(null, event.message, null);
  46. });
  47. if (isAzure(client)) {
  48. if (this.url.searchParams.get('Authorization') !== null) {
  49. this.url.searchParams.set('Authorization', '<REDACTED>');
  50. }
  51. else {
  52. this.url.searchParams.set('api-key', '<REDACTED>');
  53. }
  54. }
  55. }
  56. static async azure(client, options = {}) {
  57. const token = await client._getAzureADToken();
  58. function onURL(url) {
  59. if (client.apiKey !== '<Missing Key>') {
  60. url.searchParams.set('api-key', client.apiKey);
  61. }
  62. else {
  63. if (token) {
  64. url.searchParams.set('Authorization', `Bearer ${token}`);
  65. }
  66. else {
  67. throw new Error('AzureOpenAI is not instantiated correctly. No API key or token provided.');
  68. }
  69. }
  70. }
  71. const deploymentName = options.deploymentName ?? client.deploymentName;
  72. if (!deploymentName) {
  73. throw new Error('No deployment name provided');
  74. }
  75. const { dangerouslyAllowBrowser } = options;
  76. return new OpenAIRealtimeWebSocket({
  77. model: deploymentName,
  78. onURL,
  79. ...(dangerouslyAllowBrowser ? { dangerouslyAllowBrowser } : {}),
  80. }, client);
  81. }
  82. send(event) {
  83. try {
  84. this.socket.send(JSON.stringify(event));
  85. }
  86. catch (err) {
  87. this._onError(null, 'could not send data', err);
  88. }
  89. }
  90. close(props) {
  91. try {
  92. this.socket.close(props?.code ?? 1000, props?.reason ?? 'OK');
  93. }
  94. catch (err) {
  95. this._onError(null, 'could not close the connection', err);
  96. }
  97. }
  98. }
  99. //# sourceMappingURL=websocket.mjs.map