Sample code for 30+ languages & platforms
PureBasic

Streaming AI with Automatic JavaScript AI Tool Function Calling

See more AI Examples

Demonstrates how to get AI responses in streaming mode, including possible tool function calling using Chilkat with embedded Chilkat.Js JavaScript. Automatic JavaScript tool calls are characterized by:
  • Tool function implementations are in JavaScript.
  • The JavaScript also provides a tool registry and permissions.
  • The JavaScript runs embedded within your application using Chilkat.Js.
  • Tool calls are handled entirely within Chilkat. Your application does not need to manually check for function calls in the AI response. Internal to the Ask function, Chilkat will handle function calls by calling your registered JavaScript tools and will send results back to the AI model until the final response is received.

Chilkat PureBasic Downloads

PureBasic
IncludeFile "CkStringBuilder.pb"
IncludeFile "CkAi.pb"

Procedure ChilkatExample()

    success.i = 0

    ; ----------------------------------------------------------------------------------
    ; The Javascript file loaded here is shown at the bottom of this page.
    ; -----------------------------------------------------------------------------------

    sbJs.i = CkStringBuilder::ckCreate()
    If sbJs.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkStringBuilder::ckLoadFile(sbJs,"qa_data/js_tools/horoscope_tools.js","utf-8")
    If success = 0
        Debug CkStringBuilder::ckLastErrorText(sbJs)
        CkStringBuilder::ckDispose(sbJs)
        ProcedureReturn
    EndIf

    ai.i = CkAi::ckCreate()
    If ai.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    ; Register the tools that will be made available to the AI.
    evalOnly.i = 0
    allowAllKeyword.i = 1
    CkAi::ckRegisterJsTools(ai,sbJs,evalOnly,allowAllKeyword)

    ; The provider can be "openai", "google", "claude", "grok", "mistral", "custom", etc.
    CkAi::setCkProvider(ai, "openai")
    ; Use your provider's API key.
    CkAi::setCkApiKey(ai, "MY_API_KEY")
    ; Choose a model.
    CkAi::setCkModel(ai, "gpt-5-mini")

    ; Tool function calling must always occur within a conversation.
    conversation_name.s = "convo_astrology"
    sysMessage.s = "You are a helpful astrologer"
    devMessage.s = "Respond only with markdown."
    CkAi::ckNewConvo(ai,conversation_name,sysMessage,devMessage)

    ; Provide inputs
    CkAi::ckInputAddText(ai,"What is my horoscope? I am an Aquarius.")

    ; Get the response in streaming mode.
    CkAi::setCkStreaming(ai, 1)

    ; In streaming mode, if we receive an AI event that is a request for tool use,
    ; we'll need to make the call to the JavaScript and then continue with a followup Ask,
    ; until the final response is received.

    sbEventName.i = CkStringBuilder::ckCreate()
    If sbEventName.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    sbDelta.i = CkStringBuilder::ckCreate()
    If sbDelta.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    sbFullResponse.i = CkStringBuilder::ckCreate()
    If sbFullResponse.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    ; When PollAi returns with an event, it's highly unlikely the
    ; call to NextAiEvent does not immediately return.  Setting a max
    ; timeout is just a precaution..
    maxWaitMs.i = 5000

    finished.i = 0
    numAsks.i = 0
    ; Set a max # of followup Asks to prevent any unexpected infinite looping.
    While Not finished AND (numAsks < 10)

        ; Send the request to the AI model.
        success = CkAi::ckAsk(ai,"text")
        If success = 0
            Debug CkAi::ckLastErrorText(ai)
            CkStringBuilder::ckDispose(sbJs)
            CkAi::ckDispose(ai)
            CkStringBuilder::ckDispose(sbEventName)
            CkStringBuilder::ckDispose(sbDelta)
            CkStringBuilder::ckDispose(sbFullResponse)
            ProcedureReturn
        EndIf

        madeFunctionCalls.i = 0
        streamingDone.i = 0

        While Not streamingDone
            result.i = CkAi::ckPollAi(ai,0)
            If result < 0
                Debug CkAi::ckLastErrorText(ai)
                Debug "Failed."
                CkStringBuilder::ckDispose(sbJs)
                CkAi::ckDispose(ai)
                CkStringBuilder::ckDispose(sbEventName)
                CkStringBuilder::ckDispose(sbDelta)
                CkStringBuilder::ckDispose(sbFullResponse)
                ProcedureReturn
            EndIf

            If result > 0
                ; We have an event..
                success = CkAi::ckNextAiEvent(ai,maxWaitMs,sbEventName,sbDelta)
                If success = 0
                    Debug CkAi::ckLastErrorText(ai)
                    CkStringBuilder::ckDispose(sbJs)
                    CkAi::ckDispose(ai)
                    CkStringBuilder::ckDispose(sbEventName)
                    CkStringBuilder::ckDispose(sbDelta)
                    CkStringBuilder::ckDispose(sbFullResponse)
                    ProcedureReturn
                EndIf

                ; Is this an event where the AI is requesting a function call?
                If CkStringBuilder::ckContentsEqual(sbEventName,"js_function_call",1)
                    ; Call the JavaScript function.
                    ; We don't need to find the exact function and make the call.  
                    ; We can simply pass the sbDelta (which contains information about the function to be called and the args).
                    ; Chilkat will find the registered JavaScript function, call it, and add the results to the conversation.
                    ; We indicate that function calls were made, which results in a followup Ask (in the outer loop).
                    success = CkAi::ckStreamingJsToolCall(ai,sbDelta)
                    If success = 0
                        ; The JS function call failed.
                        streamingDone = 1
                    Else
                        madeFunctionCalls = 1
                    EndIf

                Else
                    If Not CkStringBuilder::ckContentsEqual(sbEventName,"empty",1)
                        CkStringBuilder::ckAppendSb(sbFullResponse,sbDelta)

                        If CkStringBuilder::ckContentsEqual(sbEventName,"null_terminator",1)
                            streamingDone = 1
                        EndIf

                    EndIf

                EndIf

            Else
                ; No event arrived, so wait a short time rather than spin in a loop..
                CkAi::ckSleepMs(ai,100)
            EndIf

        Wend

        If Not madeFunctionCalls
            finished = 1
        EndIf

        numAsks = numAsks + 1
    Wend

    Debug "Full Response:"
    Debug CkStringBuilder::ckGetAsString(sbFullResponse)


    CkStringBuilder::ckDispose(sbJs)
    CkAi::ckDispose(ai)
    CkStringBuilder::ckDispose(sbEventName)
    CkStringBuilder::ckDispose(sbDelta)
    CkStringBuilder::ckDispose(sbFullResponse)


    ProcedureReturn
EndProcedure