https://www.boundaryml.com logo
What's the `runtime` of BAML ?
# questions
w
What's the
runtime
of BAML ? I'm wrting a function like this in my project :
Copy code
typescript
export const chatWithLLMByBAMLSAPUnderOpenAIFormat = <T>(parser:(t:string) => T,req:any) => Effect.tryPromise({
    try:async () => {
        const openai = new OpenAI({
            baseURL:BASEURL,
            apiKey:APIKEY
        })

        /**
         * [example](https://docs.boundaryml.com/guide/baml-advanced/modular-api#openai-chat-completions-api) 
         */
        const res = await openai.chat.completions.create(req)


        const parsedResult = parser(res.choices[0].message.content!)

        return {
            result:parsedResult,
            model:res.model,
            usage:res.usage
        }
    },
    catch:(e) => {
        if(e instanceof BamlValidationError){
            return e
        }
        return openaiErrorMatcher('chatWithLLMByBAMLSAPUnderOpenAIFormat')(e as any)
    }
})
And I pass parser like this:
Copy code
typescript
const eff = chatWithLLMByBAMLSAPUnderOpenAIFormat(b.parse.Memene_Top3RelatedExtract,Sample)
When running code,I met this error:
Copy code
TypeError: Cannot read properties of undefined (reading \'runtime\')\n' +
    '    at Memene_Top3RelatedExtract (D:\Backup\Documents\GitHub\Content-crawling-generation-system\src\baml\baml_client\parser.ts:134:19)\n
And the code here are:
Copy code
typescript
  Memene_Top3RelatedExtract(
      llmResponse: string,
      __baml_options__?: { tb?: TypeBuilder, clientRegistry?: ClientRegistry, env?: Record<string, string | undefined> }
  ): types.Memene_Top3Related {
    try {
      const rawEnv = __baml_options__?.env ? { ...process.env, ...__baml_options__.env } : { ...process.env };
      const env: Record<string, string> = Object.fromEntries(
        Object.entries(rawEnv).filter(([_, value]) => value !== undefined) as [string, string][]
      );
      return this.runtime.parseLlmResponse(
        "Memene_Top3RelatedExtract",
        llmResponse,
        false,
        this.ctxManager.cloneContext(),
        __baml_options__?.tb?.__tb(),
        __baml_options__?.clientRegistry,
        env,
      ) as types.Memene_Top3Related
    } catch (error) {
      throw toBamlError(error);
    }
  }
What things make this error?
I use quokka to inspect my code's running,and I guarantee the error happened at
const parsedResult = parser(res.choices[0].message.content!)
.
It seems like BAML will do validation according to local bamlfiles's dsl string? Oh I got it.DSL stored in
inlinebaml.ts
.Fine design. But why I met runtime no defined error?Seems my code all okay. https://cdn.discordapp.com/attachments/1399663347871518791/1399667909831299082/image.png?ex=6889d5d2&is=68888452&hm=950e1596a7adc238ed43054566810820007d4a09e5c281dd79ca499352248319&
Okay,I get the answer. The reason is javascript's
this binding
.See below code:
Copy code
const t = b.parse.Memene_Top3RelatedExtract("{isRelated:false}")
const parser = b.parse.Memene_Top3RelatedExtract.bind(b.parse) // this will success because it use bind

const result = parser("{isRelated:false}")
If you just use
parse.func
,because the function rely on
this
to get the exact runtime message (I think the major message is the dsl definition):
Copy code
typescript
  Memene_Top3RelatedExtract(
      llmResponse: string,
      __baml_options__?: { tb?: TypeBuilder, clientRegistry?: ClientRegistry, env?: Record<string, string | undefined> }
  ): types.Memene_Top3Related {
    try {
      const rawEnv = __baml_options__?.env ? { ...process.env, ...__baml_options__.env } : { ...process.env };
      const env: Record<string, string> = Object.fromEntries(
        Object.entries(rawEnv).filter(([_, value]) => value !== undefined) as [string, string][]
      );
//here
      return this.runtime.parseLlmResponse(
        "Memene_Top3RelatedExtract",
        llmResponse,
        false,
        this.ctxManager.cloneContext(),
        __baml_options__?.tb?.__tb(),
        __baml_options__?.clientRegistry,
        env,
      ) as types.Memene_Top3Related
    } catch (error) {
      throw toBamlError(error);
    }
  }
So the
this.runtime
will point to undefined because it not derived from a exact instance.
To solve this please use
.bind
.Ah,thanks to JavaScript:The good parts ,the book I read 5 years ago. I finaly know the reason.๐Ÿ˜˜SO funny.
v
Oh thatโ€™s interesting issue you ran into. Glad you were able to self solve!
Yea we have to do funky stuff to make the ergonomics nice from the caller side
Though I suppose we could do it differently and try and make it fit without this as well