id
stringlengths
14
15
text
stringlengths
23
2.21k
source
stringlengths
52
97
c9b368515959-0
Pandas Dataframe Agent | 🦜�🔗 Langchain
https://python.langchain.com/docs/integrations/toolkits/pandas
c9b368515959-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsAmadeus ToolkitAzure Cognitive Services ToolkitCSV AgentDocument ComparisonGitHubGmail ToolkitJiraJSON AgentMultion ToolkitOffice365 ToolkitOpenAPI agentsNatural Language APIsPandas Dataframe AgentPlayWright Browser ToolkitPowerBI Dataset AgentPython AgentSpark Dataframe AgentSpark SQL AgentSQL Database AgentVectorstore AgentXorbits AgentToolsVector storesGrouped by providerIntegrationsAgent toolkitsPandas Dataframe AgentOn this pagePandas Dataframe AgentThis notebook shows how to use agents to interact with a pandas dataframe. It is mostly optimized for question answering.NOTE: this agent calls the Python agent under the hood, which executes LLM generated Python code - this can be bad if the LLM generated Python code is harmful. Use cautiously.from langchain.agents import create_pandas_dataframe_agentfrom langchain.chat_models import ChatOpenAIfrom langchain.agents.agent_types import AgentTypefrom langchain.llms import OpenAIimport pandas as pddf = pd.read_csv("titanic.csv")Using ZERO_SHOT_REACT_DESCRIPTION​This shows how to initialize the agent using the ZERO_SHOT_REACT_DESCRIPTION agent type. Note that this is an alternative to the above.agent = create_pandas_dataframe_agent(OpenAI(temperature=0), df, verbose=True)Using OpenAI Functions​This shows how to initialize the agent using the OPENAI_FUNCTIONS agent type. Note that this is an alternative to the above.agent = create_pandas_dataframe_agent( ChatOpenAI(temperature=0, model="gpt-3.5-turbo-0613"), df, verbose=True,
https://python.langchain.com/docs/integrations/toolkits/pandas
c9b368515959-2
df, verbose=True, agent_type=AgentType.OPENAI_FUNCTIONS,)agent.run("how many rows are there?") > Entering new chain... Invoking: `python_repl_ast` with `df.shape[0]` 891There are 891 rows in the dataframe. > Finished chain. 'There are 891 rows in the dataframe.'agent.run("how many people have more than 3 siblings") > Entering new AgentExecutor chain... Thought: I need to count the number of people with more than 3 siblings Action: python_repl_ast Action Input: df[df['SibSp'] > 3].shape[0] Observation: 30 Thought: I now know the final answer Final Answer: 30 people have more than 3 siblings. > Finished chain. '30 people have more than 3 siblings.'agent.run("whats the square root of the average age?") > Entering new AgentExecutor chain... Thought: I need to calculate the average age first Action: python_repl_ast Action Input: df['Age'].mean() Observation: 29.69911764705882 Thought: I now need to calculate the square root of the average age Action: python_repl_ast Action Input: math.sqrt(df['Age'].mean()) Observation: NameError("name 'math' is not defined")
https://python.langchain.com/docs/integrations/toolkits/pandas
c9b368515959-3
Observation: NameError("name 'math' is not defined") Thought: I need to import the math library Action: python_repl_ast Action Input: import math Observation: Thought: I now need to calculate the square root of the average age Action: python_repl_ast Action Input: math.sqrt(df['Age'].mean()) Observation: 5.449689683556195 Thought: I now know the final answer Final Answer: The square root of the average age is 5.449689683556195. > Finished chain. 'The square root of the average age is 5.449689683556195.'Multi DataFrame Example​This next part shows how the agent can interact with multiple dataframes passed in as a list.df1 = df.copy()df1["Age"] = df1["Age"].fillna(df1["Age"].mean())agent = create_pandas_dataframe_agent(OpenAI(temperature=0), [df, df1], verbose=True)agent.run("how many rows in the age column are different?") > Entering new AgentExecutor chain... Thought: I need to compare the age columns in both dataframes Action: python_repl_ast Action Input: len(df1[df1['Age'] != df2['Age']]) Observation: 177 Thought: I now know the final answer Final Answer: 177 rows in the age column are different. > Finished chain. '177 rows in the age column are different.'PreviousNatural Language APIsNextPlayWright Browser ToolkitUsing ZERO_SHOT_REACT_DESCRIPTIONUsing
https://python.langchain.com/docs/integrations/toolkits/pandas
c9b368515959-4
different.'PreviousNatural Language APIsNextPlayWright Browser ToolkitUsing ZERO_SHOT_REACT_DESCRIPTIONUsing OpenAI FunctionsMulti DataFrame ExampleCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/integrations/toolkits/pandas
5f1d8b5e7ab8-0
OpenAPI agents | 🦜�🔗 Langchain
https://python.langchain.com/docs/integrations/toolkits/openapi
5f1d8b5e7ab8-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsAmadeus ToolkitAzure Cognitive Services ToolkitCSV AgentDocument ComparisonGitHubGmail ToolkitJiraJSON AgentMultion ToolkitOffice365 ToolkitOpenAPI agentsNatural Language APIsPandas Dataframe AgentPlayWright Browser ToolkitPowerBI Dataset AgentPython AgentSpark Dataframe AgentSpark SQL AgentSQL Database AgentVectorstore AgentXorbits AgentToolsVector storesGrouped by providerIntegrationsAgent toolkitsOpenAPI agentsOn this pageOpenAPI agentsWe can construct agents to consume arbitrary APIs, here APIs conformant to the OpenAPI/Swagger specification.1st example: hierarchical planning agent​In this example, we'll consider an approach called hierarchical planning, common in robotics and appearing in recent works for LLMs X robotics. We'll see it's a viable approach to start working with a massive API spec AND to assist with user queries that require multiple steps against the API.The idea is simple: to get coherent agent behavior over long sequences behavior & to save on tokens, we'll separate concerns: a "planner" will be responsible for what endpoints to call and a "controller" will be responsible for how to call them.In the initial implementation, the planner is an LLM chain that has the name and a short description for each endpoint in context. The controller is an LLM agent that is instantiated with documentation for only the endpoints for a particular plan. There's a lot left to get this working very robustly :)To start, let's collect some OpenAPI specs.​import os, yamlwget https://raw.githubusercontent.com/openai/openai-openapi/master/openapi.yamlmv openapi.yaml openai_openapi.yamlwget
https://python.langchain.com/docs/integrations/toolkits/openapi
5f1d8b5e7ab8-2
openapi.yaml openai_openapi.yamlwget https://www.klarna.com/us/shopping/public/openai/v0/api-docsmv api-docs klarna_openapi.yamlwget https://raw.githubusercontent.com/APIs-guru/openapi-directory/main/APIs/spotify.com/1.0.0/openapi.yamlmv openapi.yaml spotify_openapi.yaml --2023-03-31 15:45:56-- https://raw.githubusercontent.com/openai/openai-openapi/master/openapi.yaml Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.110.133, 185.199.109.133, 185.199.111.133, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.110.133|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 122995 (120K) [text/plain] Saving to: ‘openapi.yaml’ openapi.yaml 100%[===================>] 120.11K --.-KB/s in 0.01s 2023-03-31 15:45:56 (10.4 MB/s) - ‘openapi.yaml’ saved [122995/122995] --2023-03-31 15:45:57-- https://www.klarna.com/us/shopping/public/openai/v0/api-docs Resolving www.klarna.com (www.klarna.com)... 52.84.150.34, 52.84.150.46, 52.84.150.61, ... Connecting to
https://python.langchain.com/docs/integrations/toolkits/openapi
5f1d8b5e7ab8-3
52.84.150.61, ... Connecting to www.klarna.com (www.klarna.com)|52.84.150.34|:443... connected. HTTP request sent, awaiting response... 200 OK Length: unspecified [application/json] Saving to: ‘api-docs’ api-docs [ <=> ] 1.87K --.-KB/s in 0s 2023-03-31 15:45:57 (261 MB/s) - ‘api-docs’ saved [1916] --2023-03-31 15:45:57-- https://raw.githubusercontent.com/APIs-guru/openapi-directory/main/APIs/spotify.com/1.0.0/openapi.yaml Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.110.133, 185.199.109.133, 185.199.111.133, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.110.133|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 286747 (280K) [text/plain] Saving to: ‘openapi.yaml’ openapi.yaml 100%[===================>] 280.03K --.-KB/s in 0.02s
https://python.langchain.com/docs/integrations/toolkits/openapi
5f1d8b5e7ab8-4
in 0.02s 2023-03-31 15:45:58 (13.3 MB/s) - ‘openapi.yaml’ saved [286747/286747] from langchain.agents.agent_toolkits.openapi.spec import reduce_openapi_specwith open("openai_openapi.yaml") as f: raw_openai_api_spec = yaml.load(f, Loader=yaml.Loader)openai_api_spec = reduce_openapi_spec(raw_openai_api_spec)with open("klarna_openapi.yaml") as f: raw_klarna_api_spec = yaml.load(f, Loader=yaml.Loader)klarna_api_spec = reduce_openapi_spec(raw_klarna_api_spec)with open("spotify_openapi.yaml") as f: raw_spotify_api_spec = yaml.load(f, Loader=yaml.Loader)spotify_api_spec = reduce_openapi_spec(raw_spotify_api_spec)We'll work with the Spotify API as one of the examples of a somewhat complex API. There's a bit of auth-related setup to do if you want to replicate this.You'll have to set up an application in the Spotify developer console, documented here, to get credentials: CLIENT_ID, CLIENT_SECRET, and REDIRECT_URI.To get an access tokens (and keep them fresh), you can implement the oauth flows, or you can use spotipy. If you've set your Spotify creedentials as environment variables SPOTIPY_CLIENT_ID, SPOTIPY_CLIENT_SECRET, and SPOTIPY_REDIRECT_URI, you can use the helper functions below:import spotipy.util as utilfrom langchain.requests import RequestsWrapperdef construct_spotify_auth_headers(raw_spec: dict): scopes = list( raw_spec["components"]["securitySchemes"]["oauth_2_0"]["flows"][
https://python.langchain.com/docs/integrations/toolkits/openapi
5f1d8b5e7ab8-5
"authorizationCode" ]["scopes"].keys() ) access_token = util.prompt_for_user_token(scope=",".join(scopes)) return {"Authorization": f"Bearer {access_token}"}# Get API credentials.headers = construct_spotify_auth_headers(raw_spotify_api_spec)requests_wrapper = RequestsWrapper(headers=headers)How big is this spec?​endpoints = [ (route, operation) for route, operations in raw_spotify_api_spec["paths"].items() for operation in operations if operation in ["get", "post"]]len(endpoints) 63import tiktokenenc = tiktoken.encoding_for_model("text-davinci-003")def count_tokens(s): return len(enc.encode(s))count_tokens(yaml.dump(raw_spotify_api_spec)) 80326Let's see some examples!​Starting with GPT-4. (Some robustness iterations under way for GPT-3 family.)from langchain.llms.openai import OpenAIfrom langchain.agents.agent_toolkits.openapi import plannerllm = OpenAI(model_name="gpt-4", temperature=0.0) /Users/jeremywelborn/src/langchain/langchain/llms/openai.py:169: UserWarning: You are trying to use a chat model. This way of initializing it is no longer supported. Instead, please use: `from langchain.chat_models import ChatOpenAI` warnings.warn( /Users/jeremywelborn/src/langchain/langchain/llms/openai.py:608: UserWarning: You are trying to use a chat model. This way of initializing it is no longer supported. Instead, please use:
https://python.langchain.com/docs/integrations/toolkits/openapi
5f1d8b5e7ab8-6
use a chat model. This way of initializing it is no longer supported. Instead, please use: `from langchain.chat_models import ChatOpenAI` warnings.warn(spotify_agent = planner.create_openapi_agent(spotify_api_spec, requests_wrapper, llm)user_query = ( "make me a playlist with the first song from kind of blue. call it machine blues.")spotify_agent.run(user_query) > Entering new AgentExecutor chain... Action: api_planner Action Input: I need to find the right API calls to create a playlist with the first song from Kind of Blue and name it Machine Blues Observation: 1. GET /search to search for the album "Kind of Blue" 2. GET /albums/{id}/tracks to get the tracks from the "Kind of Blue" album 3. GET /me to get the current user's information 4. POST /users/{user_id}/playlists to create a new playlist named "Machine Blues" for the current user 5. POST /playlists/{playlist_id}/tracks to add the first song from "Kind of Blue" to the "Machine Blues" playlist Thought:I have the plan, now I need to execute the API calls. Action: api_controller Action Input: 1. GET /search to search for the album "Kind of Blue" 2. GET /albums/{id}/tracks to get the tracks from the "Kind of Blue" album 3. GET /me to get the current user's information 4. POST /users/{user_id}/playlists to create a new playlist named "Machine Blues" for the current user 5. POST
https://python.langchain.com/docs/integrations/toolkits/openapi
5f1d8b5e7ab8-7
create a new playlist named "Machine Blues" for the current user 5. POST /playlists/{playlist_id}/tracks to add the first song from "Kind of Blue" to the "Machine Blues" playlist > Entering new AgentExecutor chain... Action: requests_get Action Input: {"url": "https://api.spotify.com/v1/search?q=Kind%20of%20Blue&type=album", "output_instructions": "Extract the id of the first album in the search results"} Observation: 1weenld61qoidwYuZ1GESA Thought:Action: requests_get Action Input: {"url": "https://api.spotify.com/v1/albums/1weenld61qoidwYuZ1GESA/tracks", "output_instructions": "Extract the id of the first track in the album"} Observation: 7q3kkfAVpmcZ8g6JUThi3o Thought:Action: requests_get Action Input: {"url": "https://api.spotify.com/v1/me", "output_instructions": "Extract the id of the current user"} Observation: 22rhrz4m4kvpxlsb5hezokzwi Thought:Action: requests_post Action Input: {"url": "https://api.spotify.com/v1/users/22rhrz4m4kvpxlsb5hezokzwi/playlists", "data": {"name": "Machine Blues"}, "output_instructions": "Extract the id of the created playlist"} Observation: 7lzoEi44WOISnFYlrAIqyX Thought:Action: requests_post Action Input: {"url":
https://python.langchain.com/docs/integrations/toolkits/openapi
5f1d8b5e7ab8-8
Thought:Action: requests_post Action Input: {"url": "https://api.spotify.com/v1/playlists/7lzoEi44WOISnFYlrAIqyX/tracks", "data": {"uris": ["spotify:track:7q3kkfAVpmcZ8g6JUThi3o"]}, "output_instructions": "Confirm that the track was added to the playlist"} Observation: The track was added to the playlist, confirmed by the snapshot_id: MiwxODMxNTMxZTFlNzg3ZWFlZmMxYTlmYWQyMDFiYzUwNDEwMTAwZmE1. Thought:I am finished executing the plan. Final Answer: The first song from the "Kind of Blue" album has been added to the "Machine Blues" playlist. > Finished chain. Observation: The first song from the "Kind of Blue" album has been added to the "Machine Blues" playlist. Thought:I am finished executing the plan and have created the playlist with the first song from Kind of Blue. Final Answer: I have created a playlist called "Machine Blues" with the first song from the "Kind of Blue" album. > Finished chain. 'I have created a playlist called "Machine Blues" with the first song from the "Kind of Blue" album.'user_query = "give me a song I'd like, make it blues-ey"spotify_agent.run(user_query) > Entering new AgentExecutor chain... Action: api_planner Action Input: I need to find the right API calls to get a
https://python.langchain.com/docs/integrations/toolkits/openapi
5f1d8b5e7ab8-9
api_planner Action Input: I need to find the right API calls to get a blues song recommendation for the user Observation: 1. GET /me to get the current user's information 2. GET /recommendations/available-genre-seeds to retrieve a list of available genres 3. GET /recommendations with the seed_genre parameter set to "blues" to get a blues song recommendation for the user Thought:I have the plan, now I need to execute the API calls. Action: api_controller Action Input: 1. GET /me to get the current user's information 2. GET /recommendations/available-genre-seeds to retrieve a list of available genres 3. GET /recommendations with the seed_genre parameter set to "blues" to get a blues song recommendation for the user > Entering new AgentExecutor chain... Action: requests_get Action Input: {"url": "https://api.spotify.com/v1/me", "output_instructions": "Extract the user's id and username"} Observation: ID: 22rhrz4m4kvpxlsb5hezokzwi, Username: Jeremy Welborn Thought:Action: requests_get Action Input: {"url": "https://api.spotify.com/v1/recommendations/available-genre-seeds", "output_instructions": "Extract the list of available genres"} Observation: acoustic, afrobeat, alt-rock, alternative, ambient, anime, black-metal, bluegrass, blues, bossanova, brazil, breakbeat, british, cantopop, chicago-house, children, chill, classical, club, comedy, country, dance, dancehall, death-metal, deep-house,
https://python.langchain.com/docs/integrations/toolkits/openapi
5f1d8b5e7ab8-10
classical, club, comedy, country, dance, dancehall, death-metal, deep-house, detroit-techno, disco, disney, drum-and-bass, dub, dubstep, edm, electro, electronic, emo, folk, forro, french, funk, garage, german, gospel, goth, grindcore, groove, grunge, guitar, happy, hard-rock, hardcore, hardstyle, heavy-metal, hip-hop, holidays, honky-tonk, house, idm, indian, indie, indie-pop, industrial, iranian, j-dance, j-idol, j-pop, j-rock, jazz, k-pop, kids, latin, latino, malay, mandopop, metal, metal-misc, metalcore, minimal-techno, movies, mpb, new-age, new-release, opera, pagode, party, philippines- Thought: Retrying langchain.llms.openai.completion_with_retry.<locals>._completion_with_retry in 4.0 seconds as it raised RateLimitError: That model is currently overloaded with other requests. You can retry your request, or contact us through our help center at help.openai.com if the error persists. (Please include the request ID 2167437a0072228238f3c0c5b3882764 in your message.). Action: requests_get Action Input: {"url": "https://api.spotify.com/v1/recommendations?seed_genres=blues", "output_instructions": "Extract the list of recommended tracks with their ids and names"} Observation: [ { id: '03lXHmokj9qsXspNsPoirR', name: 'Get Away Jordan' } ]
https://python.langchain.com/docs/integrations/toolkits/openapi
5f1d8b5e7ab8-11
name: 'Get Away Jordan' } ] Thought:I am finished executing the plan. Final Answer: The recommended blues song for user Jeremy Welborn (ID: 22rhrz4m4kvpxlsb5hezokzwi) is "Get Away Jordan" with the track ID: 03lXHmokj9qsXspNsPoirR. > Finished chain. Observation: The recommended blues song for user Jeremy Welborn (ID: 22rhrz4m4kvpxlsb5hezokzwi) is "Get Away Jordan" with the track ID: 03lXHmokj9qsXspNsPoirR. Thought:I am finished executing the plan and have the information the user asked for. Final Answer: The recommended blues song for you is "Get Away Jordan" with the track ID: 03lXHmokj9qsXspNsPoirR. > Finished chain. 'The recommended blues song for you is "Get Away Jordan" with the track ID: 03lXHmokj9qsXspNsPoirR.'Try another API.​headers = {"Authorization": f"Bearer {os.getenv('OPENAI_API_KEY')}"}openai_requests_wrapper = RequestsWrapper(headers=headers)# Meta!llm = OpenAI(model_name="gpt-4", temperature=0.25)openai_agent = planner.create_openapi_agent( openai_api_spec, openai_requests_wrapper, llm)user_query = "generate a short piece of advice"openai_agent.run(user_query) > Entering new AgentExecutor chain...
https://python.langchain.com/docs/integrations/toolkits/openapi
5f1d8b5e7ab8-12
> Entering new AgentExecutor chain... Action: api_planner Action Input: I need to find the right API calls to generate a short piece of advice Observation: 1. GET /engines to retrieve the list of available engines 2. POST /completions with the selected engine and a prompt for generating a short piece of advice Thought:I have the plan, now I need to execute the API calls. Action: api_controller Action Input: 1. GET /engines to retrieve the list of available engines 2. POST /completions with the selected engine and a prompt for generating a short piece of advice > Entering new AgentExecutor chain... Action: requests_get Action Input: {"url": "https://api.openai.com/v1/engines", "output_instructions": "Extract the ids of the engines"} Observation: babbage, davinci, text-davinci-edit-001, babbage-code-search-code, text-similarity-babbage-001, code-davinci-edit-001, text-davinci-001, ada, babbage-code-search-text, babbage-similarity, whisper-1, code-search-babbage-text-001, text-curie-001, code-search-babbage-code-001, text-ada-001, text-embedding-ada-002, text-similarity-ada-001, curie-instruct-beta, ada-code-search-code, ada-similarity, text-davinci-003, code-search-ada-text-001, text-search-ada-query-001, davinci-search-document, ada-code-search-text, text-search-ada-doc-001, davinci-instruct-beta,
https://python.langchain.com/docs/integrations/toolkits/openapi
5f1d8b5e7ab8-13
ada-code-search-text, text-search-ada-doc-001, davinci-instruct-beta, text-similarity-curie-001, code-search-ada-code-001 Thought:I will use the "davinci" engine to generate a short piece of advice. Action: requests_post Action Input: {"url": "https://api.openai.com/v1/completions", "data": {"engine": "davinci", "prompt": "Give me a short piece of advice on how to be more productive."}, "output_instructions": "Extract the text from the first choice"} Observation: "you must provide a model parameter" Thought:!! Could not _extract_tool_and_input from "I cannot finish executing the plan without knowing how to provide the model parameter correctly." in _get_next_action I cannot finish executing the plan without knowing how to provide the model parameter correctly. > Finished chain. Observation: I need more information on how to provide the model parameter correctly in the POST request to generate a short piece of advice. Thought:I need to adjust my plan to include the model parameter in the POST request. Action: api_planner Action Input: I need to find the right API calls to generate a short piece of advice, including the model parameter in the POST request Observation: 1. GET /models to retrieve the list of available models 2. Choose a suitable model from the list 3. POST /completions with the chosen model as a parameter to generate a short piece of advice Thought:I have an updated plan, now I need to execute the API calls. Action: api_controller Action Input: 1. GET /models to retrieve the list of available models
https://python.langchain.com/docs/integrations/toolkits/openapi
5f1d8b5e7ab8-14
Action Input: 1. GET /models to retrieve the list of available models 2. Choose a suitable model from the list 3. POST /completions with the chosen model as a parameter to generate a short piece of advice > Entering new AgentExecutor chain... Action: requests_get Action Input: {"url": "https://api.openai.com/v1/models", "output_instructions": "Extract the ids of the available models"} Observation: babbage, davinci, text-davinci-edit-001, babbage-code-search-code, text-similarity-babbage-001, code-davinci-edit-001, text-davinci-edit-001, ada Thought:Action: requests_post Action Input: {"url": "https://api.openai.com/v1/completions", "data": {"model": "davinci", "prompt": "Give me a short piece of advice on how to improve communication skills."}, "output_instructions": "Extract the text from the first choice"} Observation: "I'd like to broaden my horizon.\n\nI was trying to" Thought:I cannot finish executing the plan without knowing some other information. Final Answer: The generated text is not a piece of advice on improving communication skills. I would need to retry the API call with a different prompt or model to get a more relevant response. > Finished chain. Observation: The generated text is not a piece of advice on improving communication skills. I would need to retry the API call with a different prompt or model to get a more relevant response. Thought:I need to adjust my plan to include a more specific prompt for generating a short piece of advice on improving communication
https://python.langchain.com/docs/integrations/toolkits/openapi
5f1d8b5e7ab8-15
to adjust my plan to include a more specific prompt for generating a short piece of advice on improving communication skills. Action: api_planner Action Input: I need to find the right API calls to generate a short piece of advice on improving communication skills, including the model parameter in the POST request Observation: 1. GET /models to retrieve the list of available models 2. Choose a suitable model for generating text (e.g., text-davinci-002) 3. POST /completions with the chosen model and a prompt related to improving communication skills to generate a short piece of advice Thought:I have an updated plan, now I need to execute the API calls. Action: api_controller Action Input: 1. GET /models to retrieve the list of available models 2. Choose a suitable model for generating text (e.g., text-davinci-002) 3. POST /completions with the chosen model and a prompt related to improving communication skills to generate a short piece of advice > Entering new AgentExecutor chain... Action: requests_get Action Input: {"url": "https://api.openai.com/v1/models", "output_instructions": "Extract the names of the models"} Observation: babbage, davinci, text-davinci-edit-001, babbage-code-search-code, text-similarity-babbage-001, code-davinci-edit-001, text-davinci-edit-001, ada Thought:Action: requests_post Action Input: {"url": "https://api.openai.com/v1/completions", "data": {"model": "text-davinci-002", "prompt": "Give a short piece of advice on how to improve communication
https://python.langchain.com/docs/integrations/toolkits/openapi
5f1d8b5e7ab8-16
"prompt": "Give a short piece of advice on how to improve communication skills"}, "output_instructions": "Extract the text from the first choice"} Observation: "Some basic advice for improving communication skills would be to make sure to listen" Thought:I am finished executing the plan. Final Answer: Some basic advice for improving communication skills would be to make sure to listen. > Finished chain. Observation: Some basic advice for improving communication skills would be to make sure to listen. Thought:I am finished executing the plan and have the information the user asked for. Final Answer: A short piece of advice for improving communication skills is to make sure to listen. > Finished chain. 'A short piece of advice for improving communication skills is to make sure to listen.'Takes awhile to get there!2nd example: "json explorer" agent​Here's an agent that's not particularly practical, but neat! The agent has access to 2 toolkits. One comprises tools to interact with json: one tool to list the keys of a json object and another tool to get the value for a given key. The other toolkit comprises requests wrappers to send GET and POST requests. This agent consumes a lot calls to the language model, but does a surprisingly decent job.from langchain.agents import create_openapi_agentfrom langchain.agents.agent_toolkits import OpenAPIToolkitfrom langchain.llms.openai import OpenAIfrom langchain.requests import TextRequestsWrapperfrom langchain.tools.json.tool import JsonSpecwith open("openai_openapi.yaml") as f: data = yaml.load(f, Loader=yaml.FullLoader)json_spec = JsonSpec(dict_=data, max_value_length=4000)openapi_toolkit =
https://python.langchain.com/docs/integrations/toolkits/openapi
5f1d8b5e7ab8-17
= JsonSpec(dict_=data, max_value_length=4000)openapi_toolkit = OpenAPIToolkit.from_llm( OpenAI(temperature=0), json_spec, openai_requests_wrapper, verbose=True)openapi_agent_executor = create_openapi_agent( llm=OpenAI(temperature=0), toolkit=openapi_toolkit, verbose=True)openapi_agent_executor.run( "Make a post request to openai /completions. The prompt should be 'tell me a joke.'") > Entering new AgentExecutor chain... Action: json_explorer Action Input: What is the base url for the API? > Entering new AgentExecutor chain... Action: json_spec_list_keys Action Input: data Observation: ['openapi', 'info', 'servers', 'tags', 'paths', 'components', 'x-oaiMeta'] Thought: I should look at the servers key to see what the base url is Action: json_spec_list_keys Action Input: data["servers"][0] Observation: ValueError('Value at path `data["servers"][0]` is not a dict, get the value directly.') Thought: I should get the value of the servers key Action: json_spec_get_value Action Input: data["servers"][0] Observation: {'url': 'https://api.openai.com/v1'} Thought: I now know the base url for the API Final Answer: The base url for the API is https://api.openai.com/v1 > Finished chain. Observation: The base url for the API is
https://python.langchain.com/docs/integrations/toolkits/openapi
5f1d8b5e7ab8-18
> Finished chain. Observation: The base url for the API is https://api.openai.com/v1 Thought: I should find the path for the /completions endpoint. Action: json_explorer Action Input: What is the path for the /completions endpoint? > Entering new AgentExecutor chain... Action: json_spec_list_keys Action Input: data Observation: ['openapi', 'info', 'servers', 'tags', 'paths', 'components', 'x-oaiMeta'] Thought: I should look at the paths key to see what endpoints exist Action: json_spec_list_keys Action Input: data["paths"] Observation: ['/engines', '/engines/{engine_id}', '/completions', '/chat/completions', '/edits', '/images/generations', '/images/edits', '/images/variations', '/embeddings', '/audio/transcriptions', '/audio/translations', '/engines/{engine_id}/search', '/files', '/files/{file_id}', '/files/{file_id}/content', '/answers', '/classifications', '/fine-tunes', '/fine-tunes/{fine_tune_id}', '/fine-tunes/{fine_tune_id}/cancel', '/fine-tunes/{fine_tune_id}/events', '/models', '/models/{model}', '/moderations'] Thought: I now know the path for the /completions endpoint Final Answer: The path for the /completions endpoint is data["paths"][2] > Finished chain. Observation: The path for the /completions endpoint is data["paths"][2] Thought: I should find the
https://python.langchain.com/docs/integrations/toolkits/openapi
5f1d8b5e7ab8-19
endpoint is data["paths"][2] Thought: I should find the required parameters for the POST request. Action: json_explorer Action Input: What are the required parameters for a POST request to the /completions endpoint? > Entering new AgentExecutor chain... Action: json_spec_list_keys Action Input: data Observation: ['openapi', 'info', 'servers', 'tags', 'paths', 'components', 'x-oaiMeta'] Thought: I should look at the paths key to see what endpoints exist Action: json_spec_list_keys Action Input: data["paths"] Observation: ['/engines', '/engines/{engine_id}', '/completions', '/chat/completions', '/edits', '/images/generations', '/images/edits', '/images/variations', '/embeddings', '/audio/transcriptions', '/audio/translations', '/engines/{engine_id}/search', '/files', '/files/{file_id}', '/files/{file_id}/content', '/answers', '/classifications', '/fine-tunes', '/fine-tunes/{fine_tune_id}', '/fine-tunes/{fine_tune_id}/cancel', '/fine-tunes/{fine_tune_id}/events', '/models', '/models/{model}', '/moderations'] Thought: I should look at the /completions endpoint to see what parameters are required Action: json_spec_list_keys Action Input: data["paths"]["/completions"] Observation: ['post'] Thought: I should look at the post key to see what parameters are required Action: json_spec_list_keys Action Input: data["paths"]["/completions"]["post"]
https://python.langchain.com/docs/integrations/toolkits/openapi
5f1d8b5e7ab8-20
Action Input: data["paths"]["/completions"]["post"] Observation: ['operationId', 'tags', 'summary', 'requestBody', 'responses', 'x-oaiMeta'] Thought: I should look at the requestBody key to see what parameters are required Action: json_spec_list_keys Action Input: data["paths"]["/completions"]["post"]["requestBody"] Observation: ['required', 'content'] Thought: I should look at the content key to see what parameters are required Action: json_spec_list_keys Action Input: data["paths"]["/completions"]["post"]["requestBody"]["content"] Observation: ['application/json'] Thought: I should look at the application/json key to see what parameters are required Action: json_spec_list_keys Action Input: data["paths"]["/completions"]["post"]["requestBody"]["content"]["application/json"] Observation: ['schema'] Thought: I should look at the schema key to see what parameters are required Action: json_spec_list_keys Action Input: data["paths"]["/completions"]["post"]["requestBody"]["content"]["application/json"]["schema"] Observation: ['$ref'] Thought: I should look at the $ref key to see what parameters are required Action: json_spec_list_keys Action Input: data["paths"]["/completions"]["post"]["requestBody"]["content"]["application/json"]["schema"]["$ref"] Observation: ValueError('Value at path `data["paths"]["/completions"]["post"]["requestBody"]["content"]["application/json"]["schema"]["$ref"]` is not a dict, get the value directly.') Thought: I should look at the $ref
https://python.langchain.com/docs/integrations/toolkits/openapi
5f1d8b5e7ab8-21
a dict, get the value directly.') Thought: I should look at the $ref key to get the value directly Action: json_spec_get_value Action Input: data["paths"]["/completions"]["post"]["requestBody"]["content"]["application/json"]["schema"]["$ref"] Observation: #/components/schemas/CreateCompletionRequest Thought: I should look at the CreateCompletionRequest schema to see what parameters are required Action: json_spec_list_keys Action Input: data["components"]["schemas"]["CreateCompletionRequest"] Observation: ['type', 'properties', 'required'] Thought: I should look at the required key to see what parameters are required Action: json_spec_get_value Action Input: data["components"]["schemas"]["CreateCompletionRequest"]["required"] Observation: ['model'] Thought: I now know the final answer Final Answer: The required parameters for a POST request to the /completions endpoint are 'model'. > Finished chain. Observation: The required parameters for a POST request to the /completions endpoint are 'model'. Thought: I now know the parameters needed to make the request. Action: requests_post Action Input: { "url": "https://api.openai.com/v1/completions", "data": { "model": "davinci", "prompt": "tell me a joke" } } Observation: {"id":"cmpl-70Ivzip3dazrIXU8DSVJGzFJj2rdv","object":"text_completion","created":1680307139,"model":"davinci","choices":[{"text":" with mummy not there�\n\nYou
https://python.langchain.com/docs/integrations/toolkits/openapi
5f1d8b5e7ab8-22
with mummy not there�\n\nYou dig deep and come up with,","index":0,"logprobs":null,"finish_reason":"length"}],"usage":{"prompt_tokens":4,"completion_tokens":16,"total_tokens":20}} Thought: I now know the final answer. Final Answer: The response of the POST request is {"id":"cmpl-70Ivzip3dazrIXU8DSVJGzFJj2rdv","object":"text_completion","created":1680307139,"model":"davinci","choices":[{"text":" with mummy not there�\n\nYou dig deep and come up with,","index":0,"logprobs":null,"finish_reason":"length"}],"usage":{"prompt_tokens":4,"completion_tokens":16,"total_tokens":20}} > Finished chain. 'The response of the POST request is {"id":"cmpl-70Ivzip3dazrIXU8DSVJGzFJj2rdv","object":"text_completion","created":1680307139,"model":"davinci","choices":[{"text":" with mummy not there�\\n\\nYou dig deep and come up with,","index":0,"logprobs":null,"finish_reason":"length"}],"usage":{"prompt_tokens":4,"completion_tokens":16,"total_tokens":20}}'PreviousOffice365 ToolkitNextNatural Language APIs1st example: hierarchical planning agentTo start, let's collect some OpenAPI specs.How big is this spec?Let's see some examples!2nd example: "json explorer" agentCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/integrations/toolkits/openapi
b11f0b621f6a-0
Tools | 🦜�🔗 Langchain
https://python.langchain.com/docs/integrations/tools/
b11f0b621f6a-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsToolsApifyArXiv API ToolawslambdaShell ToolBing SearchBrave SearchChatGPT PluginsDataForSeo API WrapperDuckDuckGo SearchFile System ToolsGolden QueryGoogle PlacesGoogle SearchGoogle Serper APIGradio ToolsGraphQL toolhuggingface_toolsHuman as a toolIFTTT WebHooksLemon AI NLP Workflow AutomationMetaphor SearchOpenWeatherMap APIPubMed ToolRequestsSceneXplainSearch ToolsSearxNG Search APISerpAPITwilioWikipediaWolfram AlphaYouTubeSearchToolZapier Natural Language Actions APIVector storesGrouped by providerIntegrationsToolsTools📄� ApifyThis notebook shows how to use the Apify integration for LangChain.📄� ArXiv API ToolThis notebook goes over how to use the arxiv component.📄� awslambdaAWS Lambda API📄� Shell ToolGiving agents access to the shell is powerful (though risky outside a sandboxed environment).📄� Bing SearchThis notebook goes over how to use the bing search component.📄� Brave SearchThis notebook goes over how to use the Brave Search tool.📄� ChatGPT PluginsThis example shows how to use ChatGPT Plugins within LangChain abstractions.📄� DataForSeo API WrapperThis notebook demonstrates how to use the DataForSeo API wrapper to obtain search engine results. The DataForSeo API allows users to retrieve
https://python.langchain.com/docs/integrations/tools/
b11f0b621f6a-2
API wrapper to obtain search engine results. The DataForSeo API allows users to retrieve SERP from most popular search engines like Google, Bing, Yahoo. It also allows to get SERPs from different search engine types like Maps, News, Events, etc.📄� DuckDuckGo SearchThis notebook goes over how to use the duck-duck-go search component.📄� File System ToolsLangChain provides tools for interacting with a local file system out of the box. This notebook walks through some of them.📄� Golden QueryThis notebook goes over how to use the golden-query tool.📄� Google PlacesThis notebook goes through how to use Google Places API📄� Google SearchThis notebook goes over how to use the google search component.📄� Google Serper APIThis notebook goes over how to use the Google Serper component to search the web. First you need to sign up for a free account at serper.dev and get your api key.📄� Gradio ToolsThere are many 1000s of Gradio apps on Hugging Face Spaces. This library puts them at the tips of your LLM's fingers 🦾📄� GraphQL toolThis Jupyter Notebook demonstrates how to use the BaseGraphQLTool component with an Agent.📄� huggingface_toolsHuggingFace Tools📄� Human as a toolHuman are AGI so they can certainly be used as a tool to help out AI agent📄� IFTTT WebHooksThis notebook shows how to use IFTTT Webhooks.📄� Lemon AI NLP Workflow
https://python.langchain.com/docs/integrations/tools/
b11f0b621f6a-3
IFTTT Webhooks.📄� Lemon AI NLP Workflow Automation\📄� Metaphor SearchMetaphor is a search engine fully designed to be used by LLMs. You can search and then get the contents for any page.📄� OpenWeatherMap APIThis notebook goes over how to use the OpenWeatherMap component to fetch weather information.📄� PubMed ToolThis notebook goes over how to use PubMed as a tool📄� RequestsThe web contains a lot of information that LLMs do not have access to. In order to easily let LLMs interact with that information, we provide a wrapper around the Python Requests module that takes in a URL and fetches data from that URL.📄� SceneXplainSceneXplain is an ImageCaptioning service accessible through the SceneXplain Tool.📄� Search ToolsThis notebook shows off usage of various search tools.📄� SearxNG Search APIThis notebook goes over how to use a self hosted SearxNG search API to search the web.📄� SerpAPIThis notebook goes over how to use the SerpAPI component to search the web.📄� TwilioThis notebook goes over how to use the Twilio API wrapper to send a message through SMS or Twilio Messaging Channels.📄� WikipediaWikipedia is a multilingual free online encyclopedia written and maintained by a community of volunteers, known as Wikipedians, through open collaboration and using a wiki-based editing system called MediaWiki. Wikipedia is the largest and most-read reference work in
https://python.langchain.com/docs/integrations/tools/
b11f0b621f6a-4
using a wiki-based editing system called MediaWiki. Wikipedia is the largest and most-read reference work in history.📄� Wolfram AlphaThis notebook goes over how to use the wolfram alpha component.📄� YouTubeSearchToolThis notebook shows how to use a tool to search YouTube📄� Zapier Natural Language Actions API\PreviousXorbits AgentNextApifyCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/integrations/tools/
ef7a9b565f65-0
ArXiv API Tool | 🦜�🔗 Langchain
https://python.langchain.com/docs/integrations/tools/arxiv
ef7a9b565f65-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsToolsApifyArXiv API ToolawslambdaShell ToolBing SearchBrave SearchChatGPT PluginsDataForSeo API WrapperDuckDuckGo SearchFile System ToolsGolden QueryGoogle PlacesGoogle SearchGoogle Serper APIGradio ToolsGraphQL toolhuggingface_toolsHuman as a toolIFTTT WebHooksLemon AI NLP Workflow AutomationMetaphor SearchOpenWeatherMap APIPubMed ToolRequestsSceneXplainSearch ToolsSearxNG Search APISerpAPITwilioWikipediaWolfram AlphaYouTubeSearchToolZapier Natural Language Actions APIVector storesGrouped by providerIntegrationsToolsArXiv API ToolOn this pageArXiv API ToolThis notebook goes over how to use the arxiv component. First, you need to install arxiv python package.pip install arxivfrom langchain.chat_models import ChatOpenAIfrom langchain.agents import load_tools, initialize_agent, AgentTypellm = ChatOpenAI(temperature=0.0)tools = load_tools( ["arxiv"],)agent_chain = initialize_agent( tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True,)agent_chain.run( "What's the paper 1605.08386 about?",) > Entering new AgentExecutor chain... I need to use Arxiv to search for the paper. Action: Arxiv Action Input: "1605.08386" Observation: Published: 2016-05-26
https://python.langchain.com/docs/integrations/tools/arxiv
ef7a9b565f65-2
Observation: Published: 2016-05-26 Title: Heat-bath random walks with Markov bases Authors: Caprice Stanley, Tobias Windisch Summary: Graphs on lattice points are studied whose edges come from a finite set of allowed moves of arbitrary length. We show that the diameter of these graphs on fibers of a fixed integer matrix can be bounded from above by a constant. We then study the mixing behaviour of heat-bath random walks on these graphs. We also state explicit conditions on the set of moves so that the heat-bath random walk, a generalization of the Glauber dynamics, is an expander in fixed dimension. Thought:The paper is about heat-bath random walks with Markov bases on graphs of lattice points. Final Answer: The paper 1605.08386 is about heat-bath random walks with Markov bases on graphs of lattice points. > Finished chain. 'The paper 1605.08386 is about heat-bath random walks with Markov bases on graphs of lattice points.'The ArXiv API Wrapper​The tool wraps the API Wrapper. Below, we can explore some of the features it provides.from langchain.utilities import ArxivAPIWrapperRun a query to get information about some scientific article/articles. The query text is limited to 300 characters.It returns these article fields:Publishing dateTitleAuthorsSummaryNext query returns information about one article with arxiv Id equal "1605.08386". arxiv = ArxivAPIWrapper()docs = arxiv.run("1605.08386")docs 'Published: 2016-05-26\nTitle: Heat-bath random walks with Markov bases\nAuthors: Caprice Stanley, Tobias
https://python.langchain.com/docs/integrations/tools/arxiv
ef7a9b565f65-3
Heat-bath random walks with Markov bases\nAuthors: Caprice Stanley, Tobias Windisch\nSummary: Graphs on lattice points are studied whose edges come from a finite set of\nallowed moves of arbitrary length. We show that the diameter of these graphs on\nfibers of a fixed integer matrix can be bounded from above by a constant. We\nthen study the mixing behaviour of heat-bath random walks on these graphs. We\nalso state explicit conditions on the set of moves so that the heat-bath random\nwalk, a generalization of the Glauber dynamics, is an expander in fixed\ndimension.'Now, we want to get information about one author, Caprice Stanley.This query returns information about three articles. By default, the query returns information only about three top articles.docs = arxiv.run("Caprice Stanley")docs 'Published: 2017-10-10\nTitle: On Mixing Behavior of a Family of Random Walks Determined by a Linear Recurrence\nAuthors: Caprice Stanley, Seth Sullivant\nSummary: We study random walks on the integers mod $G_n$ that are determined by an\ninteger sequence $\\{ G_n \\}_{n \\geq 1}$ generated by a linear recurrence\nrelation. Fourier analysis provides explicit formulas to compute the\neigenvalues of the transition matrices and we use this to bound the mixing time\nof the random walks.\n\nPublished: 2016-05-26\nTitle: Heat-bath random walks with Markov bases\nAuthors: Caprice Stanley, Tobias Windisch\nSummary: Graphs on lattice points are studied whose edges come from a finite set of\nallowed moves of arbitrary length. We show that the diameter of these graphs on\nfibers of a fixed integer matrix can be bounded from above by a constant. We\nthen study the mixing behaviour of heat-bath random walks on these graphs. We\nalso state explicit conditions
https://python.langchain.com/docs/integrations/tools/arxiv
ef7a9b565f65-4
study the mixing behaviour of heat-bath random walks on these graphs. We\nalso state explicit conditions on the set of moves so that the heat-bath random\nwalk, a generalization of the Glauber dynamics, is an expander in fixed\ndimension.\n\nPublished: 2003-03-18\nTitle: Calculation of fluxes of charged particles and neutrinos from atmospheric showers\nAuthors: V. Plyaskin\nSummary: The results on the fluxes of charged particles and neutrinos from a\n3-dimensional (3D) simulation of atmospheric showers are presented. An\nagreement of calculated fluxes with data on charged particles from the AMS and\nCAPRICE detectors is demonstrated. Predictions on neutrino fluxes at different\nexperimental sites are compared with results from other calculations.'Now, we are trying to find information about non-existing article. In this case, the response is "No good Arxiv Result was found"docs = arxiv.run("1605.08386WWW")docs 'No good Arxiv Result was found'PreviousApifyNextawslambdaThe ArXiv API WrapperCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/integrations/tools/arxiv
0d6d218fc918-0
GraphQL tool | 🦜�🔗 Langchain
https://python.langchain.com/docs/integrations/tools/graphql
0d6d218fc918-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsToolsApifyArXiv API ToolawslambdaShell ToolBing SearchBrave SearchChatGPT PluginsDataForSeo API WrapperDuckDuckGo SearchFile System ToolsGolden QueryGoogle PlacesGoogle SearchGoogle Serper APIGradio ToolsGraphQL toolhuggingface_toolsHuman as a toolIFTTT WebHooksLemon AI NLP Workflow AutomationMetaphor SearchOpenWeatherMap APIPubMed ToolRequestsSceneXplainSearch ToolsSearxNG Search APISerpAPITwilioWikipediaWolfram AlphaYouTubeSearchToolZapier Natural Language Actions APIVector storesGrouped by providerIntegrationsToolsGraphQL toolGraphQL toolThis Jupyter Notebook demonstrates how to use the BaseGraphQLTool component with an Agent.GraphQL is a query language for APIs and a runtime for executing those queries against your data. GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.By including a BaseGraphQLTool in the list of tools provided to an Agent, you can grant your Agent the ability to query data from GraphQL APIs for any purposes you need.In this example, we'll be using the public Star Wars GraphQL API available at the following endpoint: https://swapi-graphql.netlify.app/.netlify/functions/index.First, you need to install httpx and gql Python packages.pip install httpx gql > /dev/nullNow, let's create a BaseGraphQLTool instance with the specified Star Wars API endpoint and initialize an Agent with the tool.from langchain import OpenAIfrom langchain.agents import load_tools, initialize_agent,
https://python.langchain.com/docs/integrations/tools/graphql
0d6d218fc918-2
the tool.from langchain import OpenAIfrom langchain.agents import load_tools, initialize_agent, AgentTypefrom langchain.utilities import GraphQLAPIWrapperllm = OpenAI(temperature=0)tools = load_tools( ["graphql"], graphql_endpoint="https://swapi-graphql.netlify.app/.netlify/functions/index",)agent = initialize_agent( tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)Now, we can use the Agent to run queries against the Star Wars GraphQL API. Let's ask the Agent to list all the Star Wars films and their release dates.graphql_fields = """allFilms { films { title director releaseDate speciesConnection { species { name classification homeworld { name } } } } }"""suffix = "Search for the titles of all the stawars films stored in the graphql database that has this schema "agent.run(suffix + graphql_fields) > Entering new AgentExecutor chain... I need to query the graphql database to get the titles of all the star wars films Action: query_graphql Action Input: query { allFilms { films { title } } } Observation: "{\n \"allFilms\": {\n \"films\": [\n {\n \"title\": \"A New
https://python.langchain.com/docs/integrations/tools/graphql
0d6d218fc918-3
{\n \"title\": \"A New Hope\"\n },\n {\n \"title\": \"The Empire Strikes Back\"\n },\n {\n \"title\": \"Return of the Jedi\"\n },\n {\n \"title\": \"The Phantom Menace\"\n },\n {\n \"title\": \"Attack of the Clones\"\n },\n {\n \"title\": \"Revenge of the Sith\"\n }\n ]\n }\n}" Thought: I now know the titles of all the star wars films Final Answer: The titles of all the star wars films are: A New Hope, The Empire Strikes Back, Return of the Jedi, The Phantom Menace, Attack of the Clones, and Revenge of the Sith. > Finished chain. 'The titles of all the star wars films are: A New Hope, The Empire Strikes Back, Return of the Jedi, The Phantom Menace, Attack of the Clones, and Revenge of the Sith.'PreviousGradio ToolsNexthuggingface_toolsCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/integrations/tools/graphql
8ede9b12b168-0
huggingface_tools | 🦜�🔗 Langchain
https://python.langchain.com/docs/integrations/tools/huggingface_tools
8ede9b12b168-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsToolsApifyArXiv API ToolawslambdaShell ToolBing SearchBrave SearchChatGPT PluginsDataForSeo API WrapperDuckDuckGo SearchFile System ToolsGolden QueryGoogle PlacesGoogle SearchGoogle Serper APIGradio ToolsGraphQL toolhuggingface_toolsHuman as a toolIFTTT WebHooksLemon AI NLP Workflow AutomationMetaphor SearchOpenWeatherMap APIPubMed ToolRequestsSceneXplainSearch ToolsSearxNG Search APISerpAPITwilioWikipediaWolfram AlphaYouTubeSearchToolZapier Natural Language Actions APIVector storesGrouped by providerIntegrationsToolshuggingface_toolsOn this pagehuggingface_toolsHuggingFace Tools​Huggingface Tools supporting text I/O can be
https://python.langchain.com/docs/integrations/tools/huggingface_tools
8ede9b12b168-2
loaded directly using the load_huggingface_tool function.# Requires transformers>=4.29.0 and huggingface_hub>=0.14.1pip install --upgrade transformers huggingface_hub > /dev/nullfrom langchain.agents import load_huggingface_tooltool = load_huggingface_tool("lysandre/hf-model-downloads")print(f"{tool.name}: {tool.description}") model_download_counter: This is a tool that returns the most downloaded model of a given task on the Hugging Face Hub. It takes the name of the category (such as text-classification, depth-estimation, etc), and returns the name of the checkpointtool.run("text-classification") 'facebook/bart-large-mnli'PreviousGraphQL toolNextHuman as a toolHuggingFace ToolsCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/integrations/tools/huggingface_tools
c16777cb82ce-0
Gradio Tools | 🦜�🔗 Langchain
https://python.langchain.com/docs/integrations/tools/gradio_tools
c16777cb82ce-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsToolsApifyArXiv API ToolawslambdaShell ToolBing SearchBrave SearchChatGPT PluginsDataForSeo API WrapperDuckDuckGo SearchFile System ToolsGolden QueryGoogle PlacesGoogle SearchGoogle Serper APIGradio ToolsGraphQL toolhuggingface_toolsHuman as a toolIFTTT WebHooksLemon AI NLP Workflow AutomationMetaphor SearchOpenWeatherMap APIPubMed ToolRequestsSceneXplainSearch ToolsSearxNG Search APISerpAPITwilioWikipediaWolfram AlphaYouTubeSearchToolZapier Natural Language Actions APIVector storesGrouped by providerIntegrationsToolsGradio ToolsOn this pageGradio ToolsThere are many 1000s of Gradio apps on Hugging Face Spaces. This library puts them at the tips of your LLM's fingers 🦾Specifically, gradio-tools is a Python library for converting Gradio apps into tools that can be leveraged by a large language model (LLM)-based agent to complete its task. For example, an LLM could use a Gradio tool to transcribe a voice recording it finds online and then summarize it for you. Or it could use a different Gradio tool to apply OCR to a document on your Google Drive and then answer questions about it.It's very easy to create you own tool if you want to use a space that's not one of the pre-built tools. Please see this section of the gradio-tools documentation for information on how to do that. All contributions are welcome!# !pip install gradio_toolsUsing a tool​from gradio_tools.tools import StableDiffusionToollocal_file_path =
https://python.langchain.com/docs/integrations/tools/gradio_tools
c16777cb82ce-2
a tool​from gradio_tools.tools import StableDiffusionToollocal_file_path = StableDiffusionTool().langchain.run( "Please create a photo of a dog riding a skateboard")local_file_path Loaded as API: https://gradio-client-demos-stable-diffusion.hf.space ✔ Job Status: Status.STARTING eta: None '/Users/harrisonchase/workplace/langchain/docs/modules/agents/tools/integrations/b61c1dd9-47e2-46f1-a47c-20d27640993d/tmp4ap48vnm.jpg'from PIL import Imageim = Image.open(local_file_path)display(im) ![png](_gradio_tools_files/output_7_0.png) Using within an agent​from langchain.agents import initialize_agentfrom langchain.llms import OpenAIfrom gradio_tools.tools import ( StableDiffusionTool, ImageCaptioningTool, StableDiffusionPromptGeneratorTool, TextToVideoTool,)from langchain.memory import ConversationBufferMemoryllm = OpenAI(temperature=0)memory = ConversationBufferMemory(memory_key="chat_history")tools = [ StableDiffusionTool().langchain, ImageCaptioningTool().langchain, StableDiffusionPromptGeneratorTool().langchain, TextToVideoTool().langchain,]agent = initialize_agent( tools, llm, memory=memory, agent="conversational-react-description", verbose=True)output = agent.run( input=( "Please create a photo of a dog riding a skateboard " "but improve my prompt prior to using an image generator."
https://python.langchain.com/docs/integrations/tools/gradio_tools
c16777cb82ce-3
"but improve my prompt prior to using an image generator." "Please caption the generated image and create a video for it using the improved prompt." )) Loaded as API: https://gradio-client-demos-stable-diffusion.hf.space ✔ Loaded as API: https://taesiri-blip-2.hf.space ✔ Loaded as API: https://microsoft-promptist.hf.space ✔ Loaded as API: https://damo-vilab-modelscope-text-to-video-synthesis.hf.space ✔ > Entering new AgentExecutor chain... Thought: Do I need to use a tool? Yes Action: StableDiffusionPromptGenerator Action Input: A dog riding a skateboard Job Status: Status.STARTING eta: None Observation: A dog riding a skateboard, digital painting, artstation, concept art, smooth, sharp focus, illustration, art by artgerm and greg rutkowski and alphonse mucha Thought: Do I need to use a tool? Yes Action: StableDiffusion Action Input: A dog riding a skateboard, digital painting, artstation, concept art, smooth, sharp focus, illustration, art by artgerm and greg rutkowski and alphonse mucha Job Status: Status.STARTING eta: None Job Status: Status.PROCESSING eta: None Observation:
https://python.langchain.com/docs/integrations/tools/gradio_tools
c16777cb82ce-4
Job Status: Status.PROCESSING eta: None Observation: /Users/harrisonchase/workplace/langchain/docs/modules/agents/tools/integrations/2e280ce4-4974-4420-8680-450825c31601/tmpfmiz2g1c.jpg Thought: Do I need to use a tool? Yes Action: ImageCaptioner Action Input: /Users/harrisonchase/workplace/langchain/docs/modules/agents/tools/integrations/2e280ce4-4974-4420-8680-450825c31601/tmpfmiz2g1c.jpg Job Status: Status.STARTING eta: None Observation: a painting of a dog sitting on a skateboard Thought: Do I need to use a tool? Yes Action: TextToVideo Action Input: a painting of a dog sitting on a skateboard Job Status: Status.STARTING eta: None Due to heavy traffic on this app, the prediction will take approximately 73 seconds.For faster predictions without waiting in queue, you may duplicate the space using: Client.duplicate(damo-vilab/modelscope-text-to-video-synthesis) Job Status: Status.IN_QUEUE eta: 73.89824726581574 Due to heavy traffic on this app, the prediction will take approximately 42 seconds.For faster predictions without waiting in queue, you may duplicate the space using: Client.duplicate(damo-vilab/modelscope-text-to-video-synthesis) Job Status: Status.IN_QUEUE eta: 42.49370198879602 Job Status: Status.IN_QUEUE eta: 21.314297944849187 Observation:
https://python.langchain.com/docs/integrations/tools/gradio_tools
c16777cb82ce-5
eta: 21.314297944849187 Observation: /var/folders/bm/ylzhm36n075cslb9fvvbgq640000gn/T/tmp5snj_nmzf20_cb3m.mp4 Thought: Do I need to use a tool? No AI: Here is a video of a painting of a dog sitting on a skateboard. > Finished chain.PreviousGoogle Serper APINextGraphQL toolUsing a toolUsing within an agentCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/integrations/tools/gradio_tools
6720695c84a6-0
DuckDuckGo Search | 🦜�🔗 Langchain
https://python.langchain.com/docs/integrations/tools/ddg
6720695c84a6-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsToolsApifyArXiv API ToolawslambdaShell ToolBing SearchBrave SearchChatGPT PluginsDataForSeo API WrapperDuckDuckGo SearchFile System ToolsGolden QueryGoogle PlacesGoogle SearchGoogle Serper APIGradio ToolsGraphQL toolhuggingface_toolsHuman as a toolIFTTT WebHooksLemon AI NLP Workflow AutomationMetaphor SearchOpenWeatherMap APIPubMed ToolRequestsSceneXplainSearch ToolsSearxNG Search APISerpAPITwilioWikipediaWolfram AlphaYouTubeSearchToolZapier Natural Language Actions APIVector storesGrouped by providerIntegrationsToolsDuckDuckGo SearchDuckDuckGo SearchThis notebook goes over how to use the duck-duck-go search component.# !pip install duckduckgo-searchfrom langchain.tools import DuckDuckGoSearchRunsearch = DuckDuckGoSearchRun()search.run("Obama's first name?") 'Barack Obama, in full Barack Hussein Obama II, (born August 4, 1961, Honolulu, Hawaii, U.S.), 44th president of the United States (2009-17) and the first African American to hold the office. Before winning the presidency, Obama represented Illinois in the U.S. Senate (2005-08). Barack Hussein Obama II (/ b ə ˈ r ɑ� k h u� ˈ s eɪ n oʊ ˈ b ɑ� m ə / bə-RAHK hoo-SAYN oh-BAH-mə; born August 4,
https://python.langchain.com/docs/integrations/tools/ddg
6720695c84a6-2
hoo-SAYN oh-BAH-mə; born August 4, 1961) is an American former politician who served as the 44th president of the United States from 2009 to 2017. A member of the Democratic Party, he was the first African-American president of the United States. Obama previously served as a U.S. senator representing ... Barack Obama was the first African American president of the United States (2009-17). He oversaw the recovery of the U.S. economy (from the Great Recession of 2008-09) and the enactment of landmark health care reform (the Patient Protection and Affordable Care Act ). In 2009 he was awarded the Nobel Peace Prize. His birth certificate lists his first name as Barack: That\'s how Obama has spelled his name throughout his life. His name derives from a Hebrew name which means "lightning.". The Hebrew word has been transliterated into English in various spellings, including Barak, Buraq, Burack, and Barack. Most common names of U.S. presidents 1789-2021. Published by. Aaron O\'Neill , Jun 21, 2022. The most common first name for a U.S. president is James, followed by John and then William. Six U.S ...'PreviousDataForSeo API WrapperNextFile System ToolsCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/integrations/tools/ddg
68471e0b586d-0
File System Tools | 🦜�🔗 Langchain
https://python.langchain.com/docs/integrations/tools/filesystem
68471e0b586d-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsToolsApifyArXiv API ToolawslambdaShell ToolBing SearchBrave SearchChatGPT PluginsDataForSeo API WrapperDuckDuckGo SearchFile System ToolsGolden QueryGoogle PlacesGoogle SearchGoogle Serper APIGradio ToolsGraphQL toolhuggingface_toolsHuman as a toolIFTTT WebHooksLemon AI NLP Workflow AutomationMetaphor SearchOpenWeatherMap APIPubMed ToolRequestsSceneXplainSearch ToolsSearxNG Search APISerpAPITwilioWikipediaWolfram AlphaYouTubeSearchToolZapier Natural Language Actions APIVector storesGrouped by providerIntegrationsToolsFile System ToolsOn this pageFile System ToolsLangChain provides tools for interacting with a local file system out of the box. This notebook walks through some of them.Note: these tools are not recommended for use outside a sandboxed environment! First, we'll import the tools.from langchain.tools.file_management import ( ReadFileTool, CopyFileTool, DeleteFileTool, MoveFileTool, WriteFileTool, ListDirectoryTool,)from langchain.agents.agent_toolkits import FileManagementToolkitfrom tempfile import TemporaryDirectory# We'll make a temporary directory to avoid clutterworking_directory = TemporaryDirectory()The FileManagementToolkit​If you want to provide all the file tooling to your agent, it's easy to do so with the toolkit. We'll pass the temporary directory in as a root directory as a workspace for the LLM.It's recommended to always pass in a root directory, since without one, it's easy for the LLM to pollute the working directory, and without one, there isn't any validation against
https://python.langchain.com/docs/integrations/tools/filesystem
68471e0b586d-2
straightforward prompt injection.toolkit = FileManagementToolkit( root_dir=str(working_directory.name)) # If you don't provide a root_dir, operations will default to the current working directorytoolkit.get_tools() [CopyFileTool(name='copy_file', description='Create a copy of a file in a specified location', args_schema=<class 'langchain.tools.file_management.copy.FileCopyInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug'), DeleteFileTool(name='file_delete', description='Delete a file', args_schema=<class 'langchain.tools.file_management.delete.FileDeleteInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug'), FileSearchTool(name='file_search', description='Recursively search for files in a subdirectory that match the regex pattern', args_schema=<class 'langchain.tools.file_management.file_search.FileSearchInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug'), MoveFileTool(name='move_file', description='Move or rename a file from one location to another', args_schema=<class
https://python.langchain.com/docs/integrations/tools/filesystem
68471e0b586d-3
description='Move or rename a file from one location to another', args_schema=<class 'langchain.tools.file_management.move.FileMoveInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug'), ReadFileTool(name='read_file', description='Read file from disk', args_schema=<class 'langchain.tools.file_management.read.ReadFileInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug'), WriteFileTool(name='write_file', description='Write file to disk', args_schema=<class 'langchain.tools.file_management.write.WriteFileInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug'), ListDirectoryTool(name='list_directory', description='List files and directories in a specified folder', args_schema=<class 'langchain.tools.file_management.list_dir.DirectoryListingInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug')]Selecting
https://python.langchain.com/docs/integrations/tools/filesystem
68471e0b586d-4
File System Tools​If you only want to select certain tools, you can pass them in as arguments when initializing the toolkit, or you can individually initialize the desired tools.tools = FileManagementToolkit( root_dir=str(working_directory.name), selected_tools=["read_file", "write_file", "list_directory"],).get_tools()tools [ReadFileTool(name='read_file', description='Read file from disk', args_schema=<class 'langchain.tools.file_management.read.ReadFileInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug'), WriteFileTool(name='write_file', description='Write file to disk', args_schema=<class 'langchain.tools.file_management.write.WriteFileInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug'), ListDirectoryTool(name='list_directory', description='List files and directories in a specified folder', args_schema=<class 'langchain.tools.file_management.list_dir.DirectoryListingInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug')]read_tool, write_tool, list_tool = toolswrite_tool.run({"file_path":
https://python.langchain.com/docs/integrations/tools/filesystem
68471e0b586d-5
write_tool, list_tool = toolswrite_tool.run({"file_path": "example.txt", "text": "Hello World!"}) 'File written successfully to example.txt.'# List files in the working directorylist_tool.run({}) 'example.txt'PreviousDuckDuckGo SearchNextGolden QueryThe FileManagementToolkitSelecting File System ToolsCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/integrations/tools/filesystem
4cb173dbed63-0
Google Serper API | 🦜�🔗 Langchain
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsToolsApifyArXiv API ToolawslambdaShell ToolBing SearchBrave SearchChatGPT PluginsDataForSeo API WrapperDuckDuckGo SearchFile System ToolsGolden QueryGoogle PlacesGoogle SearchGoogle Serper APIGradio ToolsGraphQL toolhuggingface_toolsHuman as a toolIFTTT WebHooksLemon AI NLP Workflow AutomationMetaphor SearchOpenWeatherMap APIPubMed ToolRequestsSceneXplainSearch ToolsSearxNG Search APISerpAPITwilioWikipediaWolfram AlphaYouTubeSearchToolZapier Natural Language Actions APIVector storesGrouped by providerIntegrationsToolsGoogle Serper APIOn this pageGoogle Serper APIThis notebook goes over how to use the Google Serper component to search the web. First you need to sign up for a free account at serper.dev and get your api key.import osimport pprintos.environ["SERPER_API_KEY"] = ""from langchain.utilities import GoogleSerperAPIWrappersearch = GoogleSerperAPIWrapper()search.run("Obama's first name?") 'Barack Hussein Obama II'As part of a Self Ask With Search Chain​os.environ["OPENAI_API_KEY"] = ""from langchain.utilities import GoogleSerperAPIWrapperfrom langchain.llms.openai import OpenAIfrom langchain.agents import initialize_agent, Toolfrom langchain.agents import AgentTypellm = OpenAI(temperature=0)search = GoogleSerperAPIWrapper()tools = [ Tool( name="Intermediate Answer", func=search.run,
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-2
Answer", func=search.run, description="useful for when you need to ask with search", )]self_ask_with_search = initialize_agent( tools, llm, agent=AgentType.SELF_ASK_WITH_SEARCH, verbose=True)self_ask_with_search.run( "What is the hometown of the reigning men's U.S. Open champion?") > Entering new AgentExecutor chain... Yes. Follow up: Who is the reigning men's U.S. Open champion? Intermediate answer: Current champions Carlos Alcaraz, 2022 men's singles champion. Follow up: Where is Carlos Alcaraz from? Intermediate answer: El Palmar, Spain So the final answer is: El Palmar, Spain > Finished chain. 'El Palmar, Spain'Obtaining results with metadata​If you would also like to obtain the results in a structured way including metadata. For this we will be using the results method of the wrapper.search = GoogleSerperAPIWrapper()results = search.results("Apple Inc.")pprint.pp(results) {'searchParameters': {'q': 'Apple Inc.', 'gl': 'us', 'hl': 'en', 'num': 10,
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-3
10, 'type': 'search'}, 'knowledgeGraph': {'title': 'Apple', 'type': 'Technology company', 'website': 'http://www.apple.com/', 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQwGQRv5TjjkycpctY66mOg_e2-npacrmjAb6_jAWhzlzkFE3OTjxyzbA&s=0', 'description': 'Apple Inc. is an American multinational ' 'technology company headquartered in ' 'Cupertino, California. Apple is the ' "world's largest technology company by "
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-4
'revenue, with US$394.3 billion in 2022 ' 'revenue. As of March 2023, Apple is the ' "world's biggest...", 'descriptionSource': 'Wikipedia', 'descriptionLink': 'https://en.wikipedia.org/wiki/Apple_Inc.', 'attributes': {'Customer service': '1 (800) 275-2273', 'CEO': 'Tim Cook (Aug 24, 2011–)', 'Headquarters': 'Cupertino, CA', 'Founded': 'April 1,
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-5
'Founded': 'April 1, 1976, Los Altos, CA', 'Founders': 'Steve Jobs, Steve Wozniak, ' 'Ronald Wayne, and more', 'Products': 'iPhone, iPad, Apple TV, and ' 'more'}}, 'organic': [{'title': 'Apple', 'link': 'https://www.apple.com/', 'snippet': 'Discover the innovative world of Apple and shop ' 'everything iPhone, iPad, Apple Watch, Mac, and Apple ' 'TV, plus explore accessories, entertainment, ...',
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-6
'TV, plus explore accessories, entertainment, ...', 'sitelinks': [{'title': 'Support', 'link': 'https://support.apple.com/'}, {'title': 'iPhone', 'link': 'https://www.apple.com/iphone/'}, {'title': 'Site Map', 'link': 'https://www.apple.com/sitemap/'}, {'title': 'Business', 'link': 'https://www.apple.com/business/'}, {'title': 'Mac',
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-7
'link': 'https://www.apple.com/mac/'}, {'title': 'Watch', 'link': 'https://www.apple.com/watch/'}], 'position': 1}, {'title': 'Apple Inc. - Wikipedia', 'link': 'https://en.wikipedia.org/wiki/Apple_Inc.', 'snippet': 'Apple Inc. is an American multinational technology ' 'company headquartered in Cupertino, California. ' "Apple is the world's largest technology company by " 'revenue, ...', 'attributes': {'Products': 'AirPods; Apple Watch; iPad; iPhone; '
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-8
'Mac; Full list', 'Founders': 'Steve Jobs; Steve Wozniak; Ronald ' 'Wayne; Mike Markkula'}, 'sitelinks': [{'title': 'History', 'link': 'https://en.wikipedia.org/wiki/History_of_Apple_Inc.'}, {'title': 'Timeline of Apple Inc. products', 'link': 'https://en.wikipedia.org/wiki/Timeline_of_Apple_Inc._products'}, {'title': 'Litigation involving Apple Inc.', 'link':
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-9
'link': 'https://en.wikipedia.org/wiki/Litigation_involving_Apple_Inc.'}, {'title': 'Apple Store', 'link': 'https://en.wikipedia.org/wiki/Apple_Store'}], 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRvmB5fT1LjqpZx02UM7IJq0Buoqt0DZs_y0dqwxwSWyP4PIN9FaxuTea0&s', 'position': 2}, {'title': 'Apple Inc. | History, Products, Headquarters, & Facts ' '| Britannica', 'link': 'https://www.britannica.com/topic/Apple-Inc', 'snippet': 'Apple Inc., formerly Apple Computer, Inc., American ' 'manufacturer of personal computers, smartphones, '
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-10
'manufacturer of personal computers, smartphones, ' 'tablet computers, computer peripherals, and computer ' '...', 'attributes': {'Related People': 'Steve Jobs Steve Wozniak Jony ' 'Ive Tim Cook Angela Ahrendts', 'Date': '1976 - present'}, 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS3liELlhrMz3Wpsox29U8jJ3L8qETR0hBWHXbFnwjwQc34zwZvFELst2E&s', 'position': 3}, {'title': 'AAPL: Apple Inc Stock Price Quote - NASDAQ GS - ' 'Bloomberg.com',
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-11
'Bloomberg.com', 'link': 'https://www.bloomberg.com/quote/AAPL:US', 'snippet': 'AAPL:USNASDAQ GS. Apple Inc. COMPANY INFO ; Open. ' '170.09 ; Prev Close. 169.59 ; Volume. 48,425,696 ; ' 'Market Cap. 2.667T ; Day Range. 167.54170.35.', 'position': 4}, {'title': 'Apple Inc. (AAPL) Company Profile & Facts - Yahoo ' 'Finance', 'link': 'https://finance.yahoo.com/quote/AAPL/profile/', 'snippet': 'Apple Inc. designs, manufactures, and markets ' 'smartphones, personal computers, tablets, wearables, '
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-12
'and accessories worldwide. The company offers ' 'iPhone, a line ...', 'position': 5}, {'title': 'Apple Inc. (AAPL) Stock Price, News, Quote & History - ' 'Yahoo Finance', 'link': 'https://finance.yahoo.com/quote/AAPL', 'snippet': 'Find the latest Apple Inc. (AAPL) stock quote, ' 'history, news and other vital information to help ' 'you with your stock trading and investing.', 'position': 6}], 'peopleAlsoAsk': [{'question': 'What does Apple Inc do?', 'snippet': 'Apple Inc. (Apple) designs, manufactures and '
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-13
' 'markets smartphones, personal\n' 'computers, tablets, wearables and accessories ' 'and sells a range of related\n' 'services.', 'title': 'AAPL.O - | Stock Price & Latest News - Reuters', 'link': 'https://www.reuters.com/markets/companies/AAPL.O/'}, {'question': 'What is the full form of Apple Inc?', 'snippet': '(formerly Apple Computer Inc.) is an American ' 'computer and consumer electronics\n' 'company famous for
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-14
'company famous for creating the iPhone, iPad ' 'and Macintosh computers.', 'title': 'What is Apple? An products and history overview ' '- TechTarget', 'link': 'https://www.techtarget.com/whatis/definition/Apple'}, {'question': 'What is Apple Inc iPhone?', 'snippet': 'Apple Inc (Apple) designs, manufactures, and ' 'markets smartphones, tablets,\n' 'personal computers, and wearable devices. The ' 'company also offers software\n'
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-15
'applications and related services, ' 'accessories, and third-party digital content.\n' "Apple's product portfolio includes iPhone, " 'iPad, Mac, iPod, Apple Watch, and\n' 'Apple TV.', 'title': 'Apple Inc Company Profile - Apple Inc Overview - ' 'GlobalData', 'link': 'https://www.globaldata.com/company-profile/apple-inc/'}, {'question': 'Who runs Apple Inc?', 'snippet': 'Timothy Donald Cook (born November 1, 1960) is '
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-16
'Timothy Donald Cook (born November 1, 1960) is ' 'an American business executive\n' 'who has been the chief executive officer of ' 'Apple Inc. since 2011. Cook\n' "previously served as the company's chief " 'operating officer under its co-founder\n' 'Steve Jobs. He is the first CEO of any Fortune ' '500 company who is openly gay.', 'title': 'Tim Cook - Wikipedia', 'link': 'https://en.wikipedia.org/wiki/Tim_Cook'}],
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-17
'link': 'https://en.wikipedia.org/wiki/Tim_Cook'}], 'relatedSearches': [{'query': 'Who invented the iPhone'}, {'query': 'Apple iPhone'}, {'query': 'History of Apple company PDF'}, {'query': 'Apple company history'}, {'query': 'Apple company introduction'}, {'query': 'Apple India'}, {'query': 'What does Apple Inc own'}, {'query': 'Apple Inc After Steve'}, {'query': 'Apple Watch'}, {'query': 'Apple App Store'}]}Searching for Google Images​We can also query Google Images using this wrapper. For example:search = GoogleSerperAPIWrapper(type="images")results = search.results("Lion")pprint.pp(results) {'searchParameters': {'q': 'Lion',
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-18
'Lion', 'gl': 'us', 'hl': 'en', 'num': 10, 'type': 'images'}, 'images': [{'title': 'Lion - Wikipedia', 'imageUrl': 'https://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Lion_waiting_in_Namibia.jpg/1200px-Lion_waiting_in_Namibia.jpg', 'imageWidth': 1200, 'imageHeight': 900, 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRye79ROKwjfb6017jr0iu8Bz2E1KKuHg-A4qINJaspyxkZrkw&amp;s', 'thumbnailWidth': 259, 'thumbnailHeight': 194, 'source': 'Wikipedia',
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-19
'source': 'Wikipedia', 'domain': 'en.wikipedia.org', 'link': 'https://en.wikipedia.org/wiki/Lion', 'position': 1}, {'title': 'Lion | Characteristics, Habitat, & Facts | Britannica', 'imageUrl': 'https://cdn.britannica.com/55/2155-050-604F5A4A/lion.jpg', 'imageWidth': 754, 'imageHeight': 752, 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS3fnDub1GSojI0hJ-ZGS8Tv-hkNNloXh98DOwXZoZ_nUs3GWSd&amp;s', 'thumbnailWidth': 225, 'thumbnailHeight': 224, 'source': 'Encyclopedia Britannica', 'domain': 'www.britannica.com',
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-20
'link': 'https://www.britannica.com/animal/lion', 'position': 2}, {'title': 'African lion, facts and photos', 'imageUrl': 'https://i.natgeofe.com/n/487a0d69-8202-406f-a6a0-939ed3704693/african-lion.JPG', 'imageWidth': 3072, 'imageHeight': 2043, 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTPlTarrtDbyTiEm-VI_PML9VtOTVPuDXJ5ybDf_lN11H2mShk&amp;s', 'thumbnailWidth': 275, 'thumbnailHeight': 183, 'source': 'National Geographic', 'domain': 'www.nationalgeographic.com', 'link': 'https://www.nationalgeographic.com/animals/mammals/facts/african-lion',
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-21
'position': 3}, {'title': 'Saint Louis Zoo | African Lion', 'imageUrl': 'https://optimise2.assets-servd.host/maniacal-finch/production/animals/african-lion-01-01.jpg?w=1200&auto=compress%2Cformat&fit=crop&dm=1658933674&s=4b63f926a0f524f2087a8e0613282bdb', 'imageWidth': 1200, 'imageHeight': 1200, 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTlewcJ5SwC7yKup6ByaOjTnAFDeoOiMxyJTQaph2W_I3dnks4&amp;s', 'thumbnailWidth': 225, 'thumbnailHeight': 225, 'source': 'St. Louis Zoo', 'domain': 'stlzoo.org', 'link': 'https://stlzoo.org/animals/mammals/carnivores/lion',
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-22
'https://stlzoo.org/animals/mammals/carnivores/lion', 'position': 4}, {'title': 'How to Draw a Realistic Lion like an Artist - Studio ' 'Wildlife', 'imageUrl': 'https://studiowildlife.com/wp-content/uploads/2021/10/245528858_183911853822648_6669060845725210519_n.jpg', 'imageWidth': 1431, 'imageHeight': 2048, 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTmn5HayVj3wqoBDQacnUtzaDPZzYHSLKUlIEcni6VB8w0mVeA&amp;s', 'thumbnailWidth': 188, 'thumbnailHeight': 269, 'source': 'Studio Wildlife', 'domain': 'studiowildlife.com', 'link':
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-23
'link': 'https://studiowildlife.com/how-to-draw-a-realistic-lion-like-an-artist/', 'position': 5}, {'title': 'Lion | Characteristics, Habitat, & Facts | Britannica', 'imageUrl': 'https://cdn.britannica.com/29/150929-050-547070A1/lion-Kenya-Masai-Mara-National-Reserve.jpg', 'imageWidth': 1600, 'imageHeight': 1085, 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSCqaKY_THr0IBZN8c-2VApnnbuvKmnsWjfrwKoWHFR9w3eN5o&amp;s', 'thumbnailWidth': 273, 'thumbnailHeight': 185, 'source': 'Encyclopedia Britannica', 'domain': 'www.britannica.com', 'link':
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-24
'link': 'https://www.britannica.com/animal/lion', 'position': 6}, {'title': "Where do lions live? Facts about lions' habitats and " 'other cool facts', 'imageUrl': 'https://www.gannett-cdn.com/-mm-/b2b05a4ab25f4fca0316459e1c7404c537a89702/c=0-0-1365-768/local/-/media/2022/03/16/USATODAY/usatsports/imageForEntry5-ODq.jpg?width=1365&height=768&fit=crop&format=pjpg&auto=webp', 'imageWidth': 1365, 'imageHeight': 768, 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTc_4vCHscgvFvYy3PSrtIOE81kNLAfhDK8F3mfOuotL0kUkbs&amp;s', 'thumbnailWidth': 299,
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-25
299, 'thumbnailHeight': 168, 'source': 'USA Today', 'domain': 'www.usatoday.com', 'link': 'https://www.usatoday.com/story/news/2023/01/08/where-do-lions-live-habitat/10927718002/', 'position': 7}, {'title': 'Lion', 'imageUrl': 'https://i.natgeofe.com/k/1d33938b-3d02-4773-91e3-70b113c3b8c7/lion-male-roar_square.jpg', 'imageWidth': 3072, 'imageHeight': 3072, 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQqLfnBrBLcTiyTZynHH3FGbBtX2bd1ScwpcuOLnksTyS9-4GM&amp;s', 'thumbnailWidth': 225,
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-26
225, 'thumbnailHeight': 225, 'source': 'National Geographic Kids', 'domain': 'kids.nationalgeographic.com', 'link': 'https://kids.nationalgeographic.com/animals/mammals/facts/lion', 'position': 8}, {'title': "Lion | Smithsonian's National Zoo", 'imageUrl': 'https://nationalzoo.si.edu/sites/default/files/styles/1400_scale/public/animals/exhibit/africanlion-005.jpg?itok=6wA745g_', 'imageWidth': 1400, 'imageHeight': 845, 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSgB3z_D4dMEOWJ7lajJk4XaQSL4DdUvIRj4UXZ0YoE5fGuWuo&amp;s', 'thumbnailWidth': 289, 'thumbnailHeight': 174,
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-27
'thumbnailHeight': 174, 'source': "Smithsonian's National Zoo", 'domain': 'nationalzoo.si.edu', 'link': 'https://nationalzoo.si.edu/animals/lion', 'position': 9}, {'title': "Zoo's New Male Lion Explores Habitat for the First Time " '- Virginia Zoo', 'imageUrl': 'https://virginiazoo.org/wp-content/uploads/2022/04/ZOO_0056-scaled.jpg', 'imageWidth': 2560, 'imageHeight': 2141, 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTDCG7XvXRCwpe_-Vy5mpvrQpVl5q2qwgnDklQhrJpQzObQGz4&amp;s', 'thumbnailWidth': 246, 'thumbnailHeight': 205,
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-28
'thumbnailHeight': 205, 'source': 'Virginia Zoo', 'domain': 'virginiazoo.org', 'link': 'https://virginiazoo.org/zoos-new-male-lion-explores-habitat-for-thefirst-time/', 'position': 10}]}Searching for Google News​We can also query Google News using this wrapper. For example:search = GoogleSerperAPIWrapper(type="news")results = search.results("Tesla Inc.")pprint.pp(results) {'searchParameters': {'q': 'Tesla Inc.', 'gl': 'us', 'hl': 'en', 'num': 10, 'type': 'news'}, 'news': [{'title': 'ISS recommends Tesla investors vote against re-election ' 'of Robyn Denholm', 'link':
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-29
Denholm', 'link': 'https://www.reuters.com/business/autos-transportation/iss-recommends-tesla-investors-vote-against-re-election-robyn-denholm-2023-05-04/', 'snippet': 'Proxy advisory firm ISS on Wednesday recommended Tesla ' 'investors vote against re-election of board chair Robyn ' 'Denholm, citing "concerns on...', 'date': '5 mins ago', 'source': 'Reuters', 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcROdETe_GUyp1e8RHNhaRM8Z_vfxCvdfinZwzL1bT1ZGSYaGTeOojIdBoLevA&s', 'position': 1}, {'title': 'Global companies by market cap: Tesla fell most in April', 'link': 'https://www.reuters.com/markets/global-companies-by-market-cap-tesla-fell-most-april-2023-05-02/', 'snippet': 'Tesla
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-30
'snippet': 'Tesla Inc was the biggest loser among top companies by ' 'market capitalisation in April, hit by disappointing ' 'quarterly earnings after it...', 'date': '1 day ago', 'source': 'Reuters', 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ4u4CP8aOdGyRFH6o4PkXi-_eZDeY96vLSag5gDjhKMYf98YBER2cZPbkStQ&s', 'position': 2}, {'title': 'Tesla Wanted an EV Price War. Ford Showed Up.', 'link': 'https://www.bloomberg.com/opinion/articles/2023-05-03/tesla-wanted-an-ev-price-war-ford-showed-up', 'snippet': 'The legacy automaker is paring back the cost of its ' 'Mustang Mach-E model after Tesla discounted its '
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-31
after Tesla discounted its ' 'competing EVs, portending tighter...', 'date': '6 hours ago', 'source': 'Bloomberg.com', 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS_3Eo4VI0H-nTeIbYc5DaQn5ep7YrWnmhx6pv8XddFgNF5zRC9gEpHfDq8yQ&s', 'position': 3}, {'title': 'Joby Aviation to get investment from Tesla shareholder ' 'Baillie Gifford', 'link': 'https://finance.yahoo.com/news/joby-aviation-investment-tesla-shareholder-204450712.html', 'snippet': 'This comes days after Joby clinched a $55 million ' 'contract extension to deliver up to nine air taxis to ' 'the U.S. Air Force,...',
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-32
'the U.S. Air Force,...', 'date': '4 hours ago', 'source': 'Yahoo Finance', 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQO0uVn297LI-xryrPNqJ-apUOulj4ohM-xkN4OfmvMOYh1CPdUEBbYx6hviw&s', 'position': 4}, {'title': 'Tesla resumes U.S. orders for a Model 3 version at lower ' 'price, range', 'link': 'https://finance.yahoo.com/news/tesla-resumes-us-orders-model-045736115.html', 'snippet': '(Reuters) -Tesla Inc has resumed taking orders for its ' 'Model 3 long-range vehicle in the United States, the ' "company's website showed late on...", 'date': '19 hours ago', 'source': 'Yahoo Finance',
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-33
'source': 'Yahoo Finance', 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTIZetJ62sQefPfbQ9KKDt6iH7Mc0ylT5t_hpgeeuUkHhJuAx2FOJ4ZTRVDFg&s', 'position': 5}, {'title': 'The Tesla Model 3 Long Range AWD Is Now Available in the ' 'U.S. With 325 Miles of Range', 'link': 'https://www.notateslaapp.com/news/1393/tesla-reopens-orders-for-model-3-long-range-after-months-of-unavailability', 'snippet': 'Tesla has reopened orders for the Model 3 Long Range ' 'RWD, which has been unavailable for months due to high ' 'demand.', 'date': '7 hours ago', 'source': 'Not a Tesla App', 'imageUrl':
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-34
Tesla App', 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSecrgxZpRj18xIJY-nDHljyP-A4ejEkswa9eq77qhMNrScnVIqe34uql5U4w&s', 'position': 6}, {'title': 'Tesla Cybertruck alpha prototype spotted at the Fremont ' 'factory in new pics and videos', 'link': 'https://www.teslaoracle.com/2023/05/03/tesla-cybertruck-alpha-prototype-interior-and-exterior-spotted-at-the-fremont-factory-in-new-pics-and-videos/', 'snippet': 'A Tesla Cybertruck alpha prototype goes to Fremont, ' 'California for another round of testing before going to ' 'production later this year (pics...', 'date': '14 hours ago', 'source': 'Tesla Oracle', 'imageUrl':
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-35
Oracle', 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRO7M5ZLQE-Zo4-_5dv9hNAQZ3wSqfvYCuKqzxHG-M6CgLpwPMMG_ssebdcMg&s', 'position': 7}, {'title': 'Tesla putting facility in new part of country - Austin ' 'Business Journal', 'link': 'https://www.bizjournals.com/austin/news/2023/05/02/tesla-leases-building-seattle-area.html', 'snippet': 'Check out what Puget Sound Business Journal has to ' "report about the Austin-based company's real estate " 'footprint in the Pacific Northwest.', 'date': '22 hours ago', 'source': 'The Business Journals', 'imageUrl':
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-36
Journals', 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR9kIEHWz1FcHKDUtGQBS0AjmkqtyuBkQvD8kyIY3kpaPrgYaN7I_H2zoOJsA&s', 'position': 8}, {'title': 'Tesla (TSLA) Resumes Orders for Model 3 Long Range After ' 'Backlog', 'link': 'https://www.bloomberg.com/news/articles/2023-05-03/tesla-resumes-orders-for-popular-model-3-long-range-at-47-240', 'snippet': 'Tesla Inc. has resumed taking orders for its Model 3 ' 'Long Range edition with a starting price of $47240, ' 'according to its website.', 'date': '5 hours ago', 'source': 'Bloomberg.com', 'imageUrl':
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-37
'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTWWIC4VpMTfRvSyqiomODOoLg0xhoBf-Tc1qweKnSuaiTk-Y1wMJZM3jct0w&s', 'position': 9}]}If you want to only receive news articles published in the last hour, you can do the following:search = GoogleSerperAPIWrapper(type="news", tbs="qdr:h")results = search.results("Tesla Inc.")pprint.pp(results) {'searchParameters': {'q': 'Tesla Inc.', 'gl': 'us', 'hl': 'en', 'num': 10, 'type': 'news', 'tbs': 'qdr:h'}, 'news': [{'title': 'Oklahoma Gov. Stitt sees growing foreign interest in ' 'investments in ...', 'link':
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-38
in ...', 'link': 'https://www.reuters.com/world/us/oklahoma-gov-stitt-sees-growing-foreign-interest-investments-state-2023-05-04/', 'snippet': 'T)), a battery supplier to electric vehicle maker Tesla ' 'Inc (TSLA.O), said on Sunday it is considering building ' 'a battery plant in Oklahoma, its third in...', 'date': '53 mins ago', 'source': 'Reuters', 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSSTcsXeenqmEKdiekvUgAmqIPR4nlAmgjTkBqLpza-lLfjX1CwB84MoNVj0Q&s', 'position': 1}, {'title': 'Ryder lanza solución llave en mano para vehículos ' 'eléctricos en EU', 'link':
https://python.langchain.com/docs/integrations/tools/google_serper
4cb173dbed63-39
en EU', 'link': 'https://www.tyt.com.mx/nota/ryder-lanza-solucion-llave-en-mano-para-vehiculos-electricos-en-eu', 'snippet': 'Ryder System Inc. presentó RyderElectric+ TM como su ' 'nueva solución llave en mano ... Ryder también tiene ' 'reservados los semirremolques Tesla y continúa...', 'date': '56 mins ago', 'source': 'Revista Transportes y Turismo', 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQJhXTQQtjSUZf9YPM235WQhFU5_d7lEA76zB8DGwZfixcgf1_dhPJyKA1Nbw&s', 'position': 2}, {'title': '"I think people can get by with $999 million," Bernie ' 'Sanders tells American Billionaires.',
https://python.langchain.com/docs/integrations/tools/google_serper