Close Menu
    Trending
    • Meanwhile in Europe: How We Learned to Stop Worrying and Love the AI Angst | by Andreas Maier | Jul, 2025
    • Transform Complexity into Opportunity with Digital Engineering
    • OpenAI Is Fighting Back Against Meta Poaching AI Talent
    • Lessons Learned After 6.5 Years Of Machine Learning
    • Handling Big Git Repos in AI Development | by Rajarshi Karmakar | Jul, 2025
    • National Lab’s Machine Learning Project to Advance Seismic Monitoring Across Energy Industries
    • HP’s PCFax: Sustainability Via Re-using Used PCs
    • Mark Zuckerberg Reveals Meta Superintelligence Labs
    AIBS News
    • Home
    • Artificial Intelligence
    • Machine Learning
    • AI Technology
    • Data Science
    • More
      • Technology
      • Business
    AIBS News
    Home»Artificial Intelligence»An Agentic Approach to Reducing LLM Hallucinations | by Youness Mansar | Dec, 2024
    Artificial Intelligence

    An Agentic Approach to Reducing LLM Hallucinations | by Youness Mansar | Dec, 2024

    Team_AIBS NewsBy Team_AIBS NewsDecember 23, 2024No Comments8 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    Share
    Facebook Twitter LinkedIn Pinterest Email


    Tip 2: Use structured outputs

    Utilizing structured outputs means forcing the LLM to output legitimate JSON or YAML textual content. This can will let you scale back the ineffective ramblings and get “straight-to-the-point” solutions about what you want from the LLM. It additionally will assist with the following ideas because it makes the LLM responses simpler to confirm.

    Right here is how you are able to do this with Gemini’s API:

    import json

    import google.generativeai as genai
    from pydantic import BaseModel, Area

    from document_ai_agents.schema_utils import prepare_schema_for_gemini

    class Reply(BaseModel):
    reply: str = Area(..., description="Your Reply.")

    mannequin = genai.GenerativeModel("gemini-1.5-flash-002")

    answer_schema = prepare_schema_for_gemini(Reply)

    query = "Listing all of the the reason why LLM hallucinate"

    context = (
    "LLM hallucination refers back to the phenomenon the place giant language fashions generate plausible-sounding however"
    " factually incorrect or nonsensical data. This will happen because of numerous components, together with biases"
    " within the coaching information, the inherent limitations of the mannequin's understanding of the true world, and the "
    "mannequin's tendency to prioritize fluency and coherence over accuracy."
    )

    messages = (
    [context]
    + [
    f"Answer this question: {question}",
    ]
    + [
    f"Use this schema for your answer: {answer_schema}",
    ]
    )

    response = mannequin.generate_content(
    messages,
    generation_config={
    "response_mime_type": "utility/json",
    "response_schema": answer_schema,
    "temperature": 0.0,
    },
    )

    response = Reply(**json.hundreds(response.textual content))

    print(f"{response.reply=}")

    The place “prepare_schema_for_gemini” is a utility operate that prepares the schema to match Gemini’s bizarre necessities. You’ll find its definition right here: code.

    This code defines a Pydantic schema and sends this schema as a part of the question within the area “response_schema”. This forces the LLM to comply with this schema in its response and makes it simpler to parse its output.

    Tip 3: Use chain of ideas and higher prompting

    Typically, giving the LLM the area to work out its response, earlier than committing to a remaining reply, can assist produce higher high quality responses. This method is named Chain-of-thoughts and is extensively used as it’s efficient and really simple to implement.

    We will additionally explicitly ask the LLM to reply with “N/A” if it might probably’t discover sufficient context to provide a high quality response. This can give it a simple manner out as an alternative of making an attempt to reply to questions it has no reply to.

    For instance, lets look into this easy query and context:

    Context

    Thomas Jefferson (April 13 [O.S. April 2], 1743 — July 4, 1826) was an American statesman, planter, diplomat, lawyer, architect, thinker, and Founding Father who served because the third president of the US from 1801 to 1809.[6] He was the first writer of the Declaration of Independence. Following the American Revolutionary Conflict and earlier than turning into president in 1801, Jefferson was the nation’s first U.S. secretary of state beneath George Washington after which the nation’s second vp beneath John Adams. Jefferson was a number one proponent of democracy, republicanism, and pure rights, and he produced formative paperwork and choices on the state, nationwide, and worldwide ranges. (Supply: Wikipedia)

    Query

    What yr did davis jefferson die?

    A naive strategy yields:

    Response

    reply=’1826′

    Which is clearly false as Jefferson Davis shouldn’t be even talked about within the context in any respect. It was Thomas Jefferson that died in 1826.

    If we modify the schema of the response to make use of chain-of-thoughts to:

    class AnswerChainOfThoughts(BaseModel):
    rationale: str = Area(
    ...,
    description="Justification of your reply.",
    )
    reply: str = Area(
    ..., description="Your Reply. Reply with 'N/A' if reply shouldn't be discovered"
    )

    We’re additionally including extra particulars about what we count on as output when the query shouldn’t be answerable utilizing the context “Reply with ‘N/A’ if reply shouldn’t be discovered”

    With this new strategy, we get the next rationale (keep in mind, chain-of-thought):

    The supplied textual content discusses Thomas Jefferson, not Jefferson Davis. No details about the dying of Jefferson Davis is included.

    And the ultimate reply:

    reply=’N/A’

    Nice ! However can we use a extra basic strategy to hallucination detection?

    We will, with Brokers!

    Tip 4: Use an Agentic strategy

    We’ll construct a easy agent that implements a three-step course of:

    • Step one is to incorporate the context and ask the query to the LLM in an effort to get the primary candidate response and the related context that it had used for its reply.
    • The second step is to reformulate the query and the primary candidate response as a declarative assertion.
    • The third step is to ask the LLM to confirm whether or not or not the related context entails the candidate response. It’s referred to as “Self-verification”: https://arxiv.org/pdf/2212.09561

    In an effort to implement this, we outline three nodes in LangGraph. The primary node will ask the query whereas together with the context, the second node will reformulate it utilizing the LLM and the third node will verify the entailment of the assertion in relation to the enter context.

    The primary node could be outlined as follows:

        def answer_question(self, state: DocumentQAState):
    logger.information(f"Responding to query '{state.query}'")
    assert (
    state.pages_as_base64_jpeg_images or state.pages_as_text
    ), "Enter textual content or photos"
    messages = (
    [
    {"mime_type": "image/jpeg", "data": base64_jpeg}
    for base64_jpeg in state.pages_as_base64_jpeg_images
    ]
    + state.pages_as_text
    + [
    f"Answer this question: {state.question}",
    ]
    + [
    f"Use this schema for your answer: {self.answer_cot_schema}",
    ]
    )

    response = self.mannequin.generate_content(
    messages,
    generation_config={
    "response_mime_type": "utility/json",
    "response_schema": self.answer_cot_schema,
    "temperature": 0.0,
    },
    )

    answer_cot = AnswerChainOfThoughts(**json.hundreds(response.textual content))

    return {"answer_cot": answer_cot}

    And the second as:

        def reformulate_answer(self, state: DocumentQAState):
    logger.information("Reformulating reply")
    if state.answer_cot.reply == "N/A":
    return

    messages = [
    {
    "role": "user",
    "parts": [
    {
    "text": "Reformulate this question and its answer as a single assertion."
    },
    {"text": f"Question: {state.question}"},
    {"text": f"Answer: {state.answer_cot.answer}"},
    ]
    + [
    {
    "text": f"Use this schema for your answer: {self.declarative_answer_schema}"
    }
    ],
    }
    ]

    response = self.mannequin.generate_content(
    messages,
    generation_config={
    "response_mime_type": "utility/json",
    "response_schema": self.declarative_answer_schema,
    "temperature": 0.0,
    },
    )

    answer_reformulation = AnswerReformulation(**json.hundreds(response.textual content))

    return {"answer_reformulation": answer_reformulation}

    The third one as:

        def verify_answer(self, state: DocumentQAState):
    logger.information(f"Verifying reply '{state.answer_cot.reply}'")
    if state.answer_cot.reply == "N/A":
    return
    messages = [
    {
    "role": "user",
    "parts": [
    {
    "text": "Analyse the following context and the assertion and decide whether the context "
    "entails the assertion or not."
    },
    {"text": f"Context: {state.answer_cot.relevant_context}"},
    {
    "text": f"Assertion: {state.answer_reformulation.declarative_answer}"
    },
    {
    "text": f"Use this schema for your answer: {self.verification_cot_schema}. Be Factual."
    },
    ],
    }
    ]

    response = self.mannequin.generate_content(
    messages,
    generation_config={
    "response_mime_type": "utility/json",
    "response_schema": self.verification_cot_schema,
    "temperature": 0.0,
    },
    )

    verification_cot = VerificationChainOfThoughts(**json.hundreds(response.textual content))

    return {"verification_cot": verification_cot}

    Full code in https://github.com/CVxTz/document_ai_agents

    Discover how every node makes use of its personal schema for structured output and its personal immediate. That is doable as a result of flexibility of each Gemini’s API and LangGraph.

    Lets work by way of this code utilizing the identical instance as above ➡️
    (Word: we’re not utilizing chain-of-thought on the primary immediate in order that the verification will get triggered for our assessments.)

    Context

    Thomas Jefferson (April 13 [O.S. April 2], 1743 — July 4, 1826) was an American statesman, planter, diplomat, lawyer, architect, thinker, and Founding Father who served because the third president of the US from 1801 to 1809.[6] He was the first writer of the Declaration of Independence. Following the American Revolutionary Conflict and earlier than turning into president in 1801, Jefferson was the nation’s first U.S. secretary of state beneath George Washington after which the nation’s second vp beneath John Adams. Jefferson was a number one proponent of democracy, republicanism, and pure rights, and he produced formative paperwork and choices on the state, nationwide, and worldwide ranges. (Supply: Wikipedia)

    Query

    What yr did davis jefferson die?

    First node outcome (First reply):

    relevant_context=’Thomas Jefferson (April 13 [O.S. April 2], 1743 — July 4, 1826) was an American statesman, planter, diplomat, lawyer, architect, thinker, and Founding Father who served because the third president of the US from 1801 to 1809.’

    reply=’1826′

    Second node outcome (Reply Reformulation):

    declarative_answer=’Davis Jefferson died in 1826′

    Third node outcome (Verification):

    rationale=’The context states that Thomas Jefferson died in 1826. The assertion states that Davis Jefferson died in 1826. The context doesn’t point out Davis Jefferson, solely Thomas Jefferson.’

    entailment=’No’

    So the verification step rejected (No entailment between the 2) the preliminary reply. We will now keep away from returning a hallucination to the person.

    Bonus Tip : Use stronger fashions

    This tip shouldn’t be all the time simple to use because of funds or latency limitations however you must know that stronger LLMs are much less liable to hallucination. So, if doable, go for a extra highly effective LLM to your most delicate use circumstances. You possibly can verify a benchmark of hallucinations right here: https://github.com/vectara/hallucination-leaderboard. We will see that the highest fashions on this benchmark (least hallucinations) additionally ranks on the prime of typical NLP chief boards.

    Supply: https://github.com/vectara/hallucination-leaderboard Supply License: Apache 2.0

    On this tutorial, we explored methods to enhance the reliability of LLM outputs by decreasing the hallucination price. The principle suggestions embody cautious formatting and prompting to information LLM calls and utilizing a workflow primarily based strategy the place Brokers are designed to confirm their very own solutions.

    This entails a number of steps:

    1. Retrieving the precise context parts utilized by the LLM to generate the reply.
    2. Reformulating the reply for simpler verification (In declarative kind).
    3. Instructing the LLM to verify for consistency between the context and the reformulated reply.

    Whereas all the following tips can considerably enhance accuracy, you must do not forget that no methodology is foolproof. There’s all the time a threat of rejecting legitimate solutions if the LLM is overly conservative throughout verification or lacking actual hallucination circumstances. Due to this fact, rigorous analysis of your particular LLM workflows remains to be important.

    Full code in https://github.com/CVxTz/document_ai_agents



    Source link

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleWill AI Do Everything? Unlocking Collaboration Between Humans and Machines | by Amit kumar | Dec, 2024
    Next Article Government Shutdown Could Cost US Economy $6 Billion a Week
    Team_AIBS News
    • Website

    Related Posts

    Artificial Intelligence

    Lessons Learned After 6.5 Years Of Machine Learning

    July 1, 2025
    Artificial Intelligence

    Prescriptive Modeling Makes Causal Bets – Whether You Know it or Not!

    June 30, 2025
    Artificial Intelligence

    A Gentle Introduction to Backtracking

    June 30, 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Top Posts

    Meanwhile in Europe: How We Learned to Stop Worrying and Love the AI Angst | by Andreas Maier | Jul, 2025

    July 1, 2025

    I Tried Buying a Car Through Amazon: Here Are the Pros, Cons

    December 10, 2024

    Amazon and eBay to pay ‘fair share’ for e-waste recycling

    December 10, 2024

    Artificial Intelligence Concerns & Predictions For 2025

    December 10, 2024

    Barbara Corcoran: Entrepreneurs Must ‘Embrace Change’

    December 10, 2024
    Categories
    • AI Technology
    • Artificial Intelligence
    • Business
    • Data Science
    • Machine Learning
    • Technology
    Most Popular

    Model Context Protocol or MCP (without the mumbo-jumbo) | by Adnan Hashmi | Mar, 2025

    March 30, 2025

    News Bytes 20250526: Biggest AI Training Center?, Big AI Pursues AGI and Beyond, NVIDIA’s Quantum Moves, RISC-V Turns 15

    May 28, 2025

    Unlocking Voices: AR for Nonverbal Autism

    May 13, 2025
    Our Picks

    Meanwhile in Europe: How We Learned to Stop Worrying and Love the AI Angst | by Andreas Maier | Jul, 2025

    July 1, 2025

    Transform Complexity into Opportunity with Digital Engineering

    July 1, 2025

    OpenAI Is Fighting Back Against Meta Poaching AI Talent

    July 1, 2025
    Categories
    • AI Technology
    • Artificial Intelligence
    • Business
    • Data Science
    • Machine Learning
    • Technology
    • Privacy Policy
    • Disclaimer
    • Terms and Conditions
    • About us
    • Contact us
    Copyright © 2024 Aibsnews.comAll Rights Reserved.

    Type above and press Enter to search. Press Esc to cancel.