MCPcopy
hub / github.com/mckaywrigley/ai-code-translator / OpenAIStream

Function OpenAIStream

utils/index.ts:74–143  ·  view source on GitHub ↗
(
  inputLanguage: string,
  outputLanguage: string,
  inputCode: string,
  model: string,
  key: string,
)

Source from the content-addressed store, hash-verified

72};
73
74export const OpenAIStream = async (
75 inputLanguage: string,
76 outputLanguage: string,
77 inputCode: string,
78 model: string,
79 key: string,
80) => {
81 const prompt = createPrompt(inputLanguage, outputLanguage, inputCode);
82
83 const system = { role: 'system', content: prompt };
84
85 const res = await fetch(`https://api.openai.com/v1/chat/completions`, {
86 headers: {
87 'Content-Type': 'application/json',
88 Authorization: `Bearer ${key || process.env.OPENAI_API_KEY}`,
89 },
90 method: 'POST',
91 body: JSON.stringify({
92 model,
93 messages: [system],
94 temperature: 0,
95 stream: true,
96 }),
97 });
98
99 const encoder = new TextEncoder();
100 const decoder = new TextDecoder();
101
102 if (res.status !== 200) {
103 const statusText = res.statusText;
104 const result = await res.body?.getReader().read();
105 throw new Error(
106 `OpenAI API returned an error: ${
107 decoder.decode(result?.value) || statusText
108 }`,
109 );
110 }
111
112 const stream = new ReadableStream({
113 async start(controller) {
114 const onParse = (event: ParsedEvent | ReconnectInterval) => {
115 if (event.type === 'event') {
116 const data = event.data;
117
118 if (data === '[DONE]') {
119 controller.close();
120 return;
121 }
122
123 try {
124 const json = JSON.parse(data);
125 const text = json.choices[0].delta.content;
126 const queue = encoder.encode(text);
127 controller.enqueue(queue);
128 } catch (e) {
129 controller.error(e);
130 }
131 }

Callers 1

handlerFunction · 0.90

Calls 1

createPromptFunction · 0.85

Tested by

no test coverage detected