1
- const http = require ( 'http ' ) ;
1
+ const https = require ( 'https ' ) ;
2
2
const _ = require ( 'lodash' ) ;
3
3
const axios = require ( 'axios' ) ;
4
4
const { } = require ( '../utils/cmdPrint' ) ;
@@ -17,14 +17,15 @@ function extractGPTMessageFromStreamData(input) {
17
17
18
18
function setOptions ( { protocol, hostname, port, path, method, headers} ) {
19
19
let options = {
20
- protocol : protocol || 'http ' ,
21
- hostname : hostname || 'localhost ' ,
20
+ protocol : protocol || 'https ' ,
21
+ hostname : hostname || 'api.pythagora.io ' ,
22
22
port : port || process . env . PORT ,
23
23
path : path || '/' ,
24
24
method : method || 'POST' ,
25
25
headers : headers || {
26
26
'Content-Type' : 'application/json' ,
27
- 'Authorization' : 'Bearer ' + process . env . OPENAI_API_KEY
27
+ 'apikey' : process . env . OPENAI_API_KEY || process . env . PYTHAGORA_API_KEY ,
28
+ 'apikeytype' : process . env . OPENAI_API_KEY ? 'openai' : 'pythagora'
28
29
} ,
29
30
} ;
30
31
@@ -36,10 +37,16 @@ async function makeRequest(data, options) {
36
37
let gptResponse = '' ;
37
38
38
39
return new Promise ( ( resolve , reject ) => {
39
- const req = http . request ( _ . omit ( options , [ 'protocol' ] ) , function ( res ) {
40
+ const req = https . request ( _ . omit ( options , [ 'protocol' ] ) , function ( res ) {
40
41
res . on ( 'data' , ( chunk ) => {
41
42
try {
42
- let receivedMessages = extractGPTMessageFromStreamData ( chunk . toString ( ) ) ;
43
+ let stringified = chunk . toString ( ) ;
44
+ try {
45
+ let json = JSON . parse ( stringified ) ;
46
+ if ( json . error ) gptResponse = json . error ;
47
+ return ;
48
+ } catch ( e ) { }
49
+ let receivedMessages = extractGPTMessageFromStreamData ( stringified ) ;
43
50
receivedMessages . forEach ( rm => {
44
51
let content = _ . get ( rm , 'choices.0.delta.content' ) ;
45
52
if ( content ) {
@@ -51,6 +58,8 @@ async function makeRequest(data, options) {
51
58
} catch ( e ) { }
52
59
} ) ;
53
60
res . on ( 'end' , async ( ) => {
61
+ if ( res . statusCode >= 400 ) throw new Error ( `Response status code: ${ res . statusCode } .` ) ;
62
+ if ( gptResponse . message ) throw new Error ( `Error: ${ gptResponse . message } . Code: ${ gptResponse . code } ` ) ;
54
63
gptResponse = cleanupGPTResponse ( gptResponse ) ;
55
64
resolve ( gptResponse ) ;
56
65
} ) ;
0 commit comments