From 83137b6697b91c09bc359d3a4f139591e3fd6efc Mon Sep 17 00:00:00 2001 From: Ping Xie Date: Sun, 11 Feb 2024 23:25:43 -0800 Subject: [PATCH 01/16] feat(vector store): Add usage demo and enhance Redis integration - Add Jupyter notebook in `docs/` for using langchain vector store with Memorystore Redis. - Update `vector_store.py` for improved performance and reliability with Redis. - Modify `__init__.py` to reflect package structure changes and new functionalities. - Include `requirements.txt` and `setup.py` for easy installation and dependency management. - Add `state_of_the_union.txt` in `docs/` as a sample dataset for the notebook demo. --- docs/state_of_the_union.txt | 723 ++++++++++++++++++ docs/vector_store.ipynb | 423 ++++++++-- requirements.txt | 3 + setup.py | 27 + .../__init__.py | 10 +- .../vector_store.py | 46 +- 6 files changed, 1142 insertions(+), 90 deletions(-) create mode 100644 docs/state_of_the_union.txt create mode 100644 requirements.txt create mode 100644 setup.py diff --git a/docs/state_of_the_union.txt b/docs/state_of_the_union.txt new file mode 100644 index 0000000..b453aac --- /dev/null +++ b/docs/state_of_the_union.txt @@ -0,0 +1,723 @@ +Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and the Cabinet. Justices of the Supreme Court. My fellow Americans. + +Last year COVID-19 kept us apart. This year we are finally together again. + +Tonight, we meet as Democrats Republicans and Independents. But most importantly as Americans. + +With a duty to one another to the American people to the Constitution. + +And with an unwavering resolve that freedom will always triumph over tyranny. + +Six days ago, Russia’s Vladimir Putin sought to shake the foundations of the free world thinking he could make it bend to his menacing ways. But he badly miscalculated. + +He thought he could roll into Ukraine and the world would roll over. Instead he met a wall of strength he never imagined. + +He met the Ukrainian people. + +From President Zelenskyy to every Ukrainian, their fearlessness, their courage, their determination, inspires the world. + +Groups of citizens blocking tanks with their bodies. Everyone from students to retirees teachers turned soldiers defending their homeland. + +In this struggle as President Zelenskyy said in his speech to the European Parliament “Light will win over darkness.” The Ukrainian Ambassador to the United States is here tonight. + +Let each of us here tonight in this Chamber send an unmistakable signal to Ukraine and to the world. + +Please rise if you are able and show that, Yes, we the United States of America stand with the Ukrainian people. + +Throughout our history we’ve learned this lesson when dictators do not pay a price for their aggression they cause more chaos. + +They keep moving. + +And the costs and the threats to America and the world keep rising. + +That’s why the NATO Alliance was created to secure peace and stability in Europe after World War 2. + +The United States is a member along with 29 other nations. + +It matters. American diplomacy matters. American resolve matters. + +Putin’s latest attack on Ukraine was premeditated and unprovoked. + +He rejected repeated efforts at diplomacy. + +He thought the West and NATO wouldn’t respond. And he thought he could divide us at home. Putin was wrong. We were ready. Here is what we did. + +We prepared extensively and carefully. + +We spent months building a coalition of other freedom-loving nations from Europe and the Americas to Asia and Africa to confront Putin. + +I spent countless hours unifying our European allies. We shared with the world in advance what we knew Putin was planning and precisely how he would try to falsely justify his aggression. + +We countered Russia’s lies with truth. + +And now that he has acted the free world is holding him accountable. + +Along with twenty-seven members of the European Union including France, Germany, Italy, as well as countries like the United Kingdom, Canada, Japan, Korea, Australia, New Zealand, and many others, even Switzerland. + +We are inflicting pain on Russia and supporting the people of Ukraine. Putin is now isolated from the world more than ever. + +Together with our allies –we are right now enforcing powerful economic sanctions. + +We are cutting off Russia’s largest banks from the international financial system. + +Preventing Russia’s central bank from defending the Russian Ruble making Putin’s $630 Billion “war fund” worthless. + +We are choking off Russia’s access to technology that will sap its economic strength and weaken its military for years to come. + +Tonight I say to the Russian oligarchs and corrupt leaders who have bilked billions of dollars off this violent regime no more. + +The U.S. Department of Justice is assembling a dedicated task force to go after the crimes of Russian oligarchs. + +We are joining with our European allies to find and seize your yachts your luxury apartments your private jets. We are coming for your ill-begotten gains. + +And tonight I am announcing that we will join our allies in closing off American air space to all Russian flights – further isolating Russia – and adding an additional squeeze –on their economy. The Ruble has lost 30% of its value. + +The Russian stock market has lost 40% of its value and trading remains suspended. Russia’s economy is reeling and Putin alone is to blame. + +Together with our allies we are providing support to the Ukrainians in their fight for freedom. Military assistance. Economic assistance. Humanitarian assistance. + +We are giving more than $1 Billion in direct assistance to Ukraine. + +And we will continue to aid the Ukrainian people as they defend their country and to help ease their suffering. + +Let me be clear, our forces are not engaged and will not engage in conflict with Russian forces in Ukraine. + +Our forces are not going to Europe to fight in Ukraine, but to defend our NATO Allies – in the event that Putin decides to keep moving west. + +For that purpose we’ve mobilized American ground forces, air squadrons, and ship deployments to protect NATO countries including Poland, Romania, Latvia, Lithuania, and Estonia. + +As I have made crystal clear the United States and our Allies will defend every inch of territory of NATO countries with the full force of our collective power. + +And we remain clear-eyed. The Ukrainians are fighting back with pure courage. But the next few days weeks, months, will be hard on them. + +Putin has unleashed violence and chaos. But while he may make gains on the battlefield – he will pay a continuing high price over the long run. + +And a proud Ukrainian people, who have known 30 years of independence, have repeatedly shown that they will not tolerate anyone who tries to take their country backwards. + +To all Americans, I will be honest with you, as I’ve always promised. A Russian dictator, invading a foreign country, has costs around the world. + +And I’m taking robust action to make sure the pain of our sanctions is targeted at Russia’s economy. And I will use every tool at our disposal to protect American businesses and consumers. + +Tonight, I can announce that the United States has worked with 30 other countries to release 60 Million barrels of oil from reserves around the world. + +America will lead that effort, releasing 30 Million barrels from our own Strategic Petroleum Reserve. And we stand ready to do more if necessary, unified with our allies. + +These steps will help blunt gas prices here at home. And I know the news about what’s happening can seem alarming. + +But I want you to know that we are going to be okay. + +When the history of this era is written Putin’s war on Ukraine will have left Russia weaker and the rest of the world stronger. + +While it shouldn’t have taken something so terrible for people around the world to see what’s at stake now everyone sees it clearly. + +We see the unity among leaders of nations and a more unified Europe a more unified West. And we see unity among the people who are gathering in cities in large crowds around the world even in Russia to demonstrate their support for Ukraine. + +In the battle between democracy and autocracy, democracies are rising to the moment, and the world is clearly choosing the side of peace and security. + +This is a real test. It’s going to take time. So let us continue to draw inspiration from the iron will of the Ukrainian people. + +To our fellow Ukrainian Americans who forge a deep bond that connects our two nations we stand with you. + +Putin may circle Kyiv with tanks, but he will never gain the hearts and souls of the Ukrainian people. + +He will never extinguish their love of freedom. He will never weaken the resolve of the free world. + +We meet tonight in an America that has lived through two of the hardest years this nation has ever faced. + +The pandemic has been punishing. + +And so many families are living paycheck to paycheck, struggling to keep up with the rising cost of food, gas, housing, and so much more. + +I understand. + +I remember when my Dad had to leave our home in Scranton, Pennsylvania to find work. I grew up in a family where if the price of food went up, you felt it. + +That’s why one of the first things I did as President was fight to pass the American Rescue Plan. + +Because people were hurting. We needed to act, and we did. + +Few pieces of legislation have done more in a critical moment in our history to lift us out of crisis. + +It fueled our efforts to vaccinate the nation and combat COVID-19. It delivered immediate economic relief for tens of millions of Americans. + +Helped put food on their table, keep a roof over their heads, and cut the cost of health insurance. + +And as my Dad used to say, it gave people a little breathing room. + +And unlike the $2 Trillion tax cut passed in the previous administration that benefitted the top 1% of Americans, the American Rescue Plan helped working people—and left no one behind. + +And it worked. It created jobs. Lots of jobs. + +In fact—our economy created over 6.5 Million new jobs just last year, more jobs created in one year +than ever before in the history of America. + +Our economy grew at a rate of 5.7% last year, the strongest growth in nearly 40 years, the first step in bringing fundamental change to an economy that hasn’t worked for the working people of this nation for too long. + +For the past 40 years we were told that if we gave tax breaks to those at the very top, the benefits would trickle down to everyone else. + +But that trickle-down theory led to weaker economic growth, lower wages, bigger deficits, and the widest gap between those at the top and everyone else in nearly a century. + +Vice President Harris and I ran for office with a new economic vision for America. + +Invest in America. Educate Americans. Grow the workforce. Build the economy from the bottom up +and the middle out, not from the top down. + +Because we know that when the middle class grows, the poor have a ladder up and the wealthy do very well. + +America used to have the best roads, bridges, and airports on Earth. + +Now our infrastructure is ranked 13th in the world. + +We won’t be able to compete for the jobs of the 21st Century if we don’t fix that. + +That’s why it was so important to pass the Bipartisan Infrastructure Law—the most sweeping investment to rebuild America in history. + +This was a bipartisan effort, and I want to thank the members of both parties who worked to make it happen. + +We’re done talking about infrastructure weeks. + +We’re going to have an infrastructure decade. + +It is going to transform America and put us on a path to win the economic competition of the 21st Century that we face with the rest of the world—particularly with China. + +As I’ve told Xi Jinping, it is never a good bet to bet against the American people. + +We’ll create good jobs for millions of Americans, modernizing roads, airports, ports, and waterways all across America. + +And we’ll do it all to withstand the devastating effects of the climate crisis and promote environmental justice. + +We’ll build a national network of 500,000 electric vehicle charging stations, begin to replace poisonous lead pipes—so every child—and every American—has clean water to drink at home and at school, provide affordable high-speed internet for every American—urban, suburban, rural, and tribal communities. + +4,000 projects have already been announced. + +And tonight, I’m announcing that this year we will start fixing over 65,000 miles of highway and 1,500 bridges in disrepair. + +When we use taxpayer dollars to rebuild America – we are going to Buy American: buy American products to support American jobs. + +The federal government spends about $600 Billion a year to keep the country safe and secure. + +There’s been a law on the books for almost a century +to make sure taxpayers’ dollars support American jobs and businesses. + +Every Administration says they’ll do it, but we are actually doing it. + +We will buy American to make sure everything from the deck of an aircraft carrier to the steel on highway guardrails are made in America. + +But to compete for the best jobs of the future, we also need to level the playing field with China and other competitors. + +That’s why it is so important to pass the Bipartisan Innovation Act sitting in Congress that will make record investments in emerging technologies and American manufacturing. + +Let me give you one example of why it’s so important to pass it. + +If you travel 20 miles east of Columbus, Ohio, you’ll find 1,000 empty acres of land. + +It won’t look like much, but if you stop and look closely, you’ll see a “Field of dreams,” the ground on which America’s future will be built. + +This is where Intel, the American company that helped build Silicon Valley, is going to build its $20 billion semiconductor “mega site”. + +Up to eight state-of-the-art factories in one place. 10,000 new good-paying jobs. + +Some of the most sophisticated manufacturing in the world to make computer chips the size of a fingertip that power the world and our everyday lives. + +Smartphones. The Internet. Technology we have yet to invent. + +But that’s just the beginning. + +Intel’s CEO, Pat Gelsinger, who is here tonight, told me they are ready to increase their investment from +$20 billion to $100 billion. + +That would be one of the biggest investments in manufacturing in American history. + +And all they’re waiting for is for you to pass this bill. + +So let’s not wait any longer. Send it to my desk. I’ll sign it. + +And we will really take off. + +And Intel is not alone. + +There’s something happening in America. + +Just look around and you’ll see an amazing story. + +The rebirth of the pride that comes from stamping products “Made In America.” The revitalization of American manufacturing. + +Companies are choosing to build new factories here, when just a few years ago, they would have built them overseas. + +That’s what is happening. Ford is investing $11 billion to build electric vehicles, creating 11,000 jobs across the country. + +GM is making the largest investment in its history—$7 billion to build electric vehicles, creating 4,000 jobs in Michigan. + +All told, we created 369,000 new manufacturing jobs in America just last year. + +Powered by people I’ve met like JoJo Burgess, from generations of union steelworkers from Pittsburgh, who’s here with us tonight. + +As Ohio Senator Sherrod Brown says, “It’s time to bury the label “Rust Belt.” + +It’s time. + +But with all the bright spots in our economy, record job growth and higher wages, too many families are struggling to keep up with the bills. + +Inflation is robbing them of the gains they might otherwise feel. + +I get it. That’s why my top priority is getting prices under control. + +Look, our economy roared back faster than most predicted, but the pandemic meant that businesses had a hard time hiring enough workers to keep up production in their factories. + +The pandemic also disrupted global supply chains. + +When factories close, it takes longer to make goods and get them from the warehouse to the store, and prices go up. + +Look at cars. + +Last year, there weren’t enough semiconductors to make all the cars that people wanted to buy. + +And guess what, prices of automobiles went up. + +So—we have a choice. + +One way to fight inflation is to drive down wages and make Americans poorer. + +I have a better plan to fight inflation. + +Lower your costs, not your wages. + +Make more cars and semiconductors in America. + +More infrastructure and innovation in America. + +More goods moving faster and cheaper in America. + +More jobs where you can earn a good living in America. + +And instead of relying on foreign supply chains, let’s make it in America. + +Economists call it “increasing the productive capacity of our economy.” + +I call it building a better America. + +My plan to fight inflation will lower your costs and lower the deficit. + +17 Nobel laureates in economics say my plan will ease long-term inflationary pressures. Top business leaders and most Americans support my plan. And here’s the plan: + +First – cut the cost of prescription drugs. Just look at insulin. One in ten Americans has diabetes. In Virginia, I met a 13-year-old boy named Joshua Davis. + +He and his Dad both have Type 1 diabetes, which means they need insulin every day. Insulin costs about $10 a vial to make. + +But drug companies charge families like Joshua and his Dad up to 30 times more. I spoke with Joshua’s mom. + +Imagine what it’s like to look at your child who needs insulin and have no idea how you’re going to pay for it. + +What it does to your dignity, your ability to look your child in the eye, to be the parent you expect to be. + +Joshua is here with us tonight. Yesterday was his birthday. Happy birthday, buddy. + +For Joshua, and for the 200,000 other young people with Type 1 diabetes, let’s cap the cost of insulin at $35 a month so everyone can afford it. + +Drug companies will still do very well. And while we’re at it let Medicare negotiate lower prices for prescription drugs, like the VA already does. + +Look, the American Rescue Plan is helping millions of families on Affordable Care Act plans save $2,400 a year on their health care premiums. Let’s close the coverage gap and make those savings permanent. + +Second – cut energy costs for families an average of $500 a year by combatting climate change. + +Let’s provide investments and tax credits to weatherize your homes and businesses to be energy efficient and you get a tax credit; double America’s clean energy production in solar, wind, and so much more; lower the price of electric vehicles, saving you another $80 a month because you’ll never have to pay at the gas pump again. + +Third – cut the cost of child care. Many families pay up to $14,000 a year for child care per child. + +Middle-class and working families shouldn’t have to pay more than 7% of their income for care of young children. + +My plan will cut the cost in half for most families and help parents, including millions of women, who left the workforce during the pandemic because they couldn’t afford child care, to be able to get back to work. + +My plan doesn’t stop there. It also includes home and long-term care. More affordable housing. And Pre-K for every 3- and 4-year-old. + +All of these will lower costs. + +And under my plan, nobody earning less than $400,000 a year will pay an additional penny in new taxes. Nobody. + +The one thing all Americans agree on is that the tax system is not fair. We have to fix it. + +I’m not looking to punish anyone. But let’s make sure corporations and the wealthiest Americans start paying their fair share. + +Just last year, 55 Fortune 500 corporations earned $40 billion in profits and paid zero dollars in federal income tax. + +That’s simply not fair. That’s why I’ve proposed a 15% minimum tax rate for corporations. + +We got more than 130 countries to agree on a global minimum tax rate so companies can’t get out of paying their taxes at home by shipping jobs and factories overseas. + +That’s why I’ve proposed closing loopholes so the very wealthy don’t pay a lower tax rate than a teacher or a firefighter. + +So that’s my plan. It will grow the economy and lower costs for families. + +So what are we waiting for? Let’s get this done. And while you’re at it, confirm my nominees to the Federal Reserve, which plays a critical role in fighting inflation. + +My plan will not only lower costs to give families a fair shot, it will lower the deficit. + +The previous Administration not only ballooned the deficit with tax cuts for the very wealthy and corporations, it undermined the watchdogs whose job was to keep pandemic relief funds from being wasted. + +But in my administration, the watchdogs have been welcomed back. + +We’re going after the criminals who stole billions in relief money meant for small businesses and millions of Americans. + +And tonight, I’m announcing that the Justice Department will name a chief prosecutor for pandemic fraud. + +By the end of this year, the deficit will be down to less than half what it was before I took office. + +The only president ever to cut the deficit by more than one trillion dollars in a single year. + +Lowering your costs also means demanding more competition. + +I’m a capitalist, but capitalism without competition isn’t capitalism. + +It’s exploitation—and it drives up prices. + +When corporations don’t have to compete, their profits go up, your prices go up, and small businesses and family farmers and ranchers go under. + +We see it happening with ocean carriers moving goods in and out of America. + +During the pandemic, these foreign-owned companies raised prices by as much as 1,000% and made record profits. + +Tonight, I’m announcing a crackdown on these companies overcharging American businesses and consumers. + +And as Wall Street firms take over more nursing homes, quality in those homes has gone down and costs have gone up. + +That ends on my watch. + +Medicare is going to set higher standards for nursing homes and make sure your loved ones get the care they deserve and expect. + +We’ll also cut costs and keep the economy going strong by giving workers a fair shot, provide more training and apprenticeships, hire them based on their skills not degrees. + +Let’s pass the Paycheck Fairness Act and paid leave. + +Raise the minimum wage to $15 an hour and extend the Child Tax Credit, so no one has to raise a family in poverty. + +Let’s increase Pell Grants and increase our historic support of HBCUs, and invest in what Jill—our First Lady who teaches full-time—calls America’s best-kept secret: community colleges. + +And let’s pass the PRO Act when a majority of workers want to form a union—they shouldn’t be stopped. + +When we invest in our workers, when we build the economy from the bottom up and the middle out together, we can do something we haven’t done in a long time: build a better America. + +For more than two years, COVID-19 has impacted every decision in our lives and the life of the nation. + +And I know you’re tired, frustrated, and exhausted. + +But I also know this. + +Because of the progress we’ve made, because of your resilience and the tools we have, tonight I can say +we are moving forward safely, back to more normal routines. + +We’ve reached a new moment in the fight against COVID-19, with severe cases down to a level not seen since last July. + +Just a few days ago, the Centers for Disease Control and Prevention—the CDC—issued new mask guidelines. + +Under these new guidelines, most Americans in most of the country can now be mask free. + +And based on the projections, more of the country will reach that point across the next couple of weeks. + +Thanks to the progress we have made this past year, COVID-19 need no longer control our lives. + +I know some are talking about “living with COVID-19”. Tonight – I say that we will never just accept living with COVID-19. + +We will continue to combat the virus as we do other diseases. And because this is a virus that mutates and spreads, we will stay on guard. + +Here are four common sense steps as we move forward safely. + +First, stay protected with vaccines and treatments. We know how incredibly effective vaccines are. If you’re vaccinated and boosted you have the highest degree of protection. + +We will never give up on vaccinating more Americans. Now, I know parents with kids under 5 are eager to see a vaccine authorized for their children. + +The scientists are working hard to get that done and we’ll be ready with plenty of vaccines when they do. + +We’re also ready with anti-viral treatments. If you get COVID-19, the Pfizer pill reduces your chances of ending up in the hospital by 90%. + +We’ve ordered more of these pills than anyone in the world. And Pfizer is working overtime to get us 1 Million pills this month and more than double that next month. + +And we’re launching the “Test to Treat” initiative so people can get tested at a pharmacy, and if they’re positive, receive antiviral pills on the spot at no cost. + +If you’re immunocompromised or have some other vulnerability, we have treatments and free high-quality masks. + +We’re leaving no one behind or ignoring anyone’s needs as we move forward. + +And on testing, we have made hundreds of millions of tests available for you to order for free. + +Even if you already ordered free tests tonight, I am announcing that you can order more from covidtests.gov starting next week. + +Second – we must prepare for new variants. Over the past year, we’ve gotten much better at detecting new variants. + +If necessary, we’ll be able to deploy new vaccines within 100 days instead of many more months or years. + +And, if Congress provides the funds we need, we’ll have new stockpiles of tests, masks, and pills ready if needed. + +I cannot promise a new variant won’t come. But I can promise you we’ll do everything within our power to be ready if it does. + +Third – we can end the shutdown of schools and businesses. We have the tools we need. + +It’s time for Americans to get back to work and fill our great downtowns again. People working from home can feel safe to begin to return to the office. + +We’re doing that here in the federal government. The vast majority of federal workers will once again work in person. + +Our schools are open. Let’s keep it that way. Our kids need to be in school. + +And with 75% of adult Americans fully vaccinated and hospitalizations down by 77%, most Americans can remove their masks, return to work, stay in the classroom, and move forward safely. + +We achieved this because we provided free vaccines, treatments, tests, and masks. + +Of course, continuing this costs money. + +I will soon send Congress a request. + +The vast majority of Americans have used these tools and may want to again, so I expect Congress to pass it quickly. + +Fourth, we will continue vaccinating the world. + +We’ve sent 475 Million vaccine doses to 112 countries, more than any other nation. + +And we won’t stop. + +We have lost so much to COVID-19. Time with one another. And worst of all, so much loss of life. + +Let’s use this moment to reset. Let’s stop looking at COVID-19 as a partisan dividing line and see it for what it is: A God-awful disease. + +Let’s stop seeing each other as enemies, and start seeing each other for who we really are: Fellow Americans. + +We can’t change how divided we’ve been. But we can change how we move forward—on COVID-19 and other issues we must face together. + +I recently visited the New York City Police Department days after the funerals of Officer Wilbert Mora and his partner, Officer Jason Rivera. + +They were responding to a 9-1-1 call when a man shot and killed them with a stolen gun. + +Officer Mora was 27 years old. + +Officer Rivera was 22. + +Both Dominican Americans who’d grown up on the same streets they later chose to patrol as police officers. + +I spoke with their families and told them that we are forever in debt for their sacrifice, and we will carry on their mission to restore the trust and safety every community deserves. + +I’ve worked on these issues a long time. + +I know what works: Investing in crime prevention and community police officers who’ll walk the beat, who’ll know the neighborhood, and who can restore trust and safety. + +So let’s not abandon our streets. Or choose between safety and equal justice. + +Let’s come together to protect our communities, restore trust, and hold law enforcement accountable. + +That’s why the Justice Department required body cameras, banned chokeholds, and restricted no-knock warrants for its officers. + +That’s why the American Rescue Plan provided $350 Billion that cities, states, and counties can use to hire more police and invest in proven strategies like community violence interruption—trusted messengers breaking the cycle of violence and trauma and giving young people hope. + +We should all agree: The answer is not to Defund the police. The answer is to FUND the police with the resources and training they need to protect our communities. + +I ask Democrats and Republicans alike: Pass my budget and keep our neighborhoods safe. + +And I will keep doing everything in my power to crack down on gun trafficking and ghost guns you can buy online and make at home—they have no serial numbers and can’t be traced. + +And I ask Congress to pass proven measures to reduce gun violence. Pass universal background checks. Why should anyone on a terrorist list be able to purchase a weapon? + +Ban assault weapons and high-capacity magazines. + +Repeal the liability shield that makes gun manufacturers the only industry in America that can’t be sued. + +These laws don’t infringe on the Second Amendment. They save lives. + +The most fundamental right in America is the right to vote – and to have it counted. And it’s under assault. + +In state after state, new laws have been passed, not only to suppress the vote, but to subvert entire elections. + +We cannot let this happen. + +Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. + +Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. + +One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. + +And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence. + +A former top litigator in private practice. A former federal public defender. And from a family of public school educators and police officers. A consensus builder. Since she’s been nominated, she’s received a broad range of support—from the Fraternal Order of Police to former judges appointed by Democrats and Republicans. + +And if we are to advance liberty and justice, we need to secure the Border and fix the immigration system. + +We can do both. At our border, we’ve installed new technology like cutting-edge scanners to better detect drug smuggling. + +We’ve set up joint patrols with Mexico and Guatemala to catch more human traffickers. + +We’re putting in place dedicated immigration judges so families fleeing persecution and violence can have their cases heard faster. + +We’re securing commitments and supporting partners in South and Central America to host more refugees and secure their own borders. + +We can do all this while keeping lit the torch of liberty that has led generations of immigrants to this land—my forefathers and so many of yours. + +Provide a pathway to citizenship for Dreamers, those on temporary status, farm workers, and essential workers. + +Revise our laws so businesses have the workers they need and families don’t wait decades to reunite. + +It’s not only the right thing to do—it’s the economically smart thing to do. + +That’s why immigration reform is supported by everyone from labor unions to religious leaders to the U.S. Chamber of Commerce. + +Let’s get it done once and for all. + +Advancing liberty and justice also requires protecting the rights of women. + +The constitutional right affirmed in Roe v. Wade—standing precedent for half a century—is under attack as never before. + +If we want to go forward—not backward—we must protect access to health care. Preserve a woman’s right to choose. And let’s continue to advance maternal health care in America. + +And for our LGBTQ+ Americans, let’s finally get the bipartisan Equality Act to my desk. The onslaught of state laws targeting transgender Americans and their families is wrong. + +As I said last year, especially to our younger transgender Americans, I will always have your back as your President, so you can be yourself and reach your God-given potential. + +While it often appears that we never agree, that isn’t true. I signed 80 bipartisan bills into law last year. From preventing government shutdowns to protecting Asian-Americans from still-too-common hate crimes to reforming military justice. + +And soon, we’ll strengthen the Violence Against Women Act that I first wrote three decades ago. It is important for us to show the nation that we can come together and do big things. + +So tonight I’m offering a Unity Agenda for the Nation. Four big things we can do together. + +First, beat the opioid epidemic. + +There is so much we can do. Increase funding for prevention, treatment, harm reduction, and recovery. + +Get rid of outdated rules that stop doctors from prescribing treatments. And stop the flow of illicit drugs by working with state and local law enforcement to go after traffickers. + +If you’re suffering from addiction, know you are not alone. I believe in recovery, and I celebrate the 23 million Americans in recovery. + +Second, let’s take on mental health. Especially among our children, whose lives and education have been turned upside down. + +The American Rescue Plan gave schools money to hire teachers and help students make up for lost learning. + +I urge every parent to make sure your school does just that. And we can all play a part—sign up to be a tutor or a mentor. + +Children were also struggling before the pandemic. Bullying, violence, trauma, and the harms of social media. + +As Frances Haugen, who is here with us tonight, has shown, we must hold social media platforms accountable for the national experiment they’re conducting on our children for profit. + +It’s time to strengthen privacy protections, ban targeted advertising to children, demand tech companies stop collecting personal data on our children. + +And let’s get all Americans the mental health services they need. More people they can turn to for help, and full parity between physical and mental health care. + +Third, support our veterans. + +Veterans are the best of us. + +I’ve always believed that we have a sacred obligation to equip all those we send to war and care for them and their families when they come home. + +My administration is providing assistance with job training and housing, and now helping lower-income veterans get VA care debt-free. + +Our troops in Iraq and Afghanistan faced many dangers. + +One was stationed at bases and breathing in toxic smoke from “burn pits” that incinerated wastes of war—medical and hazard material, jet fuel, and more. + +When they came home, many of the world’s fittest and best trained warriors were never the same. + +Headaches. Numbness. Dizziness. + +A cancer that would put them in a flag-draped coffin. + +I know. + +One of those soldiers was my son Major Beau Biden. + +We don’t know for sure if a burn pit was the cause of his brain cancer, or the diseases of so many of our troops. + +But I’m committed to finding out everything we can. + +Committed to military families like Danielle Robinson from Ohio. + +The widow of Sergeant First Class Heath Robinson. + +He was born a soldier. Army National Guard. Combat medic in Kosovo and Iraq. + +Stationed near Baghdad, just yards from burn pits the size of football fields. + +Heath’s widow Danielle is here with us tonight. They loved going to Ohio State football games. He loved building Legos with their daughter. + +But cancer from prolonged exposure to burn pits ravaged Heath’s lungs and body. + +Danielle says Heath was a fighter to the very end. + +He didn’t know how to stop fighting, and neither did she. + +Through her pain she found purpose to demand we do better. + +Tonight, Danielle—we are. + +The VA is pioneering new ways of linking toxic exposures to diseases, already helping more veterans get benefits. + +And tonight, I’m announcing we’re expanding eligibility to veterans suffering from nine respiratory cancers. + +I’m also calling on Congress: pass a law to make sure veterans devastated by toxic exposures in Iraq and Afghanistan finally get the benefits and comprehensive health care they deserve. + +And fourth, let’s end cancer as we know it. + +This is personal to me and Jill, to Kamala, and to so many of you. + +Cancer is the #2 cause of death in America–second only to heart disease. + +Last month, I announced our plan to supercharge +the Cancer Moonshot that President Obama asked me to lead six years ago. + +Our goal is to cut the cancer death rate by at least 50% over the next 25 years, turn more cancers from death sentences into treatable diseases. + +More support for patients and families. + +To get there, I call on Congress to fund ARPA-H, the Advanced Research Projects Agency for Health. + +It’s based on DARPA—the Defense Department project that led to the Internet, GPS, and so much more. + +ARPA-H will have a singular purpose—to drive breakthroughs in cancer, Alzheimer’s, diabetes, and more. + +A unity agenda for the nation. + +We can do this. + +My fellow Americans—tonight , we have gathered in a sacred space—the citadel of our democracy. + +In this Capitol, generation after generation, Americans have debated great questions amid great strife, and have done great things. + +We have fought for freedom, expanded liberty, defeated totalitarianism and terror. + +And built the strongest, freest, and most prosperous nation the world has ever known. + +Now is the hour. + +Our moment of responsibility. + +Our test of resolve and conscience, of history itself. + +It is in this moment that our character is formed. Our purpose is found. Our future is forged. + +Well I know this nation. + +We will meet the test. + +To protect freedom and liberty, to expand fairness and opportunity. + +We will save democracy. + +As hard as these times have been, I am more optimistic about America today than I have been my whole life. + +Because I see the future that is within our grasp. + +Because I know there is simply nothing beyond our capacity. + +We are the only nation on Earth that has always turned every crisis we have faced into an opportunity. + +The only nation that can be defined by a single word: possibilities. + +So on this night, in our 245th year as a nation, I have come to report on the State of the Union. + +And my report is this: the State of the Union is strong—because you, the American people, are strong. + +We are stronger today than we were a year ago. + +And we will be stronger a year from now than we are today. + +Now is our moment to meet and overcome the challenges of our time. + +And we will, as one people. + +One America. + +The United States of America. + +May God bless you all. May God protect our troops. \ No newline at end of file diff --git a/docs/vector_store.ipynb b/docs/vector_store.ipynb index 8b1a4cf..b837e47 100644 --- a/docs/vector_store.ipynb +++ b/docs/vector_store.ipynb @@ -1,79 +1,348 @@ { - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Google DATABASE\n", - "\n", - "[Google DATABASE](https://cloud.google.com/DATABASE).\n", - "\n", - "Save chat messages into `DATABASE`." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Pre-reqs" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [ - "%pip install PACKAGE_NAME" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [ - "from PACKAGE import LOADER" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Basic Usage" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3 (ipykernel)", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.10.6" - } - }, - "nbformat": 4, - "nbformat_minor": 4 + "cells": [ + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Google Database\n", + "\n", + "Use [Google Memorystore for Redis](https://cloud.google.com/memorystore) as a vector store for LangChain." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Pre-reqs" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Setting Up a Memorystore Redis Instance\n", + "\n", + "Before proceeding, an active Memorystore Redis instance is needed to store vectors:\n", + "\n", + "* Create a Memorystore for Reids Instance (v7.2): If an instance doesn't exist, follow the instructions at https://cloud.google.com/memorystore/docs/redis/create-instance-console to create a new one. Ensure version 7.2 is selected.\n", + "* Obtain Endpoint: Note the endpoint associated with the instance." + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Installing the LangChain Memorystore Redis Module\n", + "\n", + "Interaction with the Memorystore for Redis instance from LangChain requires installing the necessary module:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "#Install Memorystore Redis for LangChain module\n", + "%pip install langchainlangchain_google_memorystore_redis" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Basic Usage" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Initialize a Vector Index" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [], + "source": [ + "import redis\n", + "from langchain_google_memorystore_redis import DistanceStrategy, HNSWConfig, RedisVectorStore\n", + "\n", + "# Connect to a Memorystore for Redis instance\n", + "redis_client = redis.from_url(\"redis://127.0.0.1:6379\")\n", + "\n", + "# Configure HNSW index with descriptive parameters\n", + "index_config = HNSWConfig(\n", + " name=\"my_vector_index\",\n", + " distance_strategy=DistanceStrategy.COSINE,\n", + " vector_size=128\n", + ")\n", + "\n", + "# Initialize/create the vector store index\n", + "RedisVectorStore.init_index(client=redis_client, index_config=index_config)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Prepare Documents\n", + "\n", + "Text needs processing and numerical representation before interacting with a vector store. This involves:\n", + "\n", + "* Loading Text: The TextLoader obtains text data from a file (e.g., \"state_of_the_union.txt\").\n", + "* Text Splitting: The CharacterTextSplitter breaks the text into smaller chunks for embedding models." + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [], + "source": [ + "from langchain.text_splitter import CharacterTextSplitter\n", + "from langchain_community.document_loaders import TextLoader\n", + "\n", + "loader = TextLoader(\"./state_of_the_union.txt\")\n", + "documents = loader.load()\n", + "text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)\n", + "docs = text_splitter.split_documents(documents)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Add Documents to the Vector Store\n", + "\n", + "After text preparation and embedding generation, the following methods insert them into the Redis vector store." + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Method 1: Classmethod for Direct Insertion\n", + "\n", + "This approach combines embedding creation and insertion into a single step using the from_documents classmethod:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from langchain_community.embeddings.fake import FakeEmbeddings\n", + "\n", + "embeddings = FakeEmbeddings(size=128)\n", + "redis_client = redis.from_url(\"redis://127.0.0.1:6379\")\n", + "rvs = RedisVectorStore.from_documents(docs, embedding=embeddings, client=redis_client, index_name=\"my_vector_index\")" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Method 2: Instance-Based Insertion\n", + "This approach offers flexibility when working with a new or existing RedisVectorStore:\n", + "\n", + "* [Optional] Create a RedisVectorStore Instance: Instantiate a RedisVectorStore object for customization. If you already have an instance, proceed to the next step.\n", + "* Add Text with Metadata: Provide raw text and metadata to the instance. Embedding generation and insertion into the vector store are handled automatically." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "rvs = RedisVectorStore(client=redis_client, index_name=\"my_vector_index\", embedding_service=embeddings)\n", + "ids = rvs.add_texts(texts=[d.page_content for d in docs], metadatas=[d.metadata for d in docs])" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Perfor a Similarity Search (KNN)\n", + "\n", + "With the vector store populated, it's possible to search for text semantically similar to a query. Here's how to use KNN (K-Nearest Neighbors) with default settings:\n", + "\n", + "* Formulate the Query: A natural language question expresses the search intent (e.g., \"What did the president say about Ketanji Brown Jackson\").\n", + "* Retrieve Similar Results: The `similarity_search` method finds items in the vector store closest in meaning to the query." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import pprint\n", + "\n", + "query=\"What did the president say about Ketanji Brown Jackson\"\n", + "knn_results = rvs.similarity_search(query=query)\n", + "pprint.pprint(knn_results)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Perform a Range-Based Similarity Search\n", + "\n", + "Range queries provide more control by specifying a desired similarity threshold along with the query text:\n", + "\n", + "* Formulate the Query: A natural language question defines the search intent.\n", + "* Set Similarity Threshold: The distance_threshold parameter determines how close a match needs to be considered relevant.\n", + "* Retrieve Results: The `similarity_search_with_score` method finds items from the vector store that fall within the specified similarity threshold." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "rq_results = rvs.similarity_search_with_score(query=query, distance_threshold=0.8)\n", + "pprint.pprint(rq_results)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Perform a Maximal Marginal Relevance (MMR) Search\n", + "\n", + "MMR queries aim to find results that are both relevant to the query and diverse from each other, reducing redundancy in search results.\n", + "\n", + "* Formulate the Query: A natural language question defines the search intent.\n", + "* Balance Relevance and Diversity: The lambda_mult parameter controls the trade-off between strict relevance and promoting variety in the results.\n", + "* Retrieve MMR Results: The `max_marginal_relevance_search` method returns items that optimize the combination of relevance and diversity based on the lambda setting." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "mmr_results = rvs.max_marginal_relevance_search(query=query,lambda_mult=0.90)\n", + "pprint.pprint(mmr_results)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Use the Vector Store as a Retriever\n", + "\n", + "For seamless integration with other LangChain components, a vector store can be converted into a Retriever. This offers several advantages:\n", + "\n", + "* LangChain Compatibility: Many LangChain tools and methods are designed to directly interact with retrievers.\n", + "* Ease of Use: The `as_retriever()` method converts the vector store into a format that simplifies querying." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "retriever = rvs.as_retriever()\n", + "results = retriever.invoke(query)\n", + "pprint.pprint(results)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Clean up" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Delete Documents from the Vector Store\n", + "\n", + "Occasionally, it's necessary to remove documents (and their associated vectors) from the vector store. The `delete` method provides this functionality." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "rvs.delete(ids)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Delete a Vector Index\n", + "\n", + "There might be circumstances where the deletion of an existing vector index is necessary. Common reasons include:\n", + "\n", + "* Index Configuration Changes: If index parameters need modification, it's often required to delete and recreate the index.\n", + "* Storage Management: Removing unused indices can help free up space within the Redis instance.\n", + "\n", + "Caution: Vector index deletion is an irreversible operation. Be certain that the stored vectors and search functionality are no longer required before proceeding." + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": {}, + "outputs": [], + "source": [ + "# Delete the vector index\n", + "RedisVectorStore.drop_index(client=redis_client, index_name=\"my_vector_index\")" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.11.6" + } + }, + "nbformat": 4, + "nbformat_minor": 4 } diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..e0c52a9 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,3 @@ +numpy +redis +langchain \ No newline at end of file diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..ac0eb2f --- /dev/null +++ b/setup.py @@ -0,0 +1,27 @@ +from setuptools import find_packages, setup + +# Metadata fields +package_name = 'langchain_google_memorystore_redis' # Corrected package name +author = 'Google Cloud Memorystore' +description = 'Memorystore for Redis integration for LangChain' +long_description = open('README.md').read() # Assuming you have a README.md +url = 'https://github.com/googleapis/langchain-google-memorystore-redis-python' + +# Create your requirements.txt (see previous instructions) +install_requires = [line.strip() for line in open("requirements.txt")] + +setup( + name=package_name, + version='0.1.0', # Start with an initial version + description=description, + long_description=long_description, + long_description_content_type='text/markdown', # If you have a Markdown README + author=author, + url=url, + # Specify the package directory and find packages within src + package_dir={'': 'src'}, # Specifies that the package(s) are under src + packages=find_packages(where='src'), # Tells setuptools to look for packages in src + install_requires=install_requires, + python_requires=">=3.7", # Adjust minimum Python version as needed + # Consider including additional package data, classifiers, etc. +) \ No newline at end of file diff --git a/src/langchain_google_memorystore_redis/__init__.py b/src/langchain_google_memorystore_redis/__init__.py index 830a5f1..11ee5b7 100644 --- a/src/langchain_google_memorystore_redis/__init__.py +++ b/src/langchain_google_memorystore_redis/__init__.py @@ -12,6 +12,12 @@ # See the License for the specific language governing permissions and # limitations under the License. from .chat_message_history import MemorystoreChatMessageHistory -from .vector_store import FLATConfig, HNSWConfig, RedisVectorStore +from .vector_store import DistanceStrategy, FLATConfig, HNSWConfig, RedisVectorStore -__all__ = ["MemorystoreChatMessageHistory"] +__all__ = [ + "MemorystoreChatMessageHistory", + "DistanceStrategy", + "FLATConfig", + "HNSWConfig", + "RedisVectorStore" +] \ No newline at end of file diff --git a/src/langchain_google_memorystore_redis/vector_store.py b/src/langchain_google_memorystore_redis/vector_store.py index 468b08e..81bfe92 100644 --- a/src/langchain_google_memorystore_redis/vector_store.py +++ b/src/langchain_google_memorystore_redis/vector_store.py @@ -15,6 +15,7 @@ import json import logging import operator +import pprint import re import uuid from abc import ABC @@ -37,7 +38,7 @@ # Setting up a basic logger logger = logging.getLogger(__name__) -logger.setLevel(logging.INFO) +logger.setLevel(logging.WARNING) handler = logging.StreamHandler() formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") handler.setFormatter(formatter) @@ -149,8 +150,8 @@ class HNSWConfig(VectorIndexConfig): def __init__( self, name: str, - field_name: str, - vector_size: int, + field_name = None, + vector_size: int = 128, distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, initial_cap: int = 10000, m: int = 16, @@ -184,6 +185,8 @@ def __init__( queries, balancing between search speed and accuracy. Defaults to 10. """ + if field_name is None: + field_name = RedisVectorStore.DEFAULT_VECTOR_FIELD super().__init__( name, field_name, "HNSW", distance_strategy, vector_size, "FLOAT32" ) @@ -201,8 +204,8 @@ class FLATConfig(VectorIndexConfig): def __init__( self, name: str, - field_name: str, - vector_size: int, + field_name = None, + vector_size: int = 128, distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, ): """ @@ -221,6 +224,8 @@ def __init__( search operations. Defaults to `DistanceStrategy.COSINE`, which measures the cosine similarity between vectors. """ + if field_name is None: + field_name = RedisVectorStore.DEFAULT_VECTOR_FIELD super().__init__( name, field_name, "FLAT", distance_strategy, vector_size, "FLOAT32" ) @@ -267,14 +272,32 @@ def __init__( when adding new documents to the store and when retrieving or searching documents based on their vector embeddings. Defaults to 'vector'. """ + if client == None: + raise ValueError( + "A Redis 'client' must be provided to initialize RedisVectorStore" + ) + + if index_name == None: + raise ValueError( + "A 'index_name' must be provided to initialize RedisVectorStore" + ) + + if embedding_service == None: + raise ValueError( + "An 'embedding_service' must be provided to initialize RedisVectorStore" + ) + self.client = client self.index_name = index_name self.embedding_service = embedding_service - self.key_prefix = key_prefix + ":" if key_prefix is not None else "" + self.key_prefix = self.get_key_prefix(index_name, key_prefix) self.content_field = content_field self.vector_field = vector_field - # Helper function to check if a string is JSON parsable + @staticmethod + def get_key_prefix(index_name: str, key_prefix: Optional[str] = None): + return key_prefix + ":" if key_prefix is not None else index_name + ":" + @staticmethod def _is_json_parsable(s: str) -> bool: try: @@ -293,12 +316,9 @@ def init_index( if not isinstance(index_config, HNSWConfig): raise ValueError("index_config must be an instance of HNSWConfig") - # Use the index name if no key_prefix is provided - key_prefix = key_prefix + ":" if key_prefix is not None else index_config.name - # Preparing the command string to avoid long lines command = ( - f"FT.CREATE {index_config.name} ON HASH PREFIX 1 {key_prefix} " + f"FT.CREATE {index_config.name} ON HASH PREFIX 1 {RedisVectorStore.get_key_prefix(index_config.name, key_prefix)} " f"SCHEMA {index_config.field_name} VECTOR {index_config.type} " f"6 TYPE {index_config.data_type} DIM {index_config.vector_size} " f"DISTANCE_METRIC {index_config.distance_metric}" @@ -423,6 +443,8 @@ def add_texts( # Final execution to catch any remaining items in the pipeline pipeline.execute() + logger.info(f"{len(ids)} documents ingested into Redis.") + return ids @classmethod @@ -525,6 +547,8 @@ def _similarity_search_by_vector_with_score_and_embeddings( initial_results = self.client.execute_command(*query_args) + logger.info(f'{int((len(initial_results)-1)/2)} documents returned by Redis') + # Process the results final_results: List[Tuple[Document, float, List[float]]] = [] From d334e7f14ed86e24def5b5ff5a765eb9828ccdac Mon Sep 17 00:00:00 2001 From: Ping Xie Date: Mon, 12 Feb 2024 15:45:33 -0800 Subject: [PATCH 02/16] incorporate review feedback --- .../vector_store.py | 31 ++++++++++--------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/src/langchain_google_memorystore_redis/vector_store.py b/src/langchain_google_memorystore_redis/vector_store.py index 81bfe92..a940f09 100644 --- a/src/langchain_google_memorystore_redis/vector_store.py +++ b/src/langchain_google_memorystore_redis/vector_store.py @@ -73,7 +73,7 @@ def __init__( data_type (str, optional): Defines the data type of the elements within the vector being indexed, such as "FLOAT32" for 32-bit floating-point numbers. This parameter is crucial for ensuring that the index - accommodates the vector data appropriately. Defaults to "FLOAT32". + accommodates the vector data appropriately. """ self.name = name @@ -95,7 +95,7 @@ def __init__( type: str, distance_strategy: DistanceStrategy, vector_size: int, - data_type: str, + data_type: str = "FLOAT32", ): """ Initializes the VectorIndexConfig object. @@ -113,9 +113,9 @@ def __init__( influencing how search results are ranked and returned. vector_size (int): The dimensionality of the vectors that will be stored and indexed. All vectors must conform to this specified size. - data_type (str, optional): The data type of the vector elements (e.g., "float32"). + data_type (str, optional): The data type of the vector elements (e.g., "FLOAT32"). This specifies the precision and format of the vector data, affecting storage - requirements and possibly search performance. Defaults to "float32". + requirements and possibly search performance. Defaults to "FLOAT32". """ if distance_strategy not in self.SUPPORTED_DISTANCE_STRATEGIES: supported_strategies = ", ".join( @@ -287,7 +287,7 @@ def __init__( "An 'embedding_service' must be provided to initialize RedisVectorStore" ) - self.client = client + self._client = client self.index_name = index_name self.embedding_service = embedding_service self.key_prefix = self.get_key_prefix(index_name, key_prefix) @@ -338,7 +338,7 @@ def init_index( # for FT.INFO in the client library. @staticmethod - def drop_index(client: redis.Redis, index_name: str, index_only: bool = False): + def drop_index(client: redis.Redis, index_name: str, index_only: bool = True): """ Drops an index from the Redis database. Optionally, it can also delete the documents associated with the index. @@ -350,7 +350,7 @@ def drop_index(client: redis.Redis, index_name: str, index_only: bool = False): match the name of the existing index in the Redis database. index_only (bool, optional): A flag indicating whether to drop only the index structure (True) or to also delete the documents associated with the index (False). - Defaults to False, implying that both the index and its documents will be deleted. + Defaults to True, implying that only the index will be deleted. Raises: redis.RedisError: If any Redis-specific error occurs during the operation. This @@ -358,8 +358,11 @@ def drop_index(client: redis.Redis, index_name: str, index_only: bool = False): the command to drop the index. Callers should handle these exceptions to manage error scenarios gracefully. """ + if (index_only == False) : + raise ValueError("Not supported") + command = ( - f"FT.DROPINDEX {index_name} {'KEEPDOCS' if index_only else ''}".strip() + f"FT.DROPINDEX {index_name} {'DD' if not index_only else ''}".strip() ) client.execute_command(command) @@ -408,7 +411,7 @@ def add_texts( embeddings = self.embedding_service.embed_documents(list(texts)) ids = [] - pipeline = self.client.pipeline(transaction=False) + pipeline = self._client.pipeline(transaction=False) for i, bundle in enumerate( zip_longest(keys_or_ids, texts, embeddings, metadatas), start=1 ): @@ -437,7 +440,7 @@ def add_texts( ids.append(key) # Ensure to execute any remaining commands in the pipeline after the loop - if i % batch_size != 0: + if i % batch_size == 0: pipeline.execute() # Final execution to catch any remaining items in the pipeline @@ -511,13 +514,13 @@ def from_texts( def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[bool]: if not ids: # Check if ids list is empty or None logger.info("No IDs provided for deletion.") - return None # Or False, depending on intended behavior when ids is empty or None + return False try: - self.client.delete(*ids) + self._client.delete(*ids) logger.info("Entries deleted.") return True - except Exception as e: # It's better to catch specific exceptions + except Exception as e: logger.error(f"Failed to delete entries: {e}") return False @@ -545,7 +548,7 @@ def _similarity_search_by_vector_with_score_and_embeddings( 2, ] - initial_results = self.client.execute_command(*query_args) + initial_results = self._client.execute_command(*query_args) logger.info(f'{int((len(initial_results)-1)/2)} documents returned by Redis') From 400ebfa14ef0d8481ca93559cfea2605950b6abe Mon Sep 17 00:00:00 2001 From: Ping Xie Date: Mon, 12 Feb 2024 15:57:14 -0800 Subject: [PATCH 03/16] added missing license header --- setup.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/setup.py b/setup.py index ac0eb2f..a98cfb4 100644 --- a/setup.py +++ b/setup.py @@ -1,3 +1,17 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + from setuptools import find_packages, setup # Metadata fields From 3263b91daaed745f395de133c3524f1c6bf05039 Mon Sep 17 00:00:00 2001 From: Ping Xie Date: Mon, 12 Feb 2024 17:40:08 -0800 Subject: [PATCH 04/16] excluded the test file from license check --- .github/header-checker-lint.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/header-checker-lint.yml b/.github/header-checker-lint.yml index 6fe78aa..f259a98 100644 --- a/.github/header-checker-lint.yml +++ b/.github/header-checker-lint.yml @@ -1,6 +1,6 @@ {"allowedCopyrightHolders": ["Google LLC"], "allowedLicenses": ["Apache-2.0", "MIT", "BSD-3"], - "ignoreFiles": ["**/requirements.txt", "**/requirements-test.txt", "**/__init__.py", "samples/**/constraints.txt", "samples/**/constraints-test.txt"], + "ignoreFiles": ["**/requirements.txt", "**/requirements-test.txt", "**/__init__.py", "samples/**/constraints.txt", "samples/**/constraints-test.txt", "docs/state_of_the_union.txt"], "sourceFileExtensions": [ "ts", "js", @@ -12,4 +12,4 @@ "html", "txt" ] -} \ No newline at end of file +} From 0cf5faa0df3390c26ee3cba3cf5e97303a30ad8e Mon Sep 17 00:00:00 2001 From: Ping Xie Date: Mon, 12 Feb 2024 17:42:57 -0800 Subject: [PATCH 05/16] reformatted source files --- setup.py | 20 +++++++++---------- .../__init__.py | 4 ++-- .../vector_store.py | 12 +++++------ 3 files changed, 17 insertions(+), 19 deletions(-) diff --git a/setup.py b/setup.py index a98cfb4..1f9b651 100644 --- a/setup.py +++ b/setup.py @@ -15,27 +15,27 @@ from setuptools import find_packages, setup # Metadata fields -package_name = 'langchain_google_memorystore_redis' # Corrected package name -author = 'Google Cloud Memorystore' -description = 'Memorystore for Redis integration for LangChain' -long_description = open('README.md').read() # Assuming you have a README.md -url = 'https://github.com/googleapis/langchain-google-memorystore-redis-python' +package_name = "langchain_google_memorystore_redis" # Corrected package name +author = "Google Cloud Memorystore" +description = "Memorystore for Redis integration for LangChain" +long_description = open("README.md").read() # Assuming you have a README.md +url = "https://github.com/googleapis/langchain-google-memorystore-redis-python" # Create your requirements.txt (see previous instructions) install_requires = [line.strip() for line in open("requirements.txt")] setup( name=package_name, - version='0.1.0', # Start with an initial version + version="0.1.0", # Start with an initial version description=description, long_description=long_description, - long_description_content_type='text/markdown', # If you have a Markdown README + long_description_content_type="text/markdown", # If you have a Markdown README author=author, url=url, # Specify the package directory and find packages within src - package_dir={'': 'src'}, # Specifies that the package(s) are under src - packages=find_packages(where='src'), # Tells setuptools to look for packages in src + package_dir={"": "src"}, # Specifies that the package(s) are under src + packages=find_packages(where="src"), # Tells setuptools to look for packages in src install_requires=install_requires, python_requires=">=3.7", # Adjust minimum Python version as needed # Consider including additional package data, classifiers, etc. -) \ No newline at end of file +) diff --git a/src/langchain_google_memorystore_redis/__init__.py b/src/langchain_google_memorystore_redis/__init__.py index 11ee5b7..dd49815 100644 --- a/src/langchain_google_memorystore_redis/__init__.py +++ b/src/langchain_google_memorystore_redis/__init__.py @@ -19,5 +19,5 @@ "DistanceStrategy", "FLATConfig", "HNSWConfig", - "RedisVectorStore" -] \ No newline at end of file + "RedisVectorStore", +] diff --git a/src/langchain_google_memorystore_redis/vector_store.py b/src/langchain_google_memorystore_redis/vector_store.py index a940f09..c9db4ce 100644 --- a/src/langchain_google_memorystore_redis/vector_store.py +++ b/src/langchain_google_memorystore_redis/vector_store.py @@ -150,7 +150,7 @@ class HNSWConfig(VectorIndexConfig): def __init__( self, name: str, - field_name = None, + field_name=None, vector_size: int = 128, distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, initial_cap: int = 10000, @@ -204,7 +204,7 @@ class FLATConfig(VectorIndexConfig): def __init__( self, name: str, - field_name = None, + field_name=None, vector_size: int = 128, distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, ): @@ -358,12 +358,10 @@ def drop_index(client: redis.Redis, index_name: str, index_only: bool = True): the command to drop the index. Callers should handle these exceptions to manage error scenarios gracefully. """ - if (index_only == False) : + if index_only == False: raise ValueError("Not supported") - command = ( - f"FT.DROPINDEX {index_name} {'DD' if not index_only else ''}".strip() - ) + command = f"FT.DROPINDEX {index_name} {'DD' if not index_only else ''}".strip() client.execute_command(command) def add_texts( @@ -550,7 +548,7 @@ def _similarity_search_by_vector_with_score_and_embeddings( initial_results = self._client.execute_command(*query_args) - logger.info(f'{int((len(initial_results)-1)/2)} documents returned by Redis') + logger.info(f"{int((len(initial_results)-1)/2)} documents returned by Redis") # Process the results final_results: List[Tuple[Document, float, List[float]]] = [] From 2e953f48b9de6eefae0ae3a47aa534c405c533f9 Mon Sep 17 00:00:00 2001 From: Ping Xie Date: Mon, 12 Feb 2024 18:39:20 -0800 Subject: [PATCH 06/16] incorporated review feedback --- docs/vector_store.ipynb | 28 +++-- .../vector_store.py | 101 +++++++++++------- 2 files changed, 82 insertions(+), 47 deletions(-) diff --git a/docs/vector_store.ipynb b/docs/vector_store.ipynb index b837e47..432434d 100644 --- a/docs/vector_store.ipynb +++ b/docs/vector_store.ipynb @@ -48,7 +48,7 @@ }, "outputs": [], "source": [ - "#Install Memorystore Redis for LangChain module\n", + "# Install Memorystore Redis for LangChain module\n", "%pip install langchainlangchain_google_memorystore_redis" ] }, @@ -74,16 +74,18 @@ "outputs": [], "source": [ "import redis\n", - "from langchain_google_memorystore_redis import DistanceStrategy, HNSWConfig, RedisVectorStore\n", + "from langchain_google_memorystore_redis import (\n", + " DistanceStrategy,\n", + " HNSWConfig,\n", + " RedisVectorStore,\n", + ")\n", "\n", "# Connect to a Memorystore for Redis instance\n", "redis_client = redis.from_url(\"redis://127.0.0.1:6379\")\n", "\n", "# Configure HNSW index with descriptive parameters\n", "index_config = HNSWConfig(\n", - " name=\"my_vector_index\",\n", - " distance_strategy=DistanceStrategy.COSINE,\n", - " vector_size=128\n", + " name=\"my_vector_index\", distance_strategy=DistanceStrategy.COSINE, vector_size=128\n", ")\n", "\n", "# Initialize/create the vector store index\n", @@ -148,7 +150,9 @@ "\n", "embeddings = FakeEmbeddings(size=128)\n", "redis_client = redis.from_url(\"redis://127.0.0.1:6379\")\n", - "rvs = RedisVectorStore.from_documents(docs, embedding=embeddings, client=redis_client, index_name=\"my_vector_index\")" + "rvs = RedisVectorStore.from_documents(\n", + " docs, embedding=embeddings, client=redis_client, index_name=\"my_vector_index\"\n", + ")" ] }, { @@ -169,8 +173,12 @@ "metadata": {}, "outputs": [], "source": [ - "rvs = RedisVectorStore(client=redis_client, index_name=\"my_vector_index\", embedding_service=embeddings)\n", - "ids = rvs.add_texts(texts=[d.page_content for d in docs], metadatas=[d.metadata for d in docs])" + "rvs = RedisVectorStore(\n", + " client=redis_client, index_name=\"my_vector_index\", embedding_service=embeddings\n", + ")\n", + "ids = rvs.add_texts(\n", + " texts=[d.page_content for d in docs], metadatas=[d.metadata for d in docs]\n", + ")" ] }, { @@ -194,7 +202,7 @@ "source": [ "import pprint\n", "\n", - "query=\"What did the president say about Ketanji Brown Jackson\"\n", + "query = \"What did the president say about Ketanji Brown Jackson\"\n", "knn_results = rvs.similarity_search(query=query)\n", "pprint.pprint(knn_results)" ] @@ -243,7 +251,7 @@ "metadata": {}, "outputs": [], "source": [ - "mmr_results = rvs.max_marginal_relevance_search(query=query,lambda_mult=0.90)\n", + "mmr_results = rvs.max_marginal_relevance_search(query=query, lambda_mult=0.90)\n", "pprint.pprint(mmr_results)" ] }, diff --git a/src/langchain_google_memorystore_redis/vector_store.py b/src/langchain_google_memorystore_redis/vector_store.py index c9db4ce..0f51893 100644 --- a/src/langchain_google_memorystore_redis/vector_store.py +++ b/src/langchain_google_memorystore_redis/vector_store.py @@ -44,6 +44,11 @@ handler.setFormatter(formatter) logger.addHandler(handler) +DEFAULT_CONTENT_FIELD = "page_content" +DEFAULT_VECTOR_FIELD = "vector" +DEFAULT_DATA_TYPE = "float32" +DEFAULT_DISTANCE_STRATEGY = DistanceStrategy.COSINE + class IndexConfig(ABC): """ @@ -152,7 +157,7 @@ def __init__( name: str, field_name=None, vector_size: int = 128, - distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, + distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, initial_cap: int = 10000, m: int = 16, ef_construction: int = 200, @@ -171,7 +176,7 @@ def __init__( accommodate. All vectors must match this specified size. distance_strategy (DistanceStrategy): The metric used for calculating distances or similarities between vectors, influencing how search results - are ranked. Defaults to `DistanceStrategy.COSINE`. + are ranked. initial_cap (int): Specifies the initial capacity of the index in terms of the number of vectors it can hold, impacting the initial memory allocation. Defaults to 10000. @@ -186,7 +191,7 @@ def __init__( """ if field_name is None: - field_name = RedisVectorStore.DEFAULT_VECTOR_FIELD + field_name = DEFAULT_VECTOR_FIELD super().__init__( name, field_name, "HNSW", distance_strategy, vector_size, "FLOAT32" ) @@ -206,7 +211,7 @@ def __init__( name: str, field_name=None, vector_size: int = 128, - distance_strategy: DistanceStrategy = DistanceStrategy.COSINE, + distance_strategy: DistanceStrategy = DEFAULT_DISTANCE_STRATEGY, ): """ Initializes the FLATConfig object. @@ -221,21 +226,16 @@ def __init__( indexed. All vectors added to this index must conform to this size. distance_strategy (DistanceStrategy, optional): Determines the metric used to calculate the distance or similarity between vectors during - search operations. Defaults to `DistanceStrategy.COSINE`, which - measures the cosine similarity between vectors. + search operations. """ if field_name is None: - field_name = RedisVectorStore.DEFAULT_VECTOR_FIELD + field_name = DEFAULT_VECTOR_FIELD super().__init__( name, field_name, "FLAT", distance_strategy, vector_size, "FLOAT32" ) class RedisVectorStore(VectorStore): - DEFAULT_CONTENT_FIELD = "page_content" - DEFAULT_VECTOR_FIELD = "vector" - DEFAULT_DATA_TYPE = "float32" - def __init__( self, client: redis.Redis, @@ -293,6 +293,7 @@ def __init__( self.key_prefix = self.get_key_prefix(index_name, key_prefix) self.content_field = content_field self.vector_field = vector_field + self.encoding = client.get_encoder().encoding @staticmethod def get_key_prefix(index_name: str, key_prefix: Optional[str] = None): @@ -420,7 +421,7 @@ def add_texts( mapping = { self.content_field: text, self.vector_field: np.array(embedding) - .astype(self.DEFAULT_DATA_TYPE) + .astype(DEFAULT_DATA_TYPE) .tobytes(), } @@ -454,6 +455,8 @@ def from_texts( texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, + client: redis.Redis = None, + index_name: str = None, **kwargs: Any, ) -> "RedisVectorStore": """ @@ -480,28 +483,22 @@ def from_texts( that the method cannot proceed without a connection to a Redis database. """ - if "client" not in kwargs: + if "client" == None: raise ValueError( "A 'client' must be provided to initialize RedisVectorStore" ) - if "index_name" not in kwargs: + if "index_name" == None: raise ValueError( "A 'index_name' must be provided to initialize RedisVectorStore" ) - kwargs_copy = kwargs.copy() - - # Extract 'client' and remove it from kwargs to prevent passing it twice - client = kwargs_copy.pop("client") - index_name = kwargs_copy.pop("index_name") - # Initialize RedisVectorStore instance instance = cls( client, index_name, embedding, - **kwargs_copy, + **kwargs, ) # Add texts and their corresponding metadata to the instance @@ -525,23 +522,47 @@ def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> Optional[boo def _similarity_search_by_vector_with_score_and_embeddings( self, query_embedding: List[float], k: int = 4, **kwargs: Any ) -> List[Tuple[Document, float, List[float]]]: + """ + Performs a similarity search by a vector with score and embeddings, offering + various customization options via keyword arguments. + + Args: + query_embedding (List[float]): A list of floats representing the embedding + vector of the query for similarity search. + k (int, optional): The number of nearest neighbors to retrieve. Defaults to 4. + **kwargs (Any): Additional keyword arguments allowing for customization of + the search operation. Key options include: + - 'distance_threshold' (float, optional): A threshold value for filtering + results based on their distance or score. If not specified directly, + it may use 'score_threshold' if provided. + - 'distance_strategy' (str, optional): Strategy to apply when comparing + distances or scores. Uses a default strategy if not specified. + + Returns: + List[Tuple[Document, float, List[float]]]: A list of tuples, each containing + a Document object, its distance (score) from the query embedding, and its own + embedding vector. The Document object includes content and metadata. + + Note: + - The function dynamically adjusts its behavior based on the presence and values + of keyword arguments. For instance, if a 'distance_threshold' is provided, + only results meeting this threshold are returned. + """ + distance_threshold = kwargs.get( "distance_threshold", kwargs.get("score_threshold") ) - query_k = k - if distance_threshold is not None: - distance_strategy = kwargs.get("distance_strategy", DistanceStrategy.COSINE) - query_k *= 4 # Quadruple k if a distance threshold is specified + distance_strategy = kwargs.get("distance_strategy", DEFAULT_DISTANCE_STRATEGY) query_args = [ "FT.SEARCH", self.index_name, - f"*=>[KNN {query_k} @{self.vector_field} $query_vector AS distance]", + f"*=>[KNN {k} @{self.vector_field} $query_vector AS distance]", "PARAMS", 2, "query_vector", - np.array([query_embedding]).astype(self.DEFAULT_DATA_TYPE).tobytes(), + np.array([query_embedding]).astype(DEFAULT_DATA_TYPE).tobytes(), "DIALECT", 2, ] @@ -562,23 +583,21 @@ def _similarity_search_by_vector_with_score_and_embeddings( distance = 0.0 embedding: List[float] = [] for j in range(0, len(initial_results[i]), 2): - key = initial_results[i][j].decode() + key = initial_results[i][j].decode(self.encoding) value = initial_results[i][j + 1] if key == self.content_field: - page_content = value.decode() + page_content = value.decode(self.encoding) elif key == self.vector_field: - embedding = np.frombuffer( - value, dtype=self.DEFAULT_DATA_TYPE - ).tolist() + embedding = np.frombuffer(value, dtype=DEFAULT_DATA_TYPE).tolist() elif key == "distance": - distance = float(value.decode()) + distance = float(value.decode(self.encoding)) else: if isinstance(value, bytes) and self._is_json_parsable( - value.decode() + value.decode(self.encoding) ): - metadata[key] = json.loads(value.decode()) + metadata[key] = json.loads(value.decode(self.encoding)) else: - metadata[key] = value.decode() + metadata[key] = value.decode(self.encoding) final_results.append( ( @@ -599,7 +618,15 @@ def _similarity_search_by_vector_with_score_and_embeddings( for doc, distance, embedding in final_results if cmp(distance, distance_threshold) ] - return final_results[:k] + + # Directly sort final_results based on distance, applying the determined sort order + final_results = sorted( + final_results, + key=lambda d: d[1], + reverse=distance_strategy == DistanceStrategy.MAX_INNER_PRODUCT, + ) + + return final_results def _similarity_search_by_vector_with_score( self, query_embedding: List[float], k: int = 4, **kwargs: Any From 7231b97a6fcfa6d6c42d3f869c615855f95b3fe2 Mon Sep 17 00:00:00 2001 From: Ping Xie Date: Mon, 12 Feb 2024 19:30:57 -0800 Subject: [PATCH 07/16] fixed lint errors --- src/langchain_google_memorystore_redis/vector_store.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/langchain_google_memorystore_redis/vector_store.py b/src/langchain_google_memorystore_redis/vector_store.py index 0f51893..4062142 100644 --- a/src/langchain_google_memorystore_redis/vector_store.py +++ b/src/langchain_google_memorystore_redis/vector_store.py @@ -455,8 +455,8 @@ def from_texts( texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, - client: redis.Redis = None, - index_name: str = None, + client = None, + index_name = None, **kwargs: Any, ) -> "RedisVectorStore": """ From 1ac23e246b34b210a584b4806c8a9ee47808acef Mon Sep 17 00:00:00 2001 From: Ping Xie Date: Mon, 12 Feb 2024 19:35:00 -0800 Subject: [PATCH 08/16] fixed more lint errors --- .../chat_message_history.py | 2 +- src/langchain_google_memorystore_redis/vector_store.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/langchain_google_memorystore_redis/chat_message_history.py b/src/langchain_google_memorystore_redis/chat_message_history.py index b2c80cf..3a37a28 100644 --- a/src/langchain_google_memorystore_redis/chat_message_history.py +++ b/src/langchain_google_memorystore_redis/chat_message_history.py @@ -53,7 +53,7 @@ def messages(self) -> List[BaseMessage]: # type: ignore messages = messages_from_dict( [json.loads(self._encoder.decode(e)) for e in all_elements] ) - return messages + return loaded_messages def add_message(self, message: BaseMessage) -> None: """Append one message to this session.""" diff --git a/src/langchain_google_memorystore_redis/vector_store.py b/src/langchain_google_memorystore_redis/vector_store.py index 4062142..de4b29a 100644 --- a/src/langchain_google_memorystore_redis/vector_store.py +++ b/src/langchain_google_memorystore_redis/vector_store.py @@ -455,8 +455,8 @@ def from_texts( texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, - client = None, - index_name = None, + client=None, + index_name=None, **kwargs: Any, ) -> "RedisVectorStore": """ From b349c8859544b70343c3945fd0a1b88e1d760626 Mon Sep 17 00:00:00 2001 From: Ping Xie Date: Tue, 13 Feb 2024 10:12:28 -0800 Subject: [PATCH 09/16] removed key_prefix argument from vectorstore --- .../vector_store.py | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/src/langchain_google_memorystore_redis/vector_store.py b/src/langchain_google_memorystore_redis/vector_store.py index de4b29a..df01002 100644 --- a/src/langchain_google_memorystore_redis/vector_store.py +++ b/src/langchain_google_memorystore_redis/vector_store.py @@ -241,7 +241,6 @@ def __init__( client: redis.Redis, index_name: str, embedding_service: Embeddings, - key_prefix: Optional[str] = None, content_field: str = DEFAULT_CONTENT_FIELD, vector_field: str = DEFAULT_VECTOR_FIELD, ): @@ -259,10 +258,6 @@ def __init__( capable of generating vector embeddings from document content. This service is utilized to convert text documents into vector representations for storage and search. - key_prefix (Optional[str], optional): An optional prefix for Redis HASH keys - that are to be included in the vector index. This allows for selective - indexing of documents based on their keys. If None, all HASH keys in the - Redis database are considered for indexing. Defaults to None. content_field (str, optional): The field within the Redis HASH where document content is stored. This field is read to obtain document text for embedding during indexing operations. Defaults to 'page_content', which @@ -290,7 +285,7 @@ def __init__( self._client = client self.index_name = index_name self.embedding_service = embedding_service - self.key_prefix = self.get_key_prefix(index_name, key_prefix) + self.key_prefix = self.get_key_prefix(index_name) self.content_field = content_field self.vector_field = vector_field self.encoding = client.get_encoder().encoding @@ -308,9 +303,7 @@ def _is_json_parsable(s: str) -> bool: return False @staticmethod - def init_index( - client: redis.Redis, index_config: IndexConfig, key_prefix: Optional[str] = None - ): + def init_index(client: redis.Redis, index_config: IndexConfig): """ Initializes a named VectorStore index in Redis with specified configurations. """ @@ -319,7 +312,7 @@ def init_index( # Preparing the command string to avoid long lines command = ( - f"FT.CREATE {index_config.name} ON HASH PREFIX 1 {RedisVectorStore.get_key_prefix(index_config.name, key_prefix)} " + f"FT.CREATE {index_config.name} ON HASH PREFIX 1 {RedisVectorStore.get_key_prefix(index_config.name)} " f"SCHEMA {index_config.field_name} VECTOR {index_config.type} " f"6 TYPE {index_config.data_type} DIM {index_config.vector_size} " f"DISTANCE_METRIC {index_config.distance_metric}" From ced4961e22d649dda375ab1e029642c2870345f4 Mon Sep 17 00:00:00 2001 From: Ping Xie Date: Tue, 13 Feb 2024 11:19:05 -0800 Subject: [PATCH 10/16] incorporated review feedback --- docs/vector_store.ipynb | 16 ++++++++-------- .../vector_store.py | 6 +++--- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/docs/vector_store.ipynb b/docs/vector_store.ipynb index 432434d..20b3173 100644 --- a/docs/vector_store.ipynb +++ b/docs/vector_store.ipynb @@ -7,7 +7,7 @@ "source": [ "Google Database\n", "\n", - "Use [Google Memorystore for Redis](https://cloud.google.com/memorystore) as a vector store for LangChain." + "Use [Google Memorystore for Redis](https://cloud.google.com/memorystore/docs/redis/memorystore-for-redis-overview) as a vector store for LangChain." ] }, { @@ -22,9 +22,9 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### Setting Up a Memorystore Redis Instance\n", + "### Setting Up a Memorystore for Redis Instance\n", "\n", - "Before proceeding, an active Memorystore Redis instance is needed to store vectors:\n", + "Before proceeding, an active Memorystore for Redis instance is needed to store vectors:\n", "\n", "* Create a Memorystore for Reids Instance (v7.2): If an instance doesn't exist, follow the instructions at https://cloud.google.com/memorystore/docs/redis/create-instance-console to create a new one. Ensure version 7.2 is selected.\n", "* Obtain Endpoint: Note the endpoint associated with the instance." @@ -35,7 +35,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### Installing the LangChain Memorystore Redis Module\n", + "### Installing the LangChain Memorystore for Redis Module\n", "\n", "Interaction with the Memorystore for Redis instance from LangChain requires installing the necessary module:" ] @@ -48,7 +48,7 @@ }, "outputs": [], "source": [ - "# Install Memorystore Redis for LangChain module\n", + "# Install Memorystore for Redis for LangChain module\n", "%pip install langchainlangchain_google_memorystore_redis" ] }, @@ -186,12 +186,12 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### Perfor a Similarity Search (KNN)\n", + "### Perform a Similarity Search (KNN)\n", "\n", "With the vector store populated, it's possible to search for text semantically similar to a query. Here's how to use KNN (K-Nearest Neighbors) with default settings:\n", "\n", "* Formulate the Query: A natural language question expresses the search intent (e.g., \"What did the president say about Ketanji Brown Jackson\").\n", - "* Retrieve Similar Results: The `similarity_search` method finds items in the vector store closest in meaning to the query." + "* Retrieve Similar Results: The `similarity_search` method finds items in the vector store closest to the query in meaning." ] }, { @@ -217,7 +217,7 @@ "Range queries provide more control by specifying a desired similarity threshold along with the query text:\n", "\n", "* Formulate the Query: A natural language question defines the search intent.\n", - "* Set Similarity Threshold: The distance_threshold parameter determines how close a match needs to be considered relevant.\n", + "* Set Similarity Threshold: The distance_threshold parameter determines how close a match must be considered relevant.\n", "* Retrieve Results: The `similarity_search_with_score` method finds items from the vector store that fall within the specified similarity threshold." ] }, diff --git a/src/langchain_google_memorystore_redis/vector_store.py b/src/langchain_google_memorystore_redis/vector_store.py index df01002..964b141 100644 --- a/src/langchain_google_memorystore_redis/vector_store.py +++ b/src/langchain_google_memorystore_redis/vector_store.py @@ -100,7 +100,7 @@ def __init__( type: str, distance_strategy: DistanceStrategy, vector_size: int, - data_type: str = "FLOAT32", + data_type: str = DEFAULT_DATA_TYPE ): """ Initializes the VectorIndexConfig object. @@ -120,7 +120,7 @@ def __init__( and indexed. All vectors must conform to this specified size. data_type (str, optional): The data type of the vector elements (e.g., "FLOAT32"). This specifies the precision and format of the vector data, affecting storage - requirements and possibly search performance. Defaults to "FLOAT32". + requirements and possibly search performance. """ if distance_strategy not in self.SUPPORTED_DISTANCE_STRATEGIES: supported_strategies = ", ".join( @@ -292,7 +292,7 @@ def __init__( @staticmethod def get_key_prefix(index_name: str, key_prefix: Optional[str] = None): - return key_prefix + ":" if key_prefix is not None else index_name + ":" + return key_prefix if key_prefix is not None else index_name @staticmethod def _is_json_parsable(s: str) -> bool: From f753433147a975fdb4e7c4eabb79ecb31da399ff Mon Sep 17 00:00:00 2001 From: Ping Xie Date: Tue, 13 Feb 2024 11:22:48 -0800 Subject: [PATCH 11/16] fixed formatting errors --- src/langchain_google_memorystore_redis/vector_store.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/langchain_google_memorystore_redis/vector_store.py b/src/langchain_google_memorystore_redis/vector_store.py index 964b141..f244051 100644 --- a/src/langchain_google_memorystore_redis/vector_store.py +++ b/src/langchain_google_memorystore_redis/vector_store.py @@ -100,7 +100,7 @@ def __init__( type: str, distance_strategy: DistanceStrategy, vector_size: int, - data_type: str = DEFAULT_DATA_TYPE + data_type: str = DEFAULT_DATA_TYPE, ): """ Initializes the VectorIndexConfig object. @@ -120,7 +120,7 @@ def __init__( and indexed. All vectors must conform to this specified size. data_type (str, optional): The data type of the vector elements (e.g., "FLOAT32"). This specifies the precision and format of the vector data, affecting storage - requirements and possibly search performance. + requirements and possibly search performance. """ if distance_strategy not in self.SUPPORTED_DISTANCE_STRATEGIES: supported_strategies = ", ".join( From 83d32078620b2625405d9676ee0c034578fffa85 Mon Sep 17 00:00:00 2001 From: Ping Xie Date: Tue, 13 Feb 2024 11:39:18 -0800 Subject: [PATCH 12/16] fixed a bad merge --- src/langchain_google_memorystore_redis/chat_message_history.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/langchain_google_memorystore_redis/chat_message_history.py b/src/langchain_google_memorystore_redis/chat_message_history.py index 3a37a28..e04ae79 100644 --- a/src/langchain_google_memorystore_redis/chat_message_history.py +++ b/src/langchain_google_memorystore_redis/chat_message_history.py @@ -50,7 +50,7 @@ def messages(self) -> List[BaseMessage]: # type: ignore all_elements = self._redis.lrange(self._key, 0, -1) assert isinstance(all_elements, list) - messages = messages_from_dict( + loaded_messages = messages_from_dict( [json.loads(self._encoder.decode(e)) for e in all_elements] ) return loaded_messages From 7ccbca0b1d0230d8b41b476bbabf50dcaa35b1f5 Mon Sep 17 00:00:00 2001 From: Ping Xie Date: Tue, 13 Feb 2024 12:10:47 -0800 Subject: [PATCH 13/16] suppress mypy errors for setuptools --- setup.cfg | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 setup.cfg diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..d5ce2fa --- /dev/null +++ b/setup.cfg @@ -0,0 +1,3 @@ +[mypy-setuptools.*] +ignore_missing_imports = true + From 145d1535bf5619d8932de76c99760ec9b30e7835 Mon Sep 17 00:00:00 2001 From: Ping Xie Date: Tue, 13 Feb 2024 12:13:39 -0800 Subject: [PATCH 14/16] trying mypy.ini --- setup.cfg | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 setup.cfg diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index d5ce2fa..0000000 --- a/setup.cfg +++ /dev/null @@ -1,3 +0,0 @@ -[mypy-setuptools.*] -ignore_missing_imports = true - From 73d5ee3c69f373885623a8d3974c884b8a929476 Mon Sep 17 00:00:00 2001 From: Ping Xie Date: Tue, 13 Feb 2024 12:22:30 -0800 Subject: [PATCH 15/16] remove setup.py and requirements --- requirements.txt | 3 --- setup.py | 41 ----------------------------------------- 2 files changed, 44 deletions(-) delete mode 100644 requirements.txt delete mode 100644 setup.py diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index e0c52a9..0000000 --- a/requirements.txt +++ /dev/null @@ -1,3 +0,0 @@ -numpy -redis -langchain \ No newline at end of file diff --git a/setup.py b/setup.py deleted file mode 100644 index 1f9b651..0000000 --- a/setup.py +++ /dev/null @@ -1,41 +0,0 @@ -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from setuptools import find_packages, setup - -# Metadata fields -package_name = "langchain_google_memorystore_redis" # Corrected package name -author = "Google Cloud Memorystore" -description = "Memorystore for Redis integration for LangChain" -long_description = open("README.md").read() # Assuming you have a README.md -url = "https://github.com/googleapis/langchain-google-memorystore-redis-python" - -# Create your requirements.txt (see previous instructions) -install_requires = [line.strip() for line in open("requirements.txt")] - -setup( - name=package_name, - version="0.1.0", # Start with an initial version - description=description, - long_description=long_description, - long_description_content_type="text/markdown", # If you have a Markdown README - author=author, - url=url, - # Specify the package directory and find packages within src - package_dir={"": "src"}, # Specifies that the package(s) are under src - packages=find_packages(where="src"), # Tells setuptools to look for packages in src - install_requires=install_requires, - python_requires=">=3.7", # Adjust minimum Python version as needed - # Consider including additional package data, classifiers, etc. -) From 794dc0a3bb3b547601f33d88e9ec1b3de75506c4 Mon Sep 17 00:00:00 2001 From: Ping Xie Date: Tue, 13 Feb 2024 12:26:46 -0800 Subject: [PATCH 16/16] add numpy dependency --- pyproject.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/pyproject.toml b/pyproject.toml index 2017123..d28e669 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -8,6 +8,7 @@ requires-python = ">=3.8" dependencies = [ "langchain==0.1.1", "redis>=5.0.0", + "numpy>=1.21.0", ] [project.urls]