Source code for langchain_community.utilities.google_books
"""Util that calls Google Books."""fromtypingimportDict,List,Optionalimportrequestsfromlangchain_core.utilsimportget_from_dict_or_envfrompydanticimportBaseModel,ConfigDict,model_validatorGOOGLE_BOOKS_MAX_ITEM_SIZE=5GOOGLE_BOOKS_API_URL="https://www.googleapis.com/books/v1/volumes"
[docs]classGoogleBooksAPIWrapper(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]=Nonetop_k_results:int=GOOGLE_BOOKS_MAX_ITEM_SIZEmodel_config=ConfigDict(extra="forbid",)@model_validator(mode="before")@classmethoddefvalidate_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_keyreturnvalues
[docs]defrun(self,query:str)->str:# build Url based on API key, query, and max resultsparams=(("q",query),("maxResults",self.top_k_results),("key",self.google_books_api_key),)# send requestresponse=requests.get(GOOGLE_BOOKS_API_URL,params=params)json=response.json()# some error handelingifresponse.status_code!=200:code=response.status_codeerror=json.get("error",{}).get("message","Internal failure")returnf"Unable to retrieve books got status code {code}: {error}"# send back datareturnself._format(query,json.get("items",[]))
def_format(self,query:str,books:List)->str:ifnotbooks:returnf"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=1forbookinbooks: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+=1return"\n\n".join(results)def_format_authors(self,authors:List)->str:iflen(authors)==1:returnauthors[0]return"{} and {}".format(", ".join(authors[:-1]),authors[-1])