From b509747c7f13c5cad2226e62a3c9d948664fa193 Mon Sep 17 00:00:00 2001 From: Saad Makrod Date: Thu, 7 Nov 2024 18:29:35 -0500 Subject: [PATCH] Community: Google Books API Tool (#27307) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Description As proposed in our earlier discussion #26977 we have introduced a Google Books API Tool that leverages the Google Books API found at [https://developers.google.com/books/docs/v1/using](https://developers.google.com/books/docs/v1/using) to generate book recommendations. ### Sample Usage ```python from langchain_community.tools import GoogleBooksQueryRun from langchain_community.utilities import GoogleBooksAPIWrapper api_wrapper = GoogleBooksAPIWrapper() tool = GoogleBooksQueryRun(api_wrapper=api_wrapper) tool.run('ai') ``` ### Sample Output ```txt Here are 5 suggestions based off your search for books related to ai: 1. "AI's Take on the Stigma Against AI-Generated Content" by Sandy Y. Greenleaf: In a world where artificial intelligence (AI) is rapidly advancing and transforming various industries, a new form of content creation has emerged: AI-generated content. However, despite its potential to revolutionize the way we produce and consume information, AI-generated content often faces a significant stigma. "AI's Take on the Stigma Against AI-Generated Content" is a groundbreaking book that delves into the heart of this issue, exploring the reasons behind the stigma and offering a fresh, unbiased perspective on the topic. Written from the unique viewpoint of an AI, this book provides readers with a comprehensive understanding of the challenges and opportunities surrounding AI-generated content. Through engaging narratives, thought-provoking insights, and real-world examples, this book challenges readers to reconsider their preconceptions about AI-generated content. It explores the potential benefits of embracing this technology, such as increased efficiency, creativity, and accessibility, while also addressing the concerns and drawbacks that contribute to the stigma. As you journey through the pages of this book, you'll gain a deeper understanding of the complex relationship between humans and AI in the realm of content creation. You'll discover how AI can be used as a tool to enhance human creativity, rather than replace it, and how collaboration between humans and machines can lead to unprecedented levels of innovation. Whether you're a content creator, marketer, business owner, or simply someone curious about the future of AI and its impact on our society, "AI's Take on the Stigma Against AI-Generated Content" is an essential read. With its engaging writing style, well-researched insights, and practical strategies for navigating this new landscape, this book will leave you equipped with the knowledge and tools needed to embrace the AI revolution and harness its potential for success. Prepare to have your assumptions challenged, your mind expanded, and your perspective on AI-generated content forever changed. Get ready to embark on a captivating journey that will redefine the way you think about the future of content creation. Read more at https://play.google.com/store/books/details?id=4iH-EAAAQBAJ&source=gbs_api 2. "AI Strategies For Web Development" by Anderson Soares Furtado Oliveira: From fundamental to advanced strategies, unlock useful insights for creating innovative, user-centric websites while navigating the evolving landscape of AI ethics and security Key Features Explore AI's role in web development, from shaping projects to architecting solutions Master advanced AI strategies to build cutting-edge applications Anticipate future trends by exploring next-gen development environments, emerging interfaces, and security considerations in AI web development Purchase of the print or Kindle book includes a free PDF eBook Book Description If you're a web developer looking to leverage the power of AI in your projects, then this book is for you. Written by an AI and ML expert with more than 15 years of experience, AI Strategies for Web Development takes you on a transformative journey through the dynamic intersection of AI and web development, offering a hands-on learning experience.The first part of the book focuses on uncovering the profound impact of AI on web projects, exploring fundamental concepts, and navigating popular frameworks and tools. As you progress, you'll learn how to build smart AI applications with design intelligence, personalized user journeys, and coding assistants. Later, you'll explore how to future-proof your web development projects using advanced AI strategies and understand AI's impact on jobs. Toward the end, you'll immerse yourself in AI-augmented development, crafting intelligent web applications and navigating the ethical landscape.Packed with insights into next-gen development environments, AI-augmented practices, emerging realities, interfaces, and security governance, this web development book acts as your roadmap to staying ahead in the AI and web development domain. What you will learn Build AI-powered web projects with optimized models Personalize UX dynamically with AI, NLP, chatbots, and recommendations Explore AI coding assistants and other tools for advanced web development Craft data-driven, personalized experiences using pattern recognition Architect effective AI solutions while exploring the future of web development Build secure and ethical AI applications following TRiSM best practices Explore cutting-edge AI and web development trends Who this book is for This book is for web developers with experience in programming languages and an interest in keeping up with the latest trends in AI-powered web development. Full-stack, front-end, and back-end developers, UI/UX designers, software engineers, and web development enthusiasts will also find valuable information and practical guidelines for developing smarter websites with AI. To get the most out of this book, it is recommended that you have basic knowledge of programming languages such as HTML, CSS, and JavaScript, as well as a familiarity with machine learning concepts. Read more at https://play.google.com/store/books/details?id=FzYZEQAAQBAJ&source=gbs_api 3. "Artificial Intelligence for Students" by Vibha Pandey: A multifaceted approach to develop an understanding of AI and its potential applications KEY FEATURES ● AI-informed focuses on AI foundation, applications, and methodologies. ● AI-inquired focuses on computational thinking and bias awareness. ● AI-innovate focuses on creative and critical thinking and the Capstone project. DESCRIPTION AI is a discipline in Computer Science that focuses on developing intelligent machines, machines that can learn and then teach themselves. If you are interested in AI, this book can definitely help you prepare for future careers in AI and related fields. The book is aligned with the CBSE course, which focuses on developing employability and vocational competencies of students in skill subjects. The book is an introduction to the basics of AI. It is divided into three parts – AI-informed, AI-inquired and AI-innovate. It will help you understand AI's implications on society and the world. You will also develop a deeper understanding of how it works and how it can be used to solve complex real-world problems. Additionally, the book will also focus on important skills such as problem scoping, goal setting, data analysis, and visualization, which are essential for success in AI projects. Lastly, you will learn how decision trees, neural networks, and other AI concepts are commonly used in real-world applications. By the end of the book, you will develop the skills and competencies required to pursue a career in AI. WHAT YOU WILL LEARN ● Get familiar with the basics of AI and Machine Learning. ● Understand how and where AI can be applied. ● Explore different applications of mathematical methods in AI. ● Get tips for improving your skills in Data Storytelling. ● Understand what is AI bias and how it can affect human rights. WHO THIS BOOK IS FOR This book is for CBSE class XI and XII students who want to learn and explore more about AI. Basic knowledge of Statistical concepts, Algebra, and Plotting of equations is a must. TABLE OF CONTENTS 1. Introduction: AI for Everyone 2. AI Applications and Methodologies 3. Mathematics in Artificial Intelligence 4. AI Values (Ethical Decision-Making) 5. Introduction to Storytelling 6. Critical and Creative Thinking 7. Data Analysis 8. Regression 9. Classification and Clustering 10. AI Values (Bias Awareness) 11. Capstone Project 12. Model Lifecycle (Knowledge) 13. Storytelling Through Data 14. AI Applications in Use in Real-World Read more at https://play.google.com/store/books/details?id=ptq1EAAAQBAJ&source=gbs_api 4. "The AI Book" by Ivana Bartoletti, Anne Leslie and Shân M. Millie: Written by prominent thought leaders in the global fintech space, The AI Book aggregates diverse expertise into a single, informative volume and explains what artifical intelligence really means and how it can be used across financial services today. Key industry developments are explained in detail, and critical insights from cutting-edge practitioners offer first-hand information and lessons learned. Coverage includes: · Understanding the AI Portfolio: from machine learning to chatbots, to natural language processing (NLP); a deep dive into the Machine Intelligence Landscape; essentials on core technologies, rethinking enterprise, rethinking industries, rethinking humans; quantum computing and next-generation AI · AI experimentation and embedded usage, and the change in business model, value proposition, organisation, customer and co-worker experiences in today’s Financial Services Industry · The future state of financial services and capital markets – what’s next for the real-world implementation of AITech? · The innovating customer – users are not waiting for the financial services industry to work out how AI can re-shape their sector, profitability and competitiveness · Boardroom issues created and magnified by AI trends, including conduct, regulation & oversight in an algo-driven world, cybersecurity, diversity & inclusion, data privacy, the ‘unbundled corporation’ & the future of work, social responsibility, sustainability, and the new leadership imperatives · Ethical considerations of deploying Al solutions and why explainable Al is so important Read more at http://books.google.ca/books?id=oE3YDwAAQBAJ&dq=ai&hl=&source=gbs_api 5. "Artificial Intelligence in Society" by OECD: The artificial intelligence (AI) landscape has evolved significantly from 1950 when Alan Turing first posed the question of whether machines can think. Today, AI is transforming societies and economies. It promises to generate productivity gains, improve well-being and help address global challenges, such as climate change, resource scarcity and health crises. Read more at https://play.google.com/store/books/details?id=eRmdDwAAQBAJ&source=gbs_api ``` ## Issue This closes #27276 ## Dependencies No additional dependencies were added --------- Co-authored-by: Erick Friis --- .../integrations/tools/google_books.ipynb | 270 ++++++++++++++++++ .../agent_toolkits/load_tools.py | 8 + .../langchain_community/tools/__init__.py | 5 + .../langchain_community/tools/google_books.py | 38 +++ .../langchain_community/utilities/__init__.py | 5 + .../utilities/google_books.py | 92 ++++++ .../tests/unit_tests/tools/test_imports.py | 1 + .../unit_tests/utilities/test_imports.py | 1 + 8 files changed, 420 insertions(+) create mode 100644 docs/docs/integrations/tools/google_books.ipynb create mode 100644 libs/community/langchain_community/tools/google_books.py create mode 100644 libs/community/langchain_community/utilities/google_books.py diff --git a/docs/docs/integrations/tools/google_books.ipynb b/docs/docs/integrations/tools/google_books.ipynb new file mode 100644 index 0000000000000..57446c435f638 --- /dev/null +++ b/docs/docs/integrations/tools/google_books.ipynb @@ -0,0 +1,270 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Google Books" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Overview" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Integration details\n", + "\n", + "The Google Books tool that supports the ReAct pattern and allows you to search the Google Books API. Google Books is the largest API in the world that keeps track of books in a curated manner. It has over 40 million entries, which can give users a significant amount of data." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Tool features\n", + "\n", + "Currently the tool has the following capabilities:\n", + "- Gathers the relevant information from the Google Books API using a key word search\n", + "- Formats the information into a readable output, and return the result to the agent" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Setup\n", + "\n", + "Make sure `langchain-community` is installed." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "vscode": { + "languageId": "shellscript" + } + }, + "outputs": [], + "source": [ + "%pip install --upgrade --quiet langchain-community" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Credentials\n", + "\n", + "You will need an API key from Google Books. You can do this by visiting and following the steps at [https://developers.google.com/books/docs/v1/using#APIKey](https://developers.google.com/books/docs/v1/using#APIKey).\n", + "\n", + "Then you will need to set the environment variable `GOOGLE_BOOKS_API_KEY` to your Google Books API key." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Instantiation\n", + "\n", + "To instantiate the tool import the Google Books tool and set your credentials." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "\n", + "from langchain_community.tools.google_books import GoogleBooksQueryRun\n", + "from langchain_community.utilities.google_books import GoogleBooksAPIWrapper\n", + "\n", + "os.environ[\"GOOGLE_BOOKS_API_KEY\"] = \"\"\n", + "tool = GoogleBooksQueryRun(api_wrapper=GoogleBooksAPIWrapper())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Invocation\n", + "\n", + "You can invoke the tool by calling the `run` method." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Here are 5 suggestions for books related to ai:\n", + "\n", + "1. \"AI's Take on the Stigma Against AI-Generated Content\" by Sandy Y. Greenleaf: In a world where artificial intelligence (AI) is rapidly advancing and transforming various industries, a new form of content creation has emerged: AI-generated content. However, despite its potential to revolutionize the way we produce and consume information, AI-generated content often faces a significant stigma. \"AI's Take on the Stigma Against AI-Generated Content\" is a groundbreaking book that delves into the heart of this issue, exploring the reasons behind the stigma and offering a fresh, unbiased perspective on the topic. Written from the unique viewpoint of an AI, this book provides readers with a comprehensive understanding of the challenges and opportunities surrounding AI-generated content. Through engaging narratives, thought-provoking insights, and real-world examples, this book challenges readers to reconsider their preconceptions about AI-generated content. It explores the potential benefits of embracing this technology, such as increased efficiency, creativity, and accessibility, while also addressing the concerns and drawbacks that contribute to the stigma. As you journey through the pages of this book, you'll gain a deeper understanding of the complex relationship between humans and AI in the realm of content creation. You'll discover how AI can be used as a tool to enhance human creativity, rather than replace it, and how collaboration between humans and machines can lead to unprecedented levels of innovation. Whether you're a content creator, marketer, business owner, or simply someone curious about the future of AI and its impact on our society, \"AI's Take on the Stigma Against AI-Generated Content\" is an essential read. With its engaging writing style, well-researched insights, and practical strategies for navigating this new landscape, this book will leave you equipped with the knowledge and tools needed to embrace the AI revolution and harness its potential for success. Prepare to have your assumptions challenged, your mind expanded, and your perspective on AI-generated content forever changed. Get ready to embark on a captivating journey that will redefine the way you think about the future of content creation.\n", + "You can read more at https://play.google.com/store/books/details?id=4iH-EAAAQBAJ&source=gbs_api\n", + "\n", + "2. \"AI Strategies For Web Development\" by Anderson Soares Furtado Oliveira: From fundamental to advanced strategies, unlock useful insights for creating innovative, user-centric websites while navigating the evolving landscape of AI ethics and security Key Features Explore AI's role in web development, from shaping projects to architecting solutions Master advanced AI strategies to build cutting-edge applications Anticipate future trends by exploring next-gen development environments, emerging interfaces, and security considerations in AI web development Purchase of the print or Kindle book includes a free PDF eBook Book Description If you're a web developer looking to leverage the power of AI in your projects, then this book is for you. Written by an AI and ML expert with more than 15 years of experience, AI Strategies for Web Development takes you on a transformative journey through the dynamic intersection of AI and web development, offering a hands-on learning experience.The first part of the book focuses on uncovering the profound impact of AI on web projects, exploring fundamental concepts, and navigating popular frameworks and tools. As you progress, you'll learn how to build smart AI applications with design intelligence, personalized user journeys, and coding assistants. Later, you'll explore how to future-proof your web development projects using advanced AI strategies and understand AI's impact on jobs. Toward the end, you'll immerse yourself in AI-augmented development, crafting intelligent web applications and navigating the ethical landscape.Packed with insights into next-gen development environments, AI-augmented practices, emerging realities, interfaces, and security governance, this web development book acts as your roadmap to staying ahead in the AI and web development domain. What you will learn Build AI-powered web projects with optimized models Personalize UX dynamically with AI, NLP, chatbots, and recommendations Explore AI coding assistants and other tools for advanced web development Craft data-driven, personalized experiences using pattern recognition Architect effective AI solutions while exploring the future of web development Build secure and ethical AI applications following TRiSM best practices Explore cutting-edge AI and web development trends Who this book is for This book is for web developers with experience in programming languages and an interest in keeping up with the latest trends in AI-powered web development. Full-stack, front-end, and back-end developers, UI/UX designers, software engineers, and web development enthusiasts will also find valuable information and practical guidelines for developing smarter websites with AI. To get the most out of this book, it is recommended that you have basic knowledge of programming languages such as HTML, CSS, and JavaScript, as well as a familiarity with machine learning concepts.\n", + "You can read more at https://play.google.com/store/books/details?id=FzYZEQAAQBAJ&source=gbs_api\n", + "\n", + "3. \"Artificial Intelligence for Students\" by Vibha Pandey: A multifaceted approach to develop an understanding of AI and its potential applications KEY FEATURES ● AI-informed focuses on AI foundation, applications, and methodologies. ● AI-inquired focuses on computational thinking and bias awareness. ● AI-innovate focuses on creative and critical thinking and the Capstone project. DESCRIPTION AI is a discipline in Computer Science that focuses on developing intelligent machines, machines that can learn and then teach themselves. If you are interested in AI, this book can definitely help you prepare for future careers in AI and related fields. The book is aligned with the CBSE course, which focuses on developing employability and vocational competencies of students in skill subjects. The book is an introduction to the basics of AI. It is divided into three parts – AI-informed, AI-inquired and AI-innovate. It will help you understand AI's implications on society and the world. You will also develop a deeper understanding of how it works and how it can be used to solve complex real-world problems. Additionally, the book will also focus on important skills such as problem scoping, goal setting, data analysis, and visualization, which are essential for success in AI projects. Lastly, you will learn how decision trees, neural networks, and other AI concepts are commonly used in real-world applications. By the end of the book, you will develop the skills and competencies required to pursue a career in AI. WHAT YOU WILL LEARN ● Get familiar with the basics of AI and Machine Learning. ● Understand how and where AI can be applied. ● Explore different applications of mathematical methods in AI. ● Get tips for improving your skills in Data Storytelling. ● Understand what is AI bias and how it can affect human rights. WHO THIS BOOK IS FOR This book is for CBSE class XI and XII students who want to learn and explore more about AI. Basic knowledge of Statistical concepts, Algebra, and Plotting of equations is a must. TABLE OF CONTENTS 1. Introduction: AI for Everyone 2. AI Applications and Methodologies 3. Mathematics in Artificial Intelligence 4. AI Values (Ethical Decision-Making) 5. Introduction to Storytelling 6. Critical and Creative Thinking 7. Data Analysis 8. Regression 9. Classification and Clustering 10. AI Values (Bias Awareness) 11. Capstone Project 12. Model Lifecycle (Knowledge) 13. Storytelling Through Data 14. AI Applications in Use in Real-World\n", + "You can read more at https://play.google.com/store/books/details?id=ptq1EAAAQBAJ&source=gbs_api\n", + "\n", + "4. \"The AI Book\" by Ivana Bartoletti, Anne Leslie and Shân M. Millie: Written by prominent thought leaders in the global fintech space, The AI Book aggregates diverse expertise into a single, informative volume and explains what artifical intelligence really means and how it can be used across financial services today. Key industry developments are explained in detail, and critical insights from cutting-edge practitioners offer first-hand information and lessons learned. Coverage includes: · Understanding the AI Portfolio: from machine learning to chatbots, to natural language processing (NLP); a deep dive into the Machine Intelligence Landscape; essentials on core technologies, rethinking enterprise, rethinking industries, rethinking humans; quantum computing and next-generation AI · AI experimentation and embedded usage, and the change in business model, value proposition, organisation, customer and co-worker experiences in today’s Financial Services Industry · The future state of financial services and capital markets – what’s next for the real-world implementation of AITech? · The innovating customer – users are not waiting for the financial services industry to work out how AI can re-shape their sector, profitability and competitiveness · Boardroom issues created and magnified by AI trends, including conduct, regulation & oversight in an algo-driven world, cybersecurity, diversity & inclusion, data privacy, the ‘unbundled corporation’ & the future of work, social responsibility, sustainability, and the new leadership imperatives · Ethical considerations of deploying Al solutions and why explainable Al is so important\n", + "You can read more at http://books.google.ca/books?id=oE3YDwAAQBAJ&dq=ai&hl=&source=gbs_api\n", + "\n", + "5. \"Artificial Intelligence in Society\" by OECD: The artificial intelligence (AI) landscape has evolved significantly from 1950 when Alan Turing first posed the question of whether machines can think. Today, AI is transforming societies and economies. It promises to generate productivity gains, improve well-being and help address global challenges, such as climate change, resource scarcity and health crises.\n", + "You can read more at https://play.google.com/store/books/details?id=eRmdDwAAQBAJ&source=gbs_api'" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "tool.run(\"ai\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### [Invoke directly with args](/docs/concepts/#invoke-with-just-the-arguments)\n", + "\n", + "See below for an direct invocation example." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "\n", + "from langchain_community.tools.google_books import GoogleBooksQueryRun\n", + "from langchain_community.utilities.google_books import GoogleBooksAPIWrapper\n", + "\n", + "os.environ[\"GOOGLE_BOOKS_API_KEY\"] = \"\"\n", + "tool = GoogleBooksQueryRun(api_wrapper=GoogleBooksAPIWrapper())\n", + "\n", + "tool.run(\"ai\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### [Invoke with ToolCall](/docs/concepts/#invoke-with-toolcall)\n", + "\n", + "See below for a tool call example." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import getpass\n", + "import os\n", + "\n", + "from langchain_community.tools.google_books import GoogleBooksQueryRun\n", + "from langchain_community.utilities.google_books import GoogleBooksAPIWrapper\n", + "from langchain_core.output_parsers import StrOutputParser\n", + "from langchain_core.prompts import PromptTemplate\n", + "from langchain_openai import ChatOpenAI\n", + "\n", + "os.environ[\"OPENAI_API_KEY\"] = getpass.getpass()\n", + "os.environ[\"GOOGLE_BOOKS_API_KEY\"] = \"\"\n", + "\n", + "tool = GoogleBooksQueryRun(api_wrapper=GoogleBooksAPIWrapper())\n", + "llm = ChatOpenAI(model=\"gpt-4o-mini\")\n", + "prompt = PromptTemplate.from_template(\n", + " \"Return the keyword, and only the keyword, that the user is looking for from this text: {text}\"\n", + ")\n", + "\n", + "\n", + "def suggest_books(query):\n", + " chain = prompt | llm | StrOutputParser()\n", + " keyword = chain.invoke({\"text\": query})\n", + " return tool.run(keyword)\n", + "\n", + "\n", + "suggestions = suggest_books(\"I need some information on AI\")\n", + "print(suggestions)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Chaining\n", + "\n", + "See the below example for chaining." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import getpass\n", + "import os\n", + "\n", + "from langchain import hub\n", + "from langchain.agents import AgentExecutor, create_tool_calling_agent\n", + "from langchain_community.tools.google_books import GoogleBooksQueryRun\n", + "from langchain_community.utilities.google_books import GoogleBooksAPIWrapper\n", + "from langchain_openai import ChatOpenAI\n", + "\n", + "os.environ[\"OPENAI_API_KEY\"] = getpass.getpass()\n", + "os.environ[\"GOOGLE_BOOKS_API_KEY\"] = \"\"\n", + "\n", + "tool = GoogleBooksQueryRun(api_wrapper=GoogleBooksAPIWrapper())\n", + "llm = ChatOpenAI(model=\"gpt-4o-mini\")\n", + "\n", + "instructions = \"\"\"You are a book suggesting assistant.\"\"\"\n", + "base_prompt = hub.pull(\"langchain-ai/openai-functions-template\")\n", + "prompt = base_prompt.partial(instructions=instructions)\n", + "\n", + "tools = [tool]\n", + "agent = create_tool_calling_agent(llm, tools, prompt)\n", + "agent_executor = AgentExecutor(\n", + " agent=agent,\n", + " tools=tools,\n", + " verbose=True,\n", + ")\n", + "\n", + "agent_executor.invoke({\"input\": \"Can you recommend me some books related to ai?\"})" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## API reference\n", + "\n", + "The Google Books API can be found here: [https://developers.google.com/books](https://developers.google.com/books)" + ] + } + ], + "metadata": { + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/libs/community/langchain_community/agent_toolkits/load_tools.py b/libs/community/langchain_community/agent_toolkits/load_tools.py index fa2aeddd52aa3..d7f5fc3cfd126 100644 --- a/libs/community/langchain_community/agent_toolkits/load_tools.py +++ b/libs/community/langchain_community/agent_toolkits/load_tools.py @@ -77,6 +77,7 @@ from langchain_community.utilities.dataforseo_api_search import DataForSeoAPIWrapper from langchain_community.utilities.duckduckgo_search import DuckDuckGoSearchAPIWrapper from langchain_community.utilities.golden_query import GoldenQueryAPIWrapper +from langchain_community.utilities.google_books import GoogleBooksAPIWrapper from langchain_community.utilities.google_finance import GoogleFinanceAPIWrapper from langchain_community.utilities.google_jobs import GoogleJobsAPIWrapper from langchain_community.utilities.google_lens import GoogleLensAPIWrapper @@ -333,6 +334,12 @@ def _get_pubmed(**kwargs: Any) -> BaseTool: return PubmedQueryRun(api_wrapper=PubMedAPIWrapper(**kwargs)) +def _get_google_books(**kwargs: Any) -> BaseTool: + from langchain_community.tools.google_books import GoogleBooksQueryRun + + return GoogleBooksQueryRun(api_wrapper=GoogleBooksAPIWrapper(**kwargs)) + + def _get_google_jobs(**kwargs: Any) -> BaseTool: return GoogleJobsQueryRun(api_wrapper=GoogleJobsAPIWrapper(**kwargs)) @@ -490,6 +497,7 @@ def _get_reddit_search(**kwargs: Any) -> BaseTool: "bing-search": (_get_bing_search, ["bing_subscription_key", "bing_search_url"]), "metaphor-search": (_get_metaphor_search, ["metaphor_api_key"]), "ddg-search": (_get_ddg_search, []), + "google-books": (_get_google_books, ["google_books_api_key"]), "google-lens": (_get_google_lens, ["serp_api_key"]), "google-serper": (_get_google_serper, ["serper_api_key", "aiosession"]), "google-scholar": ( diff --git a/libs/community/langchain_community/tools/__init__.py b/libs/community/langchain_community/tools/__init__.py index 1e7899900d53f..5b4677f53dc2e 100644 --- a/libs/community/langchain_community/tools/__init__.py +++ b/libs/community/langchain_community/tools/__init__.py @@ -140,6 +140,9 @@ GmailSearch, GmailSendMessage, ) + from langchain_community.tools.google_books import ( + GoogleBooksQueryRun, + ) from langchain_community.tools.google_cloud.texttospeech import ( GoogleCloudTextToSpeechTool, ) @@ -407,6 +410,7 @@ "GmailGetThread", "GmailSearch", "GmailSendMessage", + "GoogleBooksQueryRun", "GoogleCloudTextToSpeechTool", "GooglePlacesTool", "GoogleSearchResults", @@ -559,6 +563,7 @@ "GmailGetThread": "langchain_community.tools.gmail", "GmailSearch": "langchain_community.tools.gmail", "GmailSendMessage": "langchain_community.tools.gmail", + "GoogleBooksQueryRun": "langchain_community.tools.google_books", "GoogleCloudTextToSpeechTool": "langchain_community.tools.google_cloud.texttospeech", # noqa: E501 "GooglePlacesTool": "langchain_community.tools.google_places.tool", "GoogleSearchResults": "langchain_community.tools.google_search.tool", diff --git a/libs/community/langchain_community/tools/google_books.py b/libs/community/langchain_community/tools/google_books.py new file mode 100644 index 0000000000000..390fce3fdf894 --- /dev/null +++ b/libs/community/langchain_community/tools/google_books.py @@ -0,0 +1,38 @@ +"""Tool for the Google Books API.""" + +from typing import Optional, Type + +from langchain_core.callbacks import CallbackManagerForToolRun +from langchain_core.tools import BaseTool +from pydantic import BaseModel, Field + +from langchain_community.utilities.google_books import GoogleBooksAPIWrapper + + +class GoogleBooksQueryInput(BaseModel): + """Input for the GoogleBooksQuery tool.""" + + query: str = Field(description="query to look up on google books") + + +class GoogleBooksQueryRun(BaseTool): # type: ignore[override] + """Tool that searches the Google Books API.""" + + name: str = "GoogleBooks" + description: str = ( + "A wrapper around Google Books. " + "Useful for when you need to answer general inquiries about " + "books of certain topics and generate recommendation based " + "off of key words" + "Input should be a query string" + ) + api_wrapper: GoogleBooksAPIWrapper + args_schema: Type[BaseModel] = GoogleBooksQueryInput + + def _run( + self, + query: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + """Use the Google Books tool.""" + return self.api_wrapper.run(query) diff --git a/libs/community/langchain_community/utilities/__init__.py b/libs/community/langchain_community/utilities/__init__.py index dd9565ec05f21..0174d37c07045 100644 --- a/libs/community/langchain_community/utilities/__init__.py +++ b/libs/community/langchain_community/utilities/__init__.py @@ -45,6 +45,9 @@ from langchain_community.utilities.golden_query import ( GoldenQueryAPIWrapper, ) + from langchain_community.utilities.google_books import ( + GoogleBooksAPIWrapper, + ) from langchain_community.utilities.google_finance import ( GoogleFinanceAPIWrapper, ) @@ -185,6 +188,7 @@ "DriaAPIWrapper", "DuckDuckGoSearchAPIWrapper", "GoldenQueryAPIWrapper", + "GoogleBooksAPIWrapper", "GoogleFinanceAPIWrapper", "GoogleJobsAPIWrapper", "GoogleLensAPIWrapper", @@ -248,6 +252,7 @@ "DriaAPIWrapper": "langchain_community.utilities.dria_index", "DuckDuckGoSearchAPIWrapper": "langchain_community.utilities.duckduckgo_search", "GoldenQueryAPIWrapper": "langchain_community.utilities.golden_query", + "GoogleBooksAPIWrapper": "langchain_community.utilities.google_books", "GoogleFinanceAPIWrapper": "langchain_community.utilities.google_finance", "GoogleJobsAPIWrapper": "langchain_community.utilities.google_jobs", "GoogleLensAPIWrapper": "langchain_community.utilities.google_lens", diff --git a/libs/community/langchain_community/utilities/google_books.py b/libs/community/langchain_community/utilities/google_books.py new file mode 100644 index 0000000000000..f1c3c97169238 --- /dev/null +++ b/libs/community/langchain_community/utilities/google_books.py @@ -0,0 +1,92 @@ +"""Util that calls Google Books.""" + +from typing import Dict, List, Optional + +import requests +from langchain_core.utils import get_from_dict_or_env +from pydantic import BaseModel, ConfigDict, model_validator + +GOOGLE_BOOKS_MAX_ITEM_SIZE = 5 +GOOGLE_BOOKS_API_URL = "https://www.googleapis.com/books/v1/volumes" + + +class GoogleBooksAPIWrapper(BaseModel): + """Wrapper around Google Books API. + + To use, you should have a Google Books API key available. + This wrapper will use the Google Books API to conduct searches and + fetch books based on a query passed in by the agents. By default, + it will return the top-k results. + + The response for each book will contain the book title, author name, summary, and + a source link. + """ + + google_books_api_key: Optional[str] = None + top_k_results: int = GOOGLE_BOOKS_MAX_ITEM_SIZE + + model_config = ConfigDict( + extra="forbid", + ) + + @model_validator(mode="before") + @classmethod + def validate_environment(cls, values: Dict) -> Dict: + """Validate that api key exists in environment.""" + google_books_api_key = get_from_dict_or_env( + values, "google_books_api_key", "GOOGLE_BOOKS_API_KEY" + ) + values["google_books_api_key"] = google_books_api_key + + return values + + def run(self, query: str) -> str: + # build Url based on API key, query, and max results + params = ( + ("q", query), + ("maxResults", self.top_k_results), + ("key", self.google_books_api_key), + ) + + # send request + response = requests.get(GOOGLE_BOOKS_API_URL, params=params) + json = response.json() + + # some error handeling + if response.status_code != 200: + code = response.status_code + error = json.get("error", {}).get("message", "Internal failure") + return f"Unable to retrieve books got status code {code}: {error}" + + # send back data + return self._format(query, json.get("items", [])) + + def _format(self, query: str, books: List) -> str: + if not books: + return f"Sorry no books could be found for your query: {query}" + + start = f"Here are {len(books)} suggestions for books related to {query}:" + + results = [] + results.append(start) + i = 1 + + for book in books: + info = book["volumeInfo"] + title = info["title"] + authors = self._format_authors(info["authors"]) + summary = info["description"] + source = info["infoLink"] + + desc = f'{i}. "{title}" by {authors}: {summary}\n' + desc += f"You can read more at {source}" + results.append(desc) + + i += 1 + + return "\n\n".join(results) + + def _format_authors(self, authors: List) -> str: + if len(authors) == 1: + return authors[0] + return "{} and {}".format(", ".join(authors[:-1]), authors[-1]) diff --git a/libs/community/tests/unit_tests/tools/test_imports.py b/libs/community/tests/unit_tests/tools/test_imports.py index b35b69186ee6b..0af4f3ab7ce48 100644 --- a/libs/community/tests/unit_tests/tools/test_imports.py +++ b/libs/community/tests/unit_tests/tools/test_imports.py @@ -62,6 +62,7 @@ "GmailGetThread", "GmailSearch", "GmailSendMessage", + "GoogleBooksQueryRun", "GoogleCloudTextToSpeechTool", "GooglePlacesTool", "GoogleSearchResults", diff --git a/libs/community/tests/unit_tests/utilities/test_imports.py b/libs/community/tests/unit_tests/utilities/test_imports.py index 0511820fa8999..7d2a008bb2e7c 100644 --- a/libs/community/tests/unit_tests/utilities/test_imports.py +++ b/libs/community/tests/unit_tests/utilities/test_imports.py @@ -13,6 +13,7 @@ "DuckDuckGoSearchAPIWrapper", "DriaAPIWrapper", "GoldenQueryAPIWrapper", + "GoogleBooksAPIWrapper", "GoogleFinanceAPIWrapper", "GoogleJobsAPIWrapper", "GoogleLensAPIWrapper",