Advertisement
Guest User

Untitled

a guest
Apr 29th, 2025
7
0
12 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const getOpenAIResponse = async (
  2.   query: string,
  3.   instructions?: string,
  4.   previousResponseId?: string,
  5.   functionToolCall?: any,
  6.   functionToolCallResponse?: string
  7. ) => {
  8.   const input =
  9.     functionToolCall && functionToolCallResponse
  10.       ? [
  11.           {
  12.             type: "function_call_output",
  13.             call_id: functionToolCall.call_id,
  14.             output: functionToolCallResponse,
  15.           },
  16.         ]
  17.       : query;
  18.  
  19.   let responseId: string;
  20.  
  21.   const stream = await openai.responses.create({
  22.     model: "gpt-4o-mini",
  23.     stream: true,
  24.     user: "user-123",
  25.     input,
  26.     tools,
  27.     tool_choice: "auto",
  28.     instructions, // I want to omit this ONLY if it's a tool call phase
  29.     previous_response_id: previousResponseId,
  30.   });
  31.  
  32.   return from(stream).pipe(
  33.     mergeMap((event) => {
  34.       if (event.type === "response.created") {
  35.         if (!responseId) {
  36.           responseId = event.response.id;
  37.         }
  38.         return of({ type: "response.created", data: event.response.id });
  39.       }
  40.       if (event.type === "response.function_call_arguments.done") {
  41.         const toolCall = finalToolCalls[event.output_index];
  42.         if (!toolCall) return EMPTY;
  43.         const toolHandler =
  44.           openaiToolHandler[toolCall.name as keyof typeof openaiToolHandler];
  45.         if (!toolHandler) {
  46.           this.logger.error(`Tool call ${toolCall.name} is not supported`);
  47.           return EMPTY;
  48.         }
  49.         const toolCallArguments = JSON.parse(toolCall.arguments);
  50.         const toolCall = {}; // assume extracted
  51.         const toolOutput = {}; // result of calling tool
  52.         return this.getOpenAIResponse(
  53.           query,
  54.           instructions,
  55.           responseId,
  56.           toolCall,
  57.           typeof toolCallResponse === "string"
  58.             ? toolCallResponse
  59.             : JSON.stringify(toolCallResponse)
  60.         );
  61.       }
  62.       return of(event);
  63.     })
  64.   );
  65. };
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement