| export default async function main(args) { |
| |
| const { last_utterance, openaiApiKey } = args.inputVars; |
| |
| |
| if (!last_utterance || !openaiApiKey) { |
| return { |
| next: { path: 'error' }, |
| trace: [{ type: "debug", payload: { message: "Missing required input variable: last_utterance or openaiApiKey" } }] |
| }; |
| } |
| |
| |
| const url = `https://api.openai.com/v1/chat/completions`; |
| |
| |
| const data = { |
| model: "gpt-4o", |
| messages: [ |
| { |
| "role": "system", |
| "content": "You are an assistant. Please respond thoughtfully and informatively." |
| }, |
| { |
| "role": "user", |
| "content": last_utterance |
| } |
| ] |
| }; |
| |
| |
| const config = { |
| method: 'POST', |
| headers: { |
| 'Content-Type': 'application/json', |
| 'Authorization': `Bearer ${openaiApiKey}` |
| }, |
| body: JSON.stringify(data) |
| }; |
| |
| try { |
| |
| const response = await fetch(url, config); |
| |
| |
| if (!response.ok) { |
| throw new Error(`HTTP error! status: ${response.status}`); |
| } |
| |
| |
| const responseBody = await response.json; |
| |
| |
| if (!responseBody || typeof responseBody !== 'object') { |
| throw new Error("Invalid or missing response body from the API"); |
| } |
| |
| |
| const completion = responseBody.choices[0].message.content; |
| |
| |
| return { |
| outputVars: { completion }, |
| next: { path: 'success' }, |
| trace: [ |
| { |
| type: "text", |
| payload: { message: `Received response from GPT-4: ${completion}` } |
| } |
| ] |
| }; |
| } catch (error) { |
| return { |
| next: { path: 'error' }, |
| trace: [{ type: "debug", payload: { message: "Error: " + error.message } }] |
| }; |
| } |
| } |