https://www.boundaryml.com logo
Retrieval-Augmented Generation (RAG) | B...
# questions
p
In the RAG example in the BAML docs, https://docs.boundaryml.com/examples/prompt-engineering/retrieval-augmented-generation I'm finding a frequent failure case, where there's an attempt to rewrite the question, then that fails, and the BAML call throws an exception. I'd rather handle this in two steps: 1. Attempt a question rewrite, i.e., a query expansion 2. If it fails, then run RAG with the original query But it seems like to do this I'd need to have a RAG prompt which disables any question rewrites? Have you seen any approach like this? Is there a good way in the prompts to to disable rewrites / query expansions? Or does the failure case above imply lots of prompt twiddling in my near future? πŸ™‚
p
Hey Paco, nice to see you here!
When you say "attempt to rewrite the question", do you mean that your prompt is asking for the LLM to rewrite the question prior to answering?
Have you included any chain of thought prompting in the prompt? Or is it the exact same prompt as per the docs example
In all my time using BAML, I've never seen it fail with an error on a simple prompt like that, so I'm extra curious πŸ˜…
Which LLM, what is the retrieval mechanism, is it the exact same prompt and fake vector store as per the example, et.c
p
Yes, using the RAG code I linked above, using a
llama3:latest
model via Ollama. The
question
given as the input parameter to
b.RAG(question, context)
almost always gets rewritten. For example:
Copy code
ic| question: 'how many people were in the study?'
ic| response: Response(question='What is the association between processed red meat and dementia?', answer='According to the study, eating a daily average of one-quarter or more of a serving of processed red meats (roughly two slices of bacon, one and half slices of bologna, or a hot dog), compared to those consuming a minimal amount (less than one-tenth a serving each day), had a 13 percent higher risk of developing dementia.')
**Q1**: I'm asking if anyone has examples of prompts which can disable question rewriting?
Whenever the rewritten question is an empty string then BAML throws an exception. This started happening this morning, though I hadn't seen in previously. The exceptions show the
Response
object embedded, and there's generally an answer which is usable. I may just try to trap these exceptions and parse them, but I'd really REALLY like to disable question rewrites. Overall, having to trap and parse exceptions seems to be defeating the point of using BAML? And I'd really like to use BAML πŸ™‚
p
Could you share the prompt?
p
FWIW, the GraphRAG elements of this particular project are working correctly, so the chunk list presented as
context
looks good. However the question rewriting causes the results to be relatively poor.
p
I wonder if this behaviour is specific to Llama3
Could you try that with literally any other ollama model? Say
gemma3:12b
p
Exact same as in the link above:
Copy code
function RAG(question: string, context: string) -> Response {
  client "openai/gpt-4o-mini"
  prompt #"
    Answer the question in full sentences using the provided context.
    Do not make up an answer. If the information is not provided in the context, say so clearly.
    
    QUESTION: {{ question }}
    RELEVANT CONTEXT: {{ context }}
    {{ ctx.output_format }}
    RESPONSE:
  "#
}
p
If llama3's behaviour is different from other models, that's definitely worth looking into more deeply. Interesting..
p
Yeah, my next step was going to be to try various other models to compare ... Phi-4, etc.
p
The question should never be rewritten by the model unless you explicitly asked for that
p
.... AND .... this wasn't happening as of last night. Only started happening today, around 08:00 PT
maybe Ollama updated something, but then if I hadn't pulled a new model would that even change?
p
yeah, that can't be it
p
i'll have
gemma
downloaded within the hour to compare
p
I'm actually curious enough to give it a try right now
Will also try
llama3:latest
on my end with ollama
what version of baml are you on Paco?
Latest on I hope?
p
baml_py-0.204
thank you for testing!
p
Ok for simple cases llama3 is working well
Do you have any sample data I could test?
Copy code
rs
class Response {
  question string
  answer string
}

function RAGTest(question: string, context: string) -> Response {
  client OllamaLlama3
  prompt #"
    Answer the question in full sentences using the provided context.
    Do not make up an answer. If the information is not provided in the context, say so clearly.
    
    QUESTION: {{ question }}
    RELEVANT CONTEXT: {{ context }}
    {{ ctx.output_format }}
    RESPONSE:
  "#
}

test RAG1 {
    functions [RAGTest]
    args {
        question "How many people were in the study?"
        context "According to the study, eating a daily average of one-quarter or more of a serving of processed red meats (roughly two slices of bacon, one and half slices of bologna, or a hot dog), compared to those consuming a minimal amount (less than one-tenth a serving each day), had a 13 percent higher risk of developing dementia."
    }
}

test RAG2 {
    functions [RAGTest]
    args {
        question "What is the association between processed red meat and dementia?"
        context "According to the study, eating a daily average of one-quarter or more of a serving of processed red meats (roughly two slices of bacon, one and half slices of bologna, or a hot dog), compared to those consuming a minimal amount (less than one-tenth a serving each day), had a 13 percent higher risk of developing dementia."
    }
}
Copy code
json
{
  "question": "How many people were in the study?", 
  "answer": "This information is not provided in the given context.", 
}
Copy code
json
{
  "question": "What is the association between processed red meat and dementia?",
  "answer": "According to the study, eating a daily average of one-quarter or more of a serving of processed red meats had a 13 percent higher risk of developing dementia compared to those consuming a minimal amount."
}
Seems like there are no hallucinations, and it correctly answers that there isn't enough context in the first question
From this icecream trace, it's not clear how the question is being appended to the
Response
object on the Python side. But from the BAML end, there is no query rewriting happening
p
In the lastest
main
branch of https://github.com/DerwenAI/strwythura if you run
demo.py
then it generates data.
p
Could you also link to the Python code that's processing the BAML side of things?
p
I was testing an update to the
rag.py
workflow this morning, when I ran into all the question rewrites suddenly, and exceptions. This test code isn't in a state to check in.
Though if you look at the
rag.py
script, that is calling BAML.
It's a simple call to
b.RAG(question, context)
p
What's blowing my mind is that the question you entered is drastically different from the question in the
Response
object
p
FWIW, this version is a relatively vanilla RAG, not the GraphRAG impl
p
that makes no sense lol
Yes, vanilla RAG makes sense πŸ™‚
One suggestion I have @Paco Nathan
Try updating the BAML tests in
baml_src/rag.baml
with these exact same questions and contexts
p
Yes, and I've tried lots of variants of modifying prompts: "Use exactly the question as stated. Do not attempt to rewrite the question." etc.
p
And run the tests in pure baml
See whether the same behaviour repeats
The base prompt should work imo
p
Ah, good approach, thanks!
p
no need to modify
Worth narrowing down on whether this is a bug in the Python code
Oh and btw, update your client to this (model is a string,
llama3:latest
):
Copy code
client<llm> Llama3Client {
  provider "openai-generic"
  options {
    base_url "http://localhost:11434/v1"
    model "llama3:latest"
  }
}
I wonder if its the llama3 spec that's pulling some old out of date llama3
p
Could be. This makes more sense than anything else.
Okay, now here's an example of a question rewrite producing a null question, but then no BAML exception:
Copy code
ic| question: 'does red meat cause alzheimer's disease?'
ic| response: Response(question='', answer='')
p
Empty question should work, because there's no context
Is this with the updated client
llama3:latest
as above?
Oh ok WAIT
Copy code
rs
test RAG3 {
    functions [RAGTest]
    args {
        question ""
        context "According to the study, eating a daily average of one-quarter or more of a serving of processed red meats (roughly two slices of bacon, one and half slices of bologna, or a hot dog), compared to those consuming a minimal amount (less than one-tenth a serving each day), had a 13 percent higher risk of developing dementia."
    }
}
Copy code
json
{
  "question": "According to the study, eating a daily average of one-quarter or more of a serving of processed red meats (roughly two slices of bacon, one and half slices of bologna, or a hot dog), compared to those consuming a minimal amount (less than one-tenth a serving each day), had a ...",
  "answer": "13 percent higher risk of developing dementia"
}
llama3 hallucinated a question!!!
trying with
gemma3:12b
now
This is really bad
p
I'm a half hour away from having the
gemma
model to try
p
Hahaha I'll report back in 2 min
p
Yeah, this is sort of the opposite of what I was trying to get accomplished ... probably due to Llama πŸ™‚ but use of BAML is awesome
p
Yes, it's just so easy to get rapid feedback, before even a line of Python is written. What Vaibhav has been saying since day 1 😁
I really think llama is a crap model 🀣
wow, a hallucinated question, that's a first for me
hallucinated answer, I can at least forgive the model for that
p
Well, at least I feel much better now. Thank you! (I wasn't hallucinating, probably)
p
Okay SAME behaviour with
gemma3:12b
πŸ‘€
I think this is a BAML bug?
cc @aaronv (BAML)
To the RAG function, empty context is passed. Left is the input, right is the response
Now the right is parsed response
p
WOw, really?
p
LLM hallucinates a question when an empty question is passed - what is the right behaviour here?
not even sure what the right answer is tbh
p
I caught the exception....
Copy code
Traceback (most recent call last):
  File "/Users/paco/src/strwythura/rag.py", line 39, in <module>
    response: baml_types.Response = rag.qa_cycle(
                                    ^^^^^^^^^^^^^
  File "/Users/paco/src/strwythura/strwythura/strw.py", line 508, in qa_cycle
    response: baml_types.Response = b.RAG(
                                    ^^^^^^
  File "/Users/paco/src/strwythura/strwythura/baml_client/sync_client.py", line 94, in RAG
    return typing.cast(types.Response, result.cast_to(types, types, stream_types, False, __runtime__))
                                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
baml_py.internal_monkeypatch.BamlValidationError: BamlValidationError(message=Failed to parse LLM response: Failed to coerce value: <root>: Failed while parsing required fields: missing=0, unparsed=1
  - <root>: Failed to parse field question: question: Expected string, got null
    - question: Expected string, got null, raw_output={
  "question": null,
  "answer": "As of January 15, 2025, the results were published online in Neurology, the medical journal of the American Academy of Neurology."
}, prompt=system: Answer the question in full sentences using the provided context.
Do not make up an answer. If the information is not provided in the context, say so clearly.

QUESTION: dementia and tofu
RELEVANT CONTEXT: The findings also suggest that people can decrease their risk of dementia by replacing one serving of processed red meat with one serving of nuts and legumes, such as beans and peas, every day.
'Prevention of Alzheimer's disease and all other dementia is a major focus, and the Alzheimer's Association has long encouraged eating a healthier diet ' including foods that are less processed ' because they've been associated with lower the risk of cognitive decline,' said Heather M. Snyder, Ph.D., Alzheimer's Association vice president of medical and scientific relations.
p
Well, that's why I think someone from the Boundary team should take a closer look at this
p
baml_py.internal_monkeypatch.BamlValidationError
"Failed to parse LLM response: Failed to coerce value: : Failed while parsing required fields: missing=0, unparsed=1"
a
CC @Vaibhav (BAML πŸ‘)
p
I have to go to an appointment, though MANY THANKS @prrao for all of your help today!!!
p
Lots of problems to dig into: - What should be the right behaviour if an empty question is passed? Can we avoid the LLM hallucinating a question? - Why is there an error from the BAML parser when you have an empty question? - Why is the BAML parser error not consistently reproducible? I don't get it on my end.
yeah, I'll leave it to the BAML folks.. Cheers!
v
sadly i think this is an LLM problem πŸ™
Copy code
{
  "question": null,
  "answer": "As of January 15, 2025, the results were published online in Neurology, the medical journal of the American Academy of Neurology."
}
The llm is choosing to fill
question
with
null
but your type requires
question
to be a
string
. a few ideas here: 1. make question options -- use
string | null
type 2. add a description for question:
@description("rephrased more directly from what the user asked")
3. use a smarter model
This is
gpt-4.1-mini
Definitely a way smarter model - the issue seems to be universal
Also, what is the reason for the parser error?
v
maybe i'm missing something
p
Empty string is the problem, not null
v
empy string is failing?
let me reread the thread again!
p
worse than failing: It's hallucinating both the question and the answer!
It's a the definition of a royal clusterfck πŸ˜‚
p
thank you @Vaibhav (BAML πŸ‘) !
p
Somehow in Paco's workflow, an empty string is making its way into the RAG prompt
But the way the system is handling it, and the fact that BAML's parser randomly complains (only some of the time, but not all), seems like buggy behaviour
v
hmm, maybe i'm confused, the parser is only ever running on the output from an LLM
so in order for the parser to fail, it would mean the LLM is producing something invalid
p
Oh, so you're saying sometimes the LLM produces null as the answer and that's why adding
string | null
helps
v
in this case:
Copy code
{
  "question": null,
  "answer": "As of January 15, 2025, the results were published online in Neurology, the medical journal of the American Academy of Neurology."
}
the llm produced teh
null
value for the field
question
and our parser noped out
cause
null
=>
string
is not possible
p
Well, that's at least better than the hallucination πŸ˜…
p
I pass in both params
question
and
context
into the
b.RAG()
call. But then somehow internally the value of
question
gets changed.
p
So I suppose @Paco Nathan some very careful engineering is needed to ensure that you do not under any circumstances ever, pass an empty string to the question field
The question changes only when an empty string is passed
p
True. Although so far that's been checked.
p
Otherwise the same question string is used
v
for example, in the error you posted above: this is the full prompt
Copy code
system: Answer the question in full sentences using the provided context.
Do not make up an answer. If the information is not provided in the context, say so clearly.

QUESTION: dementia and tofu
RELEVANT CONTEXT: The findings also suggest that people can decrease their risk of dementia by replacing one serving of processed red meat with one serving of nuts and legumes, such as beans and peas, every day.
'Prevention of Alzheimer's disease and all other dementia is a major focus, and the Alzheimer's Association has long encouraged eating a healthier diet ' including foods that are less processed ' because they've been associated with lower the risk of cognitive decline,' said Heather M. Snyder, Ph.D., Alzheimer's Association vice president of medical and scientific relations.
p
What amazes me, is that this is the simplest RAG example we could have come up with in the docs
p
I had to truncate the context, in the error posted above.
p
And yet, it's managed to unearth a ton of new problems πŸ˜‚
The onus is all on the user to ensure that the LLM doesn't fk up
Scary πŸ˜₯
I'm imagining a user error where for some reason, in production, an empty string got passed to the RAG prompt. Checking for empty strings being passed to the question is a totally understandable miss from a human standpoint, it didn't occur to any of us that this should be something to a) prompt against or b) check for emptiness before passing to the LLM
And the fact the LLM hallucinated both the question and the answer means that we may have silently failed without even knowing
It's an observability nightmare
v
yea one way to prevent this is:
Copy code
type NonEmptyString = string @assert({{ this | length > 0}})

function Foo(question: NonEmptyString)
that way atleast you'll get an error earlier
p
yes, I'd put an assert like that into the code
p
yeah, the fact that it's explicitly defined that way - and there's no inherent protection from the LLM's hallucination ability
That's mindblowing
Today I learned!
a
would you rather the parser fail?
sorry the input param is the bad one
my bad
p
My original question: is there any means of turning off the question rewriting?
p
I haven't been able to reproduce the question rewriting πŸ˜…
it never rewrites for me
on any model
v
the reason its "rewriting" the question is because:
Copy code
python
question: str = "something user generated"
result = b.Raw(question)

# this sadly can't be guaranteed
assert result.question == question
for example: if question is empty string, then the llm may think that you acutally meant to ask it to gneerate both a question and an answer from the context
p
Okay sorry for derailing the issue at hand: But to actually address paco's question, we need to understand when rewriting happens?
In plain BAML tests, are you able to see this rewriting happening @Paco?
Cuz I don't
v
other things you can do in your prompt: 1. move question to after the context. 2. add the question part to the user message 3. use a snippet like this
Copy code
{{ question or "<intentionally blank>" }}
to detect the rewriting i would do this:
p
Do you have example code? I'm not sure I understand about plain BAML tests
v
Copy code
python
question: str = "something user generated"
result = b.Raw(question)

# this sadly can't be guaranteed
if result.question.lower() != question.lower():
   if not b.IsSemanticallySame(question, result.question):
      raise Exception("LLM is likely hallucinating!")

# otherwise we good
p
Copy code
rs
test RAG1 {
    functions [RAGTest]
    args {
        question "How many people were in the study?"
        context "According to the study, eating a daily average of one-quarter or more of a serving of processed red meats (roughly two slices of bacon, one and half slices of bologna, or a hot dog), compared to those consuming a minimal amount (less than one-tenth a serving each day), had a 13 percent higher risk of developing dementia."
    }
}

test RAG2 {
    functions [RAGTest]
    args {
        question "What is the association between processed red meat and dementia?"
        context "According to the study, eating a daily average of one-quarter or more of a serving of processed red meats (roughly two slices of bacon, one and half slices of bologna, or a hot dog), compared to those consuming a minimal amount (less than one-tenth a serving each day), had a 13 percent higher risk of developing dementia."
    }
}

test RAG3 {
    functions [RAGTest]
    args {
        question ""
        context "According to the study, eating a daily average of one-quarter or more of a serving of processed red meats (roughly two slices of bacon, one and half slices of bologna, or a hot dog), compared to those consuming a minimal amount (less than one-tenth a serving each day), had a 13 percent higher risk of developing dementia."
    }
}
Just run these tests in your BAML playground using
baml_src/rag.baml
(there's already a test there in that file on the GitHub repo, just update the function name accordingly)
Or do you not use VS code?
When I run these tests 10 times, only test 3 hallucinates 100% of the time. Tests 1 and 2 are flawless 10/10 times.
p
great, many thanks @prrao and @Vaibhav (BAML πŸ‘) ! i've got to run to an appt
p
tests 1 and 2 always work correctly, there is no question rewriting happening whatsoever
v
ohter things you can do 1: in your output:
Copy code
class Answer {
  qusetion_type "verbaitm" | "reworded" | "new"
  question string
  answer string
}
then just filter out everything that is
question_type == "new"
p
I think there's something off in the Python code that Paco's using that's causing an empty question to be sent to the RAG function. But let's revisit that later when he's had the chance to test
v
πŸ‘πŸΎ
p
Just checked the behaviour with Pydantic + DSPy and BAML's behaviour is consistent - no bug on BAML's end. it's ALL on the LLM's end! The only scenario when the question is rewritten/hallucinated is when the input string is empty https://gist.github.com/prrao87/6cbb4810ec5f024046ad32d53514a88b
In the above gist, when lines 34-35 are absent (i.e., we don't raise a
ValueError
in the application code), the LLM will hallucinate and make up a question. The prompt doesn't protect you, and the LLM is primed to want to help, so it does something to get you a response. The fact that the prompt doesn't protect you from outright hallucination like this is a wakeup call to me, gonna be very wary about evals and empty strings any time LLMs are involved from this point πŸ˜…
p
Many thanks again, I've made some changes and tested: - using
assert
on the
question
value to prevent any null questions - added the
question_type
field which @Vaibhav (BAML πŸ‘) suggested - moved the
Question
below
Context
in the prompt - now using
gemma3:12b
model instead of Llama3 Seems to work much better. Gemma3 still rewrites questions, just not as poorly as Llama3. Runs a bit slower. If you want to run an illustration of enhanced GraphRAG -- using a fully annotated lexical graph based on spaCy + GLiNER, semantic expansions, semantic random walks, etc., to rerank the chunks -- which looks pretty cool when you see the traces of runs! code: https://github.com/DerwenAI/strwythura call to BAML: https://github.com/DerwenAI/strwythura/blob/c3f23ce5151b0b46ce566e6333ab635cad7a9553/strwythura/strw.py#L508 BAML source: https://github.com/DerwenAI/strwythura/blob/main/strwythura/baml_src/rag.baml I cannot see anywhere that the Python code would be introducing an error -- unless somehow I'm not calling BAML correctly?
Copy code
response: baml_types.Response = b.RAG(
            question,
            context,
        )
p
I'm not exactly pleased with the fact that questions are being rewritten without being asked πŸ˜…
I don't fully understand each step of the code yet, but will take a look in due course!
v
My hunch says it’s almost definitely the LLM somehow.
LLMs are dumb and do sometimes not listen
p
@Paco Nathan these tips by Vaibhav are really good. I think there's something going on with the way open source LLMs handle the question when it's part of the system prompt vs. the user message.
Here's an example prompt I use for RAG, where I explicitly declare the
{{ question }}
parameter in the part after the user message begins. Specifically, in this order:
Copy code
.., (rest of the system messsage up here)
{{ ctx.output_format }}


{{ _.role("user") }}

QUESTION: {{ question }}
The question string should be deterministically passed around. Somewhere along the way, it seems that the open source LLM thinks that because the question is not in the user message, it has the right to modify it. That could be the issue. Basically, as a rule of thumb a) declare the user message part separately, and pass inputs that may change per user request in that section, and b) Place the question after
{{ ctx.output_format }}
p
Super helpful! I've followed the patterns in your BAML example and set the temperature to zero, with Gemma3 ... Behavior now is that question rewrites are rare. When they happen they are relatively minor. Unless the question is bizarre, then a new question gets substituted to provide a general response about the content.