Teach your LLM how to talk through examples Photo by Markus Winkler on Unsplash
One of the most frustrating parts of building gen-AI applications is the manual process of optimising prompts. In a publication made by LinkedIn earlier this year, they described what they learned after deploying an agentic RAG application. One of the main challenges was obtaining consistent quality. They spent 4 months tweaking various parts of the application, including prompts, to mitigate issues such as hallucination.
DSPy is an open-source library that tries to parameterise prompts so that it becomes an optimisation problem. The original paper calls prompt engineering brittle and unscalable and compares it to hand-tuning the weights for a classifier.
Haystack is an open-source library to build LLM applications, including RAG pipelines. It is platform-agnostic and offers a large number of integrations with different LLM providers, search databases and more. It also has its own evaluation metrics.
In this article, we will briefly go over the internals of DSPy, and show how it can be used to teach an LLM to prefer more concise answers when answering questions over an academic medical dataset.
This article from TDS provides a great in-depth exploration of DSPy. We will be summarising and using some of their examples.
In order to build a LLM application that can be optimised, DSPy offers two main abstractions: signatures and modules. A signature is a way to define the input and output of a system that interacts with LLMs. The signature is translated internally into a prompt by DSPy.
When using the DSPy Predict module (more on this later), this signature is turned into the following prompt:
Then, DSPy also has modules which define the predictors that have parameters that can be optimised, such as the selection of few-shot examples. The simplest module is dspy.Predict which does not modify the signature. Later in this article we will use the module dspy.ChainOfThought which asks the LLM to provide reasoning.
Things start to get interesting once we try to optimise a module (or as DSPy calls it compiling a module). When optimising a module, you typically need to specify 3 things:
When using the dspy.Predict or the dspy.ChainOfThought modules, DSPy searches through the training set and selects the best examples to add to the prompt as few-shot examples. In the case of RAG, it can also include the context that was used to get the final response. It calls these examples demonstrations.
You also need to specify the type of optimiser you want to use to search through the parameter space. In this article, we use the BootstrapFewShot optimiser. How does this algorithm work internally? It is actually very simple and the paper provides some simplified pseudo-code:
The search algorithm goes through every training input in the trainset , gets a prediction and then checks whether it passes the metric by looking at self.metric(example, prediction, predicted_traces). If the metric passes, then the examples are added to the demonstrations of the compiled program.
The entire code can be found in this cookbook with associated colab, so we will only go through some of the most important steps here. For the example, we use a dataset derived from the PubMedQA dataset (both under the MIT license). It has questions based on abstracts of medical research papers and their associated answers. Some of the answers provided can be quite long, so we will be using DSPy to teach the LLM to prefer more concise answers, while keeping the accuracy of the final answer high.
After adding the first 1000 examples to an in-memory document store (which can be replaced by any number of retrievers), we can now build our RAG pipeline:
Lets try it out!
The answer to the above question:
Ketamine inhibits the proliferation of rat neural stem cells in a dose-dependent manner at concentrations of 200, 500, 800, and 1000M. Additionally, ketamine decreases intracellular Ca(2+) concentration, suppresses protein kinase C- (PKC) activation, and phosphorylation of extracellular signal-regulated kinases 1/2 (ERK1/2) in rat neural stem cells. These effects do not seem to be mediated through caspase-3-dependent apoptosis.
We can see how the answers tend to be very detailed and long.
We start by creating a DSPy signature of the input and output fields:
As we can see, we already specify in our description that we are expecting a short answer.
Then, we create a DSPy module that will be later compiled:
We are using the Haystack retriever previously defined to search the documents in the document store results = retriever.run(query=question). The prediction step is done with the DSPy module dspy.ChainOfThought which teaches the LM to think step-by-step before committing to the response.
During compilation, the prompt that will be optimised to look like this:
Finally, we have to define the metrics that we would like to optimise. The evaluator will have two parts:
Our evaluation dataset is composed of 20 training examples and 50 examples in the devset.
If we evaluate the current naive RAG pipeline with the code below, we get an average score of 0.49.
Looking at some examples can give us some intuition on what the score is doing:
Question: Is increased time from neoadjuvant chemoradiation to surgery associated with higher pathologic complete response rates in esophageal cancer?
Predicted answer: Yes, increased time from neoadjuvant chemoradiation to surgery is associated with higher pathologic complete response rates in esophageal cancer.
Score: 0.78
But
Question: Is epileptic focus localization based on resting state interictal MEG recordings feasible irrespective of the presence or absence of spikes?
Predicted answer: Yes.
Score: 0.089
As we can see from the examples, if the answer is too short, it gets a low score because its similarity with the ground truth answer drops.
We then compile the RAG pipeline with DSPy:
After we do this and re-evaluate the compiled pipeline, the score is now 0.69!
Now its time to get the final optimised prompt and add it into our Haystack pipeline.
We can see the few-shot examples selected by DSPy by looking at the demos field in the compiled_rag object:
There are 2 types of examples provided in the final prompt: few-shot examples and bootstrapped demos, like in the prompt shown above. The few-shot examples are question-answer pairs:
Whereas the bootstrapped demo has the full trace of the LLM, including the context and reasoning provided (in the rationale field below):
All we need to do now is extract these examples found by DSPy and insert them in our Haystack pipeline:
Our new pipeline becomes:
Lets check the same question we tried before.
Question:
What effects does ketamine have on rat neural stem cells?
Before:
Ketamine inhibits the proliferation of rat neural stem cells in a dose-dependent manner at concentrations of 200, 500, 800, and 1000M. Additionally, ketamine decreases intracellular Ca(2+) concentration, suppresses protein kinase C- (PKC) activation, and phosphorylation of extracellular signal-regulated kinases 1/2 (ERK1/2) in rat neural stem cells. These effects do not seem to be mediated through caspase-3-dependent apoptosis.
After:
Ketamine at higher concentrations inhibits the proliferation of rat neural stem cells, while not affecting apoptosis. Additionally, it decreases intracellular calcium concentration and suppresses PKC activation and ERK1/2 phosphorylation in these cells.
Job done!
In this post, we have used DSPy to optimise the prompt used in a Haystack RAG pipeline. We have done so by using a custom metric based on Haystacks evaluation framework that penalised the LLM for long answers while keeping the similarity with the correct answer high. With this approach, we have managed to improve our performance by almost 40% without having to do any manual prompt engineering.
More:
- 10 books thatll help you become a better software engineer - The Next Web [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- Total hands out UKCS engineering framework deals to trio of consultants - News for the Oil and Gas Sector - Energy Voice [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- Prometheus: Why The Engineers Were Heading To Earth | Screen Rant - Screen Rant [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- Management CEMETERY SUPERINTENDENT The City of Gibbon is currently accepting - Kearney Hub [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- Transportation Engineering and Safety Conference to be held Dec. 9-11 - Penn State News [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- 'Bending' light to engineer improved optical devices and circuits - ND Newswire [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- UC Merced Engineering Center to Focus on Ag Technology - AG INFORMATION NETWORK OF THE WEST - AGInfo Ag Information Network Of The West [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- Head of Engineering Maintenance job with DURHAM UNIVERSITY | 233561 - Times Higher Education (THE) [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- Civil Engineering student part of National Women in Engineering "Dream Team" panel - uoflnews.com [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- Breaking News - Engineering at Its Best... and Worst: Don't Miss the Return of Science Channel's Hit Series "Deadly Engineering" and... [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- Tesla is No. 1 most attractive company for engineering students, and thats a massive advantage - Electrek [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- Wolves alter wetland creation and recolonization by killing ecosystem engineers - UMN News [Last Updated On: November 17th, 2020] [Originally Added On: November 17th, 2020]
- Global Automotive Simulation Market To Witness Astonishing Growth 2026 | Altair Engineering Inc., ANSYS Inc., PTC, Siemens AG, Autodesk Inc.,... [Last Updated On: November 17th, 2020] [Originally Added On: November 17th, 2020]
- Engineers Without Borders urges industry reflection - The Engineer [Last Updated On: November 17th, 2020] [Originally Added On: November 17th, 2020]
- 9 Engineers on the Hardest Song They Ever Mixed - Vulture [Last Updated On: November 17th, 2020] [Originally Added On: November 17th, 2020]
- Daewoo Engineering and Construction and SPH Engineering disclose AI partnership - sUAS News [Last Updated On: November 17th, 2020] [Originally Added On: November 17th, 2020]
- TRIPLE EIGHT BATHURST WINNING ENGINEER TO JOIN WAU - Auto Action [Last Updated On: November 24th, 2020] [Originally Added On: November 24th, 2020]
- First-year engineering classes for Anna University affiliated colleges take the e-way from today - The New Indian Express [Last Updated On: November 24th, 2020] [Originally Added On: November 24th, 2020]
- Datafold raises seed from NEA to keep improving the lives of data engineers - TechCrunch [Last Updated On: November 24th, 2020] [Originally Added On: November 24th, 2020]
- Tech has overtaken engineering as Bristol's fastest-growing industry with more than $1.07bn invested in the city since 2014 - Business Leader [Last Updated On: November 24th, 2020] [Originally Added On: November 24th, 2020]
- Start 2021 as an electrical engineer with this training for less than $20 - Boing Boing [Last Updated On: November 24th, 2020] [Originally Added On: November 24th, 2020]
- The Global Engineering Plastics Market is expected to grow by $ 43.00 bn during 2020-2024 progressing at a CAGR of 8% during the forecast period -... [Last Updated On: November 24th, 2020] [Originally Added On: November 24th, 2020]
- Elementary students test their engineering skills with Mayflower project - williamsonherald.com [Last Updated On: November 24th, 2020] [Originally Added On: November 24th, 2020]
- Global Architectural Engineering and Construction Solutions (AECS) Market 2020-2024 | Market Analysis, Drivers, Restraints, Opportunities, and Threats... [Last Updated On: December 14th, 2020] [Originally Added On: December 14th, 2020]
- American Institute of Chemical Engineers Celebrates Organizations and Leaders for Doing a World of Good - GlobeNewswire [Last Updated On: December 14th, 2020] [Originally Added On: December 14th, 2020]
- 2 Texas Engineers Honored Among Top Inventors in US - UT News - UT News | The University of Texas at Austin [Last Updated On: December 14th, 2020] [Originally Added On: December 14th, 2020]
- Chemical engineering alumna named Woman of the Year in Engineering - Penn State News [Last Updated On: December 14th, 2020] [Originally Added On: December 14th, 2020]
- 14 Largest Engineering Companies In The World - Yahoo Finance [Last Updated On: December 14th, 2020] [Originally Added On: December 14th, 2020]
- Vails namesake was a controversial state highway engineer - The Grand Junction Daily Sentinel [Last Updated On: December 14th, 2020] [Originally Added On: December 14th, 2020]
- The Next Frontier of Learning Engineering: AI That Teaches Other AI - EdSurge [Last Updated On: December 14th, 2020] [Originally Added On: December 14th, 2020]
- $496M Contract Will Give DOD Engineering Capabilities, Official Says - Nextgov [Last Updated On: December 14th, 2020] [Originally Added On: December 14th, 2020]
- William H. Robinson has a 'new and expanded leadership' post at Vanderbilt University - BlackEngineer.com [Last Updated On: December 14th, 2020] [Originally Added On: December 14th, 2020]
- Di Appointed to Lead Computer Science and Computer Engineering - University of Arkansas Newswire [Last Updated On: December 14th, 2020] [Originally Added On: December 14th, 2020]
- English is easier: India is woefully underprepared to teach engineering in regional languages - The Times of India Blog [Last Updated On: December 15th, 2020] [Originally Added On: December 15th, 2020]
- VW Bolsters U.S. Footprint With Advancements In Electric Car Portfolio, Infrastructure And Engineering - CarScoops [Last Updated On: December 15th, 2020] [Originally Added On: December 15th, 2020]
- These 4 Measures Indicate That SIA Engineering (SGX:S59) Is Using Debt Reasonably Well - Simply Wall St [Last Updated On: December 15th, 2020] [Originally Added On: December 15th, 2020]
- New engineering business opens its doors in Netherton despite the pandemic - expressandstar.com [Last Updated On: December 15th, 2020] [Originally Added On: December 15th, 2020]
- 'Earables' the next milestone in wearable tech, say engineers - E&T Magazine [Last Updated On: December 15th, 2020] [Originally Added On: December 15th, 2020]
- Senior Lecturer in Mechanical Engineering job with BIRMINGHAM CITY UNIVERSITY | 238845 - Times Higher Education (THE) [Last Updated On: December 15th, 2020] [Originally Added On: December 15th, 2020]
- New collaboration provides opportunity for future water scientists and engineers - Cranfield University [Last Updated On: December 15th, 2020] [Originally Added On: December 15th, 2020]
- Box Opens Research and Development Engineering Site in Warsaw, Poland - Business Wire [Last Updated On: December 15th, 2020] [Originally Added On: December 15th, 2020]
- Engineering and Technology Management students achieve high pass rate on certification exam - Morehead State University News [Last Updated On: December 15th, 2020] [Originally Added On: December 15th, 2020]
- Hydram Engineering warns Covid-19 and Brexit will dent its turnover - Business Live [Last Updated On: January 4th, 2021] [Originally Added On: January 4th, 2021]
- Calculating The Intrinsic Value Of Watts International Maritime Engineering Limited (HKG:2258) - Simply Wall St [Last Updated On: January 4th, 2021] [Originally Added On: January 4th, 2021]
- Is Suprajit Engineering Limited's (NSE:SUPRAJIT) Stock's Recent Performance A Reflection Of Its Financial Health? - Simply Wall St [Last Updated On: January 4th, 2021] [Originally Added On: January 4th, 2021]
- Engineering CAD Software Market is Flourishing due to Rising Emergence of Technical Implementation Drives Growth by 2027 | TurboCAD, SketchUp,... [Last Updated On: January 4th, 2021] [Originally Added On: January 4th, 2021]
- Apple vs. Tesla: Which Offers Software Engineers the Biggest Salaries? - Dice Insights [Last Updated On: January 4th, 2021] [Originally Added On: January 4th, 2021]
- From the classroom: Mechanical engineering at global top 10 uni - Study International News [Last Updated On: January 4th, 2021] [Originally Added On: January 4th, 2021]
- 'A lot of unknowns': Grass Valley Assistant City Engineer Bjorn Jones said the city has adapted under the pandemic - The Union of Grass Valley [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- Associate Professor in Broadcast Engineering job with BIRMINGHAM CITY UNIVERSITY | 243677 - Times Higher Education (THE) [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- CORRECTING and REPLACING: KCI, One of the Top Engineering Firms in the US, Adopts ProStar's PointMan SaaS Solution for SUE - Business Wire [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- Purdue's online engineering graduate programs again rank in the top 3 nationally - Purdue News Service [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- Faculty Positions of Intelligent Engineering and Microelectronics job with South China University of Technology (SCUT) | 314652 - The Chronicle of... [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- Examining the Engineering of the Kasukabe Reservoir in Japan - Interesting Engineering [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- Home - Springer [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- SIA Engineering ekes out small profit in third quarter - Flightglobal [Last Updated On: February 2nd, 2021] [Originally Added On: February 2nd, 2021]
- ST Engineering Launches Anti-Microbial Solution Approved for Use in Cabin Interiors - AviationPros.com [Last Updated On: February 2nd, 2021] [Originally Added On: February 2nd, 2021]
- Journey Engineering announces the addition of a new VP and Principal, Projects and Engineering - BOE Report [Last Updated On: February 2nd, 2021] [Originally Added On: February 2nd, 2021]
- K-2 Ventures Advises Mark Two Engineering on Its Sale to CORE Industrial Partners - Business Wire [Last Updated On: February 2nd, 2021] [Originally Added On: February 2nd, 2021]
- Global Engineering Liability Insurance Market latest demand by 2020-2025 with leading players & COVID-19 Analysis KSU | The Sentinel Newspaper -... [Last Updated On: February 2nd, 2021] [Originally Added On: February 2nd, 2021]
- First recipient of the Black Engineer of the Year Award is appointed Deans' Professor in Education and Engineering - BlackEngineer.com [Last Updated On: February 2nd, 2021] [Originally Added On: February 2nd, 2021]
- Google will pay $2.5 million to underpaid female engineers and overlooked Asian applicants - The Verge [Last Updated On: February 2nd, 2021] [Originally Added On: February 2nd, 2021]
- Clay County teen whose dream is to be an astronaut introduces other girls to STEM pursuits - The Florida Times-Union [Last Updated On: February 2nd, 2021] [Originally Added On: February 2nd, 2021]
- Universal Engineering Sciences Strengthens Western Expansion By Acquiring Construction Testing & Engineering, Inc., In Southern California -... [Last Updated On: February 2nd, 2021] [Originally Added On: February 2nd, 2021]
- U.S. Navy Has Patents on Tech It Says Will Engineer the Fabric of Reality - VICE [Last Updated On: February 5th, 2021] [Originally Added On: February 5th, 2021]
- Cummins and Isuzu collaborate on mid-range powertrains and advanced engineering - Engine Technology International [Last Updated On: February 5th, 2021] [Originally Added On: February 5th, 2021]
- Liberty engineering teams helmet prototype earns second place in NFLs 1st and Future competition - WFXRtv.com [Last Updated On: February 5th, 2021] [Originally Added On: February 5th, 2021]
- FM Global executive on the insurer's risk-engineering based approach - Insurance Business Australia [Last Updated On: February 5th, 2021] [Originally Added On: February 5th, 2021]
- Black former NASA engineer: We have to teach our children well - WFXRtv.com [Last Updated On: February 5th, 2021] [Originally Added On: February 5th, 2021]
- Cummins and Isuzu announce global mid-range powertrain and advanced engineering collaboration - Automotive World [Last Updated On: February 5th, 2021] [Originally Added On: February 5th, 2021]
- University of Iowa College of Engineering receives diversity recognition, but still has work to do - UI The Daily Iowan [Last Updated On: February 5th, 2021] [Originally Added On: February 5th, 2021]
- Darin Gray Named Engineer of the Year - USC Viterbi | School of Engineering - USC Viterbi School of Engineering [Last Updated On: February 5th, 2021] [Originally Added On: February 5th, 2021]
- Rubrik transitions to new phase as sales and engineering heads leave Blocks and Files - Blocks and Files [Last Updated On: February 5th, 2021] [Originally Added On: February 5th, 2021]
- A*Star scientist Jackie Ying elected to prestigious US engineering academy based on work in Singapore - The Straits Times [Last Updated On: February 14th, 2021] [Originally Added On: February 14th, 2021]
- A Disillusioned ExxonMobil Engineer Quits to Take Action on Climate Change and Stop Making the World Worse - InsideClimate News [Last Updated On: February 14th, 2021] [Originally Added On: February 14th, 2021]
- USC Junior Advances Communities By Engineering Infrastructures That Serve The People - USC Viterbi | School of Engineering - USC Viterbi School of... [Last Updated On: February 14th, 2021] [Originally Added On: February 14th, 2021]
- Join us on Saturday, Feb. 13 at 7:00 pm EST for the Black Engineer of the Year Awards - BlackEngineer.com [Last Updated On: February 14th, 2021] [Originally Added On: February 14th, 2021]
- Sebastian Ceria Elected to the National Academy of Engineering - Salamanca Press [Last Updated On: February 14th, 2021] [Originally Added On: February 14th, 2021]
- Three Harvard Professors Elected to the National Academy of Engineering | News - Harvard Crimson [Last Updated On: February 14th, 2021] [Originally Added On: February 14th, 2021]
- Newsmaker: South Shore native working on NASA space telescope - The Patriot Ledger [Last Updated On: February 14th, 2021] [Originally Added On: February 14th, 2021]