1- import { EventSourceParserStream } from "eventsource-parser/stream" ;
2- import type { ChatJob , ChatTool , ModelsJob } from "~/src/job/schema" ;
1+ import type { ChatJob , ModelsJob } from "~/src/job/schema" ;
32import { createHTTPJob } from "~/src/job/http" ;
3+ import {
4+ getApiKey ,
5+ transformToolsToFunctions ,
6+ transformUsageData ,
7+ createStreamingGenerator ,
8+ } from "~/src/job/utils" ;
49
510const BASE_URL = "https://api.openai.com/v1" ;
611
712export const runner = {
813 chat : async ( input : ChatJob [ "input" ] , options ?: ChatJob [ "options" ] ) => {
9- const apiKey = options ?. apiKey || process . env . OPENAI_API_KEY ;
14+ const apiKey = getApiKey ( options , " OPENAI_API_KEY" ) ;
1015
11- const tools = input . tools ?. map ( ( tool : ChatTool ) => ( {
12- type : "function" ,
13- function : {
14- name : tool . name ,
15- description : tool . description ,
16- parameters : tool . input ,
17- } ,
18- } ) ) ;
16+ const tools = transformToolsToFunctions ( input . tools ) ;
1917
2018 const request = new Request ( `${ BASE_URL } /chat/completions` , {
2119 method : "POST" ,
@@ -35,25 +33,7 @@ export const runner = {
3533
3634 return createHTTPJob ( request , async ( response : Response ) => {
3735 if ( input . stream ) {
38- return ( async function * ( ) {
39- const eventStream = response
40- . body ! . pipeThrough ( new TextDecoderStream ( ) )
41- . pipeThrough ( new EventSourceParserStream ( ) ) ;
42- const reader = eventStream . getReader ( ) ;
43-
44- try {
45- for ( ; ; ) {
46- const { done, value } = await reader . read ( ) ;
47- if ( done || value . data === "[DONE]" ) {
48- break ;
49- }
50- const chunk = JSON . parse ( value . data ) ;
51- yield { raw : chunk } ;
52- }
53- } finally {
54- reader . releaseLock ( ) ;
55- }
56- } ) ( ) ;
36+ return createStreamingGenerator ( response ) ;
5737 }
5838
5939 const data = await response . json ( ) ;
@@ -66,13 +46,7 @@ export const runner = {
6646 tool_calls : data . choices [ 0 ] . message . tool_calls ,
6747 } ,
6848 ] ,
69- usage : data . usage
70- ? {
71- promptTokens : data . usage . prompt_tokens ,
72- completionTokens : data . usage . completion_tokens ,
73- totalTokens : data . usage . total_tokens ,
74- }
75- : undefined ,
49+ usage : transformUsageData ( data . usage ) ,
7650 } ;
7751 } ) ;
7852 } ,
@@ -81,7 +55,7 @@ export const runner = {
8155 input ?: ModelsJob [ "input" ] ,
8256 options ?: ModelsJob [ "options" ] ,
8357 ) => {
84- const apiKey = options ?. apiKey || process . env . OPENAI_API_KEY ;
58+ const apiKey = getApiKey ( options , " OPENAI_API_KEY" ) ;
8559
8660 const request = new Request ( `${ BASE_URL } /models` , {
8761 method : "GET" ,
0 commit comments