id
stringlengths
14
16
text
stringlengths
36
2.73k
source
stringlengths
49
117
27d56fbe3a6f-4
Action: Search Action Input: National Anthem of Canada Observation: Jun 7, 2010 ... https://twitter.com/CanadaImmigrantCanadian National Anthem O Canada in HQ - complete with lyrics, captions, vocals & music.LYRICS:O Canada! Nov 23, 2022 ... After 100 years of tradition, O Canada was proclaimed Canada's national anthem...
https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html
27d56fbe3a6f-5
Thought: I now know the final answer. Final Answer: The national anthem of Canada is called "O Canada". > Finished AgentExecutor chain. 'The national anthem of Canada is called "O Canada".' We can see that the agent remembered that the previous question was about Canada, and properly asked Google Search what the name o...
https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html
27d56fbe3a6f-6
Action: Search Action Input: Population of Canada Observation: The current population of Canada is 38,566,192 as of Saturday, December 31, 2022, based on Worldometer elaboration of the latest United Nations data. · Canada ... Additional information related to Canadian population trends can be found on Statistics Canada...
https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html
27d56fbe3a6f-7
> Finished AgentExecutor chain. 'The current population of Canada is 38,566,192 as of Saturday, December 31, 2022, based on Worldometer elaboration of the latest United Nations data.' agent_without_memory.run("what is their national anthem called?") > Entering new AgentExecutor chain... Thought: I should look up the an...
https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html
27d56fbe3a6f-8
Action: Search Action Input: national anthem of [country] Observation: Most nation states have an anthem, defined as "a song, as of praise, devotion, or patriotism"; most anthems are either marches or hymns in style. List of all countries around the world with its national anthem. ... Title and lyrics in the language o...
https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html
27d56fbe3a6f-9
Thought: I now know the final answer Final Answer: The national anthem of [country] is [name of anthem]. > Finished AgentExecutor chain. 'The national anthem of [country] is [name of anthem].' previous How to add Memory to an Agent next Cassandra Chat Message History By Harrison Chase © Copyright 2023, Harri...
https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html
c35c9d38b4a7-0
.ipynb .pdf How to customize conversational memory Contents AI Prefix Human Prefix How to customize conversational memory# This notebook walks through a few ways to customize conversational memory. from langchain.llms import OpenAI from langchain.chains import ConversationChain from langchain.memory import Conversati...
https://python.langchain.com/en/latest/modules/memory/examples/conversational_customization.html
c35c9d38b4a7-1
Current conversation: Human: Hi there! AI: Hi there! It's nice to meet you. How can I help you today? Human: What's the weather? AI: > Finished ConversationChain chain. ' The current weather is sunny and warm with a temperature of 75 degrees Fahrenheit. The forecast for the next few days is sunny with temperatures in ...
https://python.langchain.com/en/latest/modules/memory/examples/conversational_customization.html
c35c9d38b4a7-2
> Entering new ConversationChain chain... Prompt after formatting: The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know. Current conversation: ...
https://python.langchain.com/en/latest/modules/memory/examples/conversational_customization.html
c35c9d38b4a7-3
verbose=True, memory=ConversationBufferMemory(human_prefix="Friend") ) conversation.predict(input="Hi there!") > Entering new ConversationChain chain... Prompt after formatting: The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its co...
https://python.langchain.com/en/latest/modules/memory/examples/conversational_customization.html
568b0e1b00f6-0
.ipynb .pdf Callbacks Contents Callbacks How to use callbacks When do you want to use each of these? Using an existing handler Creating a custom handler Async Callbacks Using multiple handlers, passing in handlers Tracing and Token Counting Tracing Token Counting Callbacks# LangChain provides a callbacks system that ...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
568b0e1b00f6-1
CallbackHandlers are objects that implement the CallbackHandler interface, which has a method for each event that can be subscribed to. The CallbackManager will call the appropriate method on each handler when the event is triggered. class BaseCallbackHandler: """Base callback handler that can be used to handle cal...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
568b0e1b00f6-2
def on_tool_end(self, output: str, **kwargs: Any) -> Any: """Run when tool ends running.""" def on_tool_error( self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any ) -> Any: """Run when tool errors.""" def on_text(self, text: str, **kwargs: Any) -> Any: """Run on a...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
568b0e1b00f6-3
The verbose argument is available on most objects throughout the API (Chains, Models, Tools, Agents, etc.) as a constructor argument, eg. LLMChain(verbose=True), and it is equivalent to passing a ConsoleCallbackHandler to the callbacks argument of that object and all child objects. This is useful for debugging, as it w...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
568b0e1b00f6-4
# First, let's explicitly set the StdOutCallbackHandler in `callbacks` chain = LLMChain(llm=llm, prompt=prompt, callbacks=[handler]) chain.run(number=2) # Then, let's use the `verbose` flag to achieve the same result chain = LLMChain(llm=llm, prompt=prompt, verbose=True) chain.run(number=2) # Finally, let's use the req...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
568b0e1b00f6-5
chat([HumanMessage(content="Tell me a joke")]) My custom handler, token: My custom handler, token: Why My custom handler, token: did My custom handler, token: the My custom handler, token: tomato My custom handler, token: turn My custom handler, token: red My custom handler, token: ? My custom handler, token: Be...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
568b0e1b00f6-6
self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any ) -> None: """Run when chain starts running.""" print("zzzz....") await asyncio.sleep(0.3) class_name = serialized["name"] print("Hi! I just woke up. Your llm is starting") async def on_llm_end(self, resp...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
568b0e1b00f6-7
Sync handler being called in a `thread_pool_executor`: token: they Sync handler being called in a `thread_pool_executor`: token: make Sync handler being called in a `thread_pool_executor`: token: up Sync handler being called in a `thread_pool_executor`: token: everything Sync handler being called in a `thread_pool_...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
568b0e1b00f6-8
from langchain.agents import AgentType, initialize_agent, load_tools from langchain.callbacks import tracing_enabled from langchain.llms import OpenAI # First, define custom callback handler implementations class MyCustomHandlerOne(BaseCallbackHandler): def on_llm_start( self, serialized: Dict[str, Any], pr...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
568b0e1b00f6-9
handler1 = MyCustomHandlerOne() handler2 = MyCustomHandlerTwo() # Setup the agent. Only the `llm` will issue callbacks for handler2 llm = OpenAI(temperature=0, streaming=True, callbacks=[handler2]) tools = load_tools(["llm-math"], llm=llm) agent = initialize_agent( tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRI...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
568b0e1b00f6-10
on_chain_start LLMChain on_llm_start OpenAI on_llm_start (I'm the second handler!!) OpenAI on_new_token on_new_token ```text on_new_token on_new_token 2 on_new_token ** on_new_token 0 on_new_token . on_new_token 235 on_new_token on_new_token ``` on_new_token ... on_new_token num on_new_token expr on_new_token . on_n...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
568b0e1b00f6-11
Using a context manager with tracing_enabled() to trace a particular block of code. Note if the environment variable is set, all code will be traced, regardless of whether or not it’s within the context manager. import os from langchain.agents import AgentType, initialize_agent, load_tools from langchain.callbacks impo...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
568b0e1b00f6-12
Action: Search Action Input: "US Open men's final 2019 winner" Observation: Rafael Nadal defeated Daniil Medvedev in the final, 7–5, 6–3, 5–7, 4–6, 6–4 to win the men's singles tennis title at the 2019 US Open. It was his fourth US ... Thought: I need to find out the age of the winner Action: Search Action Input: "Rafa...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
568b0e1b00f6-13
Action: Calculator Action Input: 29^0.23 Observation: Answer: 2.169459462491557 Thought: I now know the final answer. Final Answer: Harry Styles is Olivia Wilde's boyfriend and his current age raised to the 0.23 power is 2.169459462491557. > Finished chain. # Now, we unset the environment variable and use a context man...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
568b0e1b00f6-14
Thought: I now know the final answer Final Answer: Rafael Nadal, aged 36, won the US Open men's final in 2019 and his age raised to the 0.334 power is 3.3098250249682484. > Finished chain. > Entering new AgentExecutor chain... I need to find out who Olivia Wilde's boyfriend is and then calculate his age raised to the ...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
568b0e1b00f6-15
task = asyncio.create_task(agent.arun(questions[0])) # this should not be traced with tracing_enabled() as session: assert session tasks = [agent.arun(q) for q in questions[1:3]] # these should be traced await asyncio.gather(*tasks) await task > Entering new AgentExecutor chain... > Entering new AgentExec...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
568b0e1b00f6-16
Action: Search Action Input: "Rafael Nadal age"36 years I need to find out Harry Styles' age. Action: Search Action Input: "Harry Styles age" I need to find out Lewis Hamilton's age Action: Search Action Input: "Lewis Hamilton Age"29 years I need to calculate the age raised to the 0.334 power Action: Calculator Action ...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
568b0e1b00f6-17
with get_openai_callback() as cb: await asyncio.gather( *[llm.agenerate(["What is the square root of 4?"]) for _ in range(3)] ) assert cb.total_tokens == total_tokens * 3 # The context manager is concurrency safe task = asyncio.create_task(llm.agenerate(["What is the square root of 4?"])) with get_opena...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
a49f4316da82-0
.rst .pdf Agent Executors Agent Executors# Note Conceptual Guide Agent executors take an agent and tools and use the agent to decide which tools to call and in what order. In this part of the documentation we cover other related functionality to agent executors How to combine agents and vectorstores How to use the asyn...
https://python.langchain.com/en/latest/modules/agents/agent_executors.html
1bf121feca3e-0
.ipynb .pdf Getting Started Getting Started# Agents use an LLM to determine which actions to take and in what order. An action can either be using a tool and observing its output, or returning to the user. When used correctly agents can be extremely powerful. The purpose of this notebook is to show you how to easily us...
https://python.langchain.com/en/latest/modules/agents/getting_started.html
1bf121feca3e-1
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True) Now let’s test it out! agent.run("Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?") > Entering new AgentExecutor chain... I need to find out who Leo DiCaprio's girlfriend is and then calc...
https://python.langchain.com/en/latest/modules/agents/getting_started.html
566ba45eb797-0
.rst .pdf Agents Agents# Note Conceptual Guide In this part of the documentation we cover the different types of agents, disregarding which specific tools they are used with. For a high level overview of the different types of agents, see the below documentation. Agent Types For documentation on how to create a custom ...
https://python.langchain.com/en/latest/modules/agents/agents.html
917344db67d3-0
.ipynb .pdf Plan and Execute Contents Plan and Execute Imports Tools Planner, Executor, and Agent Run Example Plan and Execute# Plan and execute agents accomplish an objective by first planning what to do, then executing the sub tasks. This idea is largely inspired by BabyAGI and then the “Plan-and-Solve” paper. The ...
https://python.langchain.com/en/latest/modules/agents/plan_and_execute.html
917344db67d3-1
> Entering new PlanAndExecute chain... steps=[Step(value="Search for Leo DiCaprio's girlfriend on the internet."), Step(value='Find her current age.'), Step(value='Raise her current age to the 0.43 power using a calculator or programming language.'), Step(value='Output the result.'), Step(value="Given the above steps t...
https://python.langchain.com/en/latest/modules/agents/plan_and_execute.html
917344db67d3-2
Current objective: value='Find her current age.' Action: ``` { "action": "Search", "action_input": "What is Gigi Hadid's current age?" } ``` Observation: 28 years Thought:Previous steps: steps=[(Step(value="Search for Leo DiCaprio's girlfriend on the internet."), StepResponse(response='Leo DiCaprio is currently lin...
https://python.langchain.com/en/latest/modules/agents/plan_and_execute.html
917344db67d3-3
Step: Raise her current age to the 0.43 power using a calculator or programming language. Response: Gigi Hadid's current age raised to the 0.43 power is approximately 4.19. > Entering new AgentExecutor chain... Action: ``` { "action": "Final Answer", "action_input": "The result is approximately 4.19." } ``` > Finis...
https://python.langchain.com/en/latest/modules/agents/plan_and_execute.html
8ef5bf8e3490-0
.rst .pdf Toolkits Toolkits# Note Conceptual Guide This section of documentation covers agents with toolkits - eg an agent applied to a particular use case. See below for a full list of agent toolkits Azure Cognitive Services Toolkit CSV Agent Gmail Toolkit Jira JSON Agent OpenAPI agents Natural Language APIs Pandas Da...
https://python.langchain.com/en/latest/modules/agents/toolkits.html
144f38f48132-0
.rst .pdf Tools Tools# Note Conceptual Guide Tools are ways that an agent can use to interact with the outside world. For an overview of what a tool is, how to use them, and a full list of examples, please see the getting started documentation Getting Started Next, we have some examples of customizing and generically w...
https://python.langchain.com/en/latest/modules/agents/tools.html
9831a82379f9-0
.ipynb .pdf Tool Input Schema Tool Input Schema# By default, tools infer the argument schema by inspecting the function signature. For more strict requirements, custom input schema can be specified, along with custom validation logic. from typing import Any, Dict from langchain.agents import AgentType, initialize_agent...
https://python.langchain.com/en/latest/modules/agents/tools/tool_input_validation.html
9831a82379f9-1
answer = agent.run("What's the main title on langchain.com?") print(answer) The main title of langchain.com is "LANG CHAIN 🦜️🔗 Official Home Page" agent.run("What's the main title on google.com?") --------------------------------------------------------------------------- ValidationError Tra...
https://python.langchain.com/en/latest/modules/agents/tools/tool_input_validation.html
9831a82379f9-2
112 try: --> 113 outputs = self._call(inputs) 114 except (KeyboardInterrupt, Exception) as e: 115 self.callback_manager.on_chain_error(e, verbose=self.verbose) File ~/code/lc/lckg/langchain/agents/agent.py:792, in AgentExecutor._call(self, inputs) 790 # We now enter the agent loop (until it returns ...
https://python.langchain.com/en/latest/modules/agents/tools/tool_input_validation.html
9831a82379f9-3
103 tool_input: Union[str, Dict], (...) 107 **kwargs: Any, 108 ) -> str: 109 """Run the tool.""" --> 110 run_input = self._parse_input(tool_input) 111 if not self.verbose and verbose is not None: 112 verbose_ = verbose File ~/code/lc/lckg/langchain/tools/base.py:71, in...
https://python.langchain.com/en/latest/modules/agents/tools/tool_input_validation.html
f6946ebba7b9-0
.ipynb .pdf Multi-Input Tools Contents Multi-Input Tools with a string format Multi-Input Tools# This notebook shows how to use a tool that requires multiple inputs with an agent. The recommended way to do so is with the StructuredTool class. import os os.environ["LANGCHAIN_TRACING"] = "true" from langchain import Op...
https://python.langchain.com/en/latest/modules/agents/tools/multi_input_tool.html
f6946ebba7b9-1
'3 times 4 is 12' Multi-Input Tools with a string format# An alternative to the structured tool would be to use the regular Tool class and accept a single string. The tool would then have to handle the parsing logic to extract the relavent values from the text, which tightly couples the tool representation to the agent...
https://python.langchain.com/en/latest/modules/agents/tools/multi_input_tool.html
f6946ebba7b9-2
> Entering new AgentExecutor chain... I need to multiply two numbers Action: Multiplier Action Input: 3,4 Observation: 12 Thought: I now know the final answer Final Answer: 3 times 4 is 12 > Finished chain. '3 times 4 is 12' previous Defining Custom Tools next Tool Input Schema Contents Multi-Input Tools with a st...
https://python.langchain.com/en/latest/modules/agents/tools/multi_input_tool.html
960f02fcc5fa-0
.ipynb .pdf Defining Custom Tools Contents Completely New Tools - String Input and Output Tool dataclass Subclassing the BaseTool class Using the tool decorator Custom Structured Tools StructuredTool dataclass Subclassing the BaseTool Using the decorator Modify existing tools Defining the priorities among Tools Using...
https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html
960f02fcc5fa-1
Tool dataclass# The ‘Tool’ dataclass wraps functions that accept a single string input and returns a string output. # Load the tool configs that are needed. search = SerpAPIWrapper() llm_math_chain = LLMMathChain(llm=llm, verbose=True) tools = [ Tool.from_function( func=search.run, name = "Search", ...
https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html
960f02fcc5fa-2
> Entering new AgentExecutor chain... I need to find out Leo DiCaprio's girlfriend's name and her age Action: Search Action Input: "Leo DiCaprio girlfriend" Observation: After rumours of a romance with Gigi Hadid, the Oscar winner has seemingly moved on. First being linked to the television personality in September 202...
https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html
960f02fcc5fa-3
Subclassing the BaseTool class# You can also directly subclass BaseTool. This is useful if you want more control over the instance variables or if you want to propagate callbacks to nested chains or other tools. from typing import Optional, Type from langchain.callbacks.manager import AsyncCallbackManagerForToolRun, Ca...
https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html
960f02fcc5fa-4
agent.run("Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?") > Entering new AgentExecutor chain... I need to use custom_search to find out who Leo DiCaprio's girlfriend is, and then use the Calculator to raise her age to the 0.43 power. Action: custom_search Action Input: "Leo DiCapr...
https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html
960f02fcc5fa-5
> Finished chain. '3.547023357958959' Using the tool decorator# To make it easier to define custom tools, a @tool decorator is provided. This decorator can be used to quickly create a Tool from a simple function. The decorator uses the function name as the tool name by default, but this can be overridden by passing a s...
https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html
960f02fcc5fa-6
"""Searches the API for the query.""" return "Results" search_api Tool(name='search', description='search(query: str) -> str - Searches the API for the query.', args_schema=<class '__main__.SearchInput'>, return_direct=True, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at...
https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html
960f02fcc5fa-7
"""Use the tool.""" search_wrapper = SerpAPIWrapper(params={"engine": engine, "gl": gl, "hl": hl}) return search_wrapper.run(query) async def _arun(self, query: str, engine: str = "google", gl: str = "us", hl: str = "en", run_manager: Optional[AsyncCallbackManagerForToolRun] = None) -> str: ...
https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html
960f02fcc5fa-8
"""Use the tool asynchronously.""" raise NotImplementedError("custom_search does not support async") Using the decorator# The tool decorator creates a structured tool automatically if the signature has multiple arguments. import requests from langchain.tools import tool @tool def post_message(url: str...
https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html
960f02fcc5fa-9
Action: Google Search Action Input: "Leo DiCaprio current girlfriend age" Observation: Leonardo DiCaprio has been linked with 19-year-old model Eden Polani, continuing the rumour that he doesn't date any women over the age of ... Thought:I need to find out the age of Eden Polani. Action: Calculator Action Input: 19^(0....
https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html
960f02fcc5fa-10
tools = [ Tool( name = "Search", func=search.run, description="useful for when you need to answer questions about current events" ), Tool( name="Music Search", func=lambda x: "'All I Want For Christmas Is You' by Mariah Carey.", #Mock Function description="A M...
https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html
960f02fcc5fa-11
return_direct=True ) ] llm = OpenAI(temperature=0) agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True) agent.run("whats 2**.12") > Entering new AgentExecutor chain... I need to calculate this Action: Calculator Action Input: 2**.12Answer: 1.086734862526058 > Finished cha...
https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html
d40f7efbf52b-0
.md .pdf Getting Started Contents List of Tools Getting Started# Tools are functions that agents can use to interact with the world. These tools can be generic utilities (e.g. search), other chains, or even other agents. Currently, tools can be loaded with the following snippet: from langchain.agents import load_tool...
https://python.langchain.com/en/latest/modules/agents/tools/getting_started.html
d40f7efbf52b-1
Requires LLM: No wolfram-alpha Tool Name: Wolfram Alpha Tool Description: A wolfram alpha search engine. Useful for when you need to answer questions about Math, Science, Technology, Culture, Society and Everyday Life. Input should be a search query. Notes: Calls the Wolfram Alpha API and then parses results. Requires ...
https://python.langchain.com/en/latest/modules/agents/tools/getting_started.html
d40f7efbf52b-2
Requires LLM: Yes open-meteo-api Tool Name: Open Meteo API Tool Description: Useful for when you want to get weather information from the OpenMeteo API. The input should be a question in natural language that this API can answer. Notes: A natural language connection to the Open Meteo API (https://api.open-meteo.com/), ...
https://python.langchain.com/en/latest/modules/agents/tools/getting_started.html
d40f7efbf52b-3
For more information on this, see this page searx-search Tool Name: Search Tool Description: A wrapper around SearxNG meta search engine. Input should be a search query. Notes: SearxNG is easy to deploy self-hosted. It is a good privacy friendly alternative to Google Search. Uses the SearxNG API. Requires LLM: No Extra...
https://python.langchain.com/en/latest/modules/agents/tools/getting_started.html
d40f7efbf52b-4
Notes: A connection to the OpenWeatherMap API (https://api.openweathermap.org), specifically the /data/2.5/weather endpoint. Requires LLM: No Extra Parameters: openweathermap_api_key (your API key to access this endpoint) previous Tools next Defining Custom Tools Contents List of Tools By Harrison Chase ...
https://python.langchain.com/en/latest/modules/agents/tools/getting_started.html
495f8df71263-0
.ipynb .pdf Zapier Natural Language Actions API Contents Zapier Natural Language Actions API Example with Agent Example with SimpleSequentialChain Zapier Natural Language Actions API# Full docs here: https://nla.zapier.com/api/v1/docs Zapier Natural Language Actions gives you access to the 5k+ apps, 20k+ actions on Z...
https://python.langchain.com/en/latest/modules/agents/tools/examples/zapier.html
495f8df71263-1
os.environ["OPENAI_API_KEY"] = os.environ.get("OPENAI_API_KEY", "") # get from https://nla.zapier.com/demo/provider/debug (under User Information, after logging in): os.environ["ZAPIER_NLA_API_KEY"] = os.environ.get("ZAPIER_NLA_API_KEY", "") Example with Agent# Zapier tools can be used with an agent. See the example b...
https://python.langchain.com/en/latest/modules/agents/tools/examples/zapier.html
495f8df71263-2
Action: Gmail: Find Email Action Input: Find the latest email from Silicon Valley Bank Observation: {"from__name": "Silicon Valley Bridge Bank, N.A.", "from__email": "sreply@svb.com", "body_plain": "Dear Clients, After chaotic, tumultuous & stressful days, we have clarity on path for SVB, FDIC is fully insuring all dep...
https://python.langchain.com/en/latest/modules/agents/tools/examples/zapier.html
495f8df71263-3
Observation: {"message__text": "Silicon Valley Bank has announced that Tim Mayopoulos is the new CEO. FDIC is fully insuring all deposits and they have an ask for clients and partners as they rebuild.", "message__permalink": "https://langchain.slack.com/archives/C04TSGU0RA7/p1678859932375259", "channel": "C04TSGU0RA7",...
https://python.langchain.com/en/latest/modules/agents/tools/examples/zapier.html
495f8df71263-4
from langchain.tools.zapier.tool import ZapierNLARunAction from langchain.utilities.zapier import ZapierNLAWrapper ## step 0. expose gmail 'find email' and slack 'send direct message' actions # first go here, log in, expose (enable) the two actions: https://nla.zapier.com/demo/start -- for this example, can leave all f...
https://python.langchain.com/en/latest/modules/agents/tools/examples/zapier.html
495f8df71263-5
SLACK_HANDLE = "@Ankush Gola" def nla_slack(inputs): action = next((a for a in actions if a["description"].startswith("Slack: Send Direct Message")), None) instructions = f'Send this to {SLACK_HANDLE} in Slack: {inputs["draft_reply"]}' return {"slack_data": ZapierNLARunAction(action_id=action["id"], zapier_...
https://python.langchain.com/en/latest/modules/agents/tools/examples/zapier.html
495f8df71263-6
overall_chain.run(GMAIL_SEARCH_INSTRUCTIONS) > Entering new SimpleSequentialChain chain... {"from__name": "Silicon Valley Bridge Bank, N.A.", "from__email": "sreply@svb.com", "body_plain": "Dear Clients, After chaotic, tumultuous & stressful days, we have clarity on path for SVB, FDIC is fully insuring all deposits & h...
https://python.langchain.com/en/latest/modules/agents/tools/examples/zapier.html
495f8df71263-7
Best regards, [Your Name] {"message__text": "Dear Silicon Valley Bridge Bank, \n\nThank you for your email and the update regarding your new CEO Tim Mayopoulos. We appreciate your dedication to keeping your clients and partners informed and we look forward to continuing our relationship with you. \n\nBest regards, \n[...
https://python.langchain.com/en/latest/modules/agents/tools/examples/zapier.html
495f8df71263-8
> Finished chain. '{"message__text": "Dear Silicon Valley Bridge Bank, \\n\\nThank you for your email and the update regarding your new CEO Tim Mayopoulos. We appreciate your dedication to keeping your clients and partners informed and we look forward to continuing our relationship with you. \\n\\nBest regards, \\n[You...
https://python.langchain.com/en/latest/modules/agents/tools/examples/zapier.html
5423a16c9aa3-0
.ipynb .pdf File System Tools Contents The FileManagementToolkit Selecting File System Tools File System Tools# LangChain 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! Fir...
https://python.langchain.com/en/latest/modules/agents/tools/examples/filesystem.html
5423a16c9aa3-1
toolkit.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...
https://python.langchain.com/en/latest/modules/agents/tools/examples/filesystem.html
5423a16c9aa3-2
MoveFileTool(name='move_file', 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...
https://python.langchain.com/en/latest/modules/agents/tools/examples/filesystem.html
5423a16c9aa3-3
Selecting 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"])....
https://python.langchain.com/en/latest/modules/agents/tools/examples/filesystem.html
5423a16c9aa3-4
write_tool.run({"file_path": "example.txt", "text": "Hello World!"}) 'File written successfully to example.txt.' # List files in the working directory list_tool.run({}) 'example.txt' previous DuckDuckGo Search next Google Places Contents The FileManagementToolkit Selecting File System Tools By Harrison Chase ...
https://python.langchain.com/en/latest/modules/agents/tools/examples/filesystem.html
b0cc5b080343-0
.ipynb .pdf Python REPL Python REPL# Sometimes, for complex calculations, rather than have an LLM generate the answer directly, it can be better to have the LLM generate code to calculate the answer, and then run that code to get the answer. In order to easily do that, we provide a simple Python REPL to execute command...
https://python.langchain.com/en/latest/modules/agents/tools/examples/python.html
7a3b00af9a2c-0
.ipynb .pdf Shell Tool Contents Use with Agents Shell Tool# Giving agents access to the shell is powerful (though risky outside a sandboxed environment). The LLM can use it to execute any shell commands. A common use case for this is letting the LLM interact with your local file system. from langchain.tools import Sh...
https://python.langchain.com/en/latest/modules/agents/tools/examples/bash.html
7a3b00af9a2c-1
Action: ``` { "action": "shell", "action_input": { "commands": [ "curl -s https://langchain.com | grep -o 'http[s]*://[^\" ]*' | sort" ] } } ``` /Users/wfh/code/lc/lckg/langchain/tools/shell/tool.py:34: UserWarning: The shell tool has no safeguards by default. Use at your own risk. warnings.warn( ...
https://python.langchain.com/en/latest/modules/agents/tools/examples/bash.html
7a3b00af9a2c-2
> Finished chain. '["https://blog.langchain.dev/", "https://discord.gg/6adMQxSpJS", "https://docs.langchain.com/docs/", "https://github.com/hwchase17/chat-langchain", "https://github.com/hwchase17/langchain", "https://github.com/hwchase17/langchainjs", "https://github.com/sullivan-sean/chat-langchainjs", "https://js.la...
https://python.langchain.com/en/latest/modules/agents/tools/examples/bash.html
df3ddef8adf2-0
.ipynb .pdf Search Tools Contents Google Serper API Wrapper SerpAPI GoogleSearchAPIWrapper SearxNG Meta Search Engine Search Tools# This notebook shows off usage of various search tools. from langchain.agents import load_tools from langchain.agents import initialize_agent from langchain.agents import AgentType from l...
https://python.langchain.com/en/latest/modules/agents/tools/examples/search_tools.html
df3ddef8adf2-1
Action: Search Action Input: "weather in Pomfret" Observation: Partly cloudy skies during the morning hours will give way to cloudy skies with light rain and snow developing in the afternoon. High 42F. Winds WNW at 10 to 15 ... Thought: I now know the current weather in Pomfret. Final Answer: Partly cloudy skies during...
https://python.langchain.com/en/latest/modules/agents/tools/examples/search_tools.html
df3ddef8adf2-2
Action: Google Search Action Input: "weather in Pomfret" Observation: Showers early becoming a steady light rain later in the day. Near record high temperatures. High around 60F. Winds SW at 10 to 15 mph. Chance of rain 60%. Pomfret, CT Weather Forecast, with current conditions, wind, air quality, and what to expect fo...
https://python.langchain.com/en/latest/modules/agents/tools/examples/search_tools.html
df3ddef8adf2-3
> Finished AgentExecutor chain. 'Showers early becoming a steady light rain later in the day. Near record high temperatures. High around 60F. Winds SW at 10 to 15 mph. Chance of rain 60%.' SearxNG Meta Search Engine# Here we will be using a self hosted SearxNG meta search engine. tools = load_tools(["searx-search"], se...
https://python.langchain.com/en/latest/modules/agents/tools/examples/search_tools.html
df3ddef8adf2-4
Pomfret, CT ; Current Weather. 1:06 AM. 35°F · RealFeel® 32° ; TODAY'S WEATHER FORECAST. 3/3. 44°Hi. RealFeel® 50° ; TONIGHT'S WEATHER FORECAST. 3/3. 32°Lo. Pomfret, MD Forecast Today Hourly Daily Morning 41° 1% Afternoon 43° 0% Evening 35° 3% Overnight 34° 2% Don't Miss Finally, Here’s Why We Get More Colds and Flu Wh...
https://python.langchain.com/en/latest/modules/agents/tools/examples/search_tools.html
df3ddef8adf2-5
Thought: I now know the final answer Final Answer: The current weather in Pomfret is mainly cloudy with snow showers around in the morning. The temperature is around 40F with winds NNW at 5 to 10 mph. Chance of snow is 40%. > Finished chain. 'The current weather in Pomfret is mainly cloudy with snow showers around in t...
https://python.langchain.com/en/latest/modules/agents/tools/examples/search_tools.html
3f2453bc206f-0
.ipynb .pdf GraphQL tool GraphQL tool# This 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 cl...
https://python.langchain.com/en/latest/modules/agents/tools/examples/graphql.html
3f2453bc206f-1
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 ...
https://python.langchain.com/en/latest/modules/agents/tools/examples/graphql.html
3f2453bc206f-2
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 25, 2023.
https://python.langchain.com/en/latest/modules/agents/tools/examples/graphql.html
60daf1b43318-0
.ipynb .pdf Apify Apify# This notebook shows how to use the Apify integration for LangChain. Apify is a cloud platform for web scraping and data extraction, which provides an ecosystem of more than a thousand ready-made apps called Actors for various web scraping, crawling, and data extraction use cases. For example, y...
https://python.langchain.com/en/latest/modules/agents/tools/examples/apify.html
60daf1b43318-1
loader = apify.call_actor( actor_id="apify/website-content-crawler", run_input={"startUrls": [{"url": "https://python.langchain.com/en/latest/"}]}, dataset_mapping_function=lambda item: Document( page_content=item["text"] or "", metadata={"source": item["url"]} ), ) Initialize the vector index f...
https://python.langchain.com/en/latest/modules/agents/tools/examples/apify.html
a383afda21f9-0
.ipynb .pdf SearxNG Search API Contents Custom Parameters Obtaining results with metadata SearxNG Search API# This notebook goes over how to use a self hosted SearxNG search API to search the web. You can check this link for more informations about Searx API parameters. import pprint from langchain.utilities import S...
https://python.langchain.com/en/latest/modules/agents/tools/examples/searx_search.html
a383afda21f9-1
search.run("large language model ", engines=['wiki']) 'Large language models (LLMs) represent a major advancement in AI, with the promise of transforming domains through learned knowledge. LLM sizes have been increasing 10X every year for the last few years, and as these models grow in complexity and size, so do their ...
https://python.langchain.com/en/latest/modules/agents/tools/examples/searx_search.html
a383afda21f9-2
search.run("deep learning", language='es', engines=['wiki']) 'Aprendizaje profundo (en inglés, deep learning) es un conjunto de algoritmos de aprendizaje automático (en inglés, machine learning) que intenta modelar abstracciones de alto nivel en datos usando arquitecturas computacionales que admiten transformaciones no...
https://python.langchain.com/en/latest/modules/agents/tools/examples/searx_search.html
a383afda21f9-3
'title': 'Promptchainer: Chaining large language model prompts through ' 'visual programming', 'link': 'https://dl.acm.org/doi/abs/10.1145/3491101.3519729', 'engines': ['google scholar'], 'category': 'science'}, {'snippet': '… can introspect the large prompt model. We derive the view ' 'ϕ...
https://python.langchain.com/en/latest/modules/agents/tools/examples/searx_search.html
a383afda21f9-4
'link': 'https://arxiv.org/abs/2204.02329', 'engines': ['google scholar'], 'category': 'science'}] Get papers from arxiv results = search.results("Large Language Model prompt", num_results=5, engines=['arxiv']) pprint.pp(results) [{'snippet': 'Thanks to the advanced improvement of large pre-trained language ' ...
https://python.langchain.com/en/latest/modules/agents/tools/examples/searx_search.html
a383afda21f9-5
'development of real-world AES systems, yet it remains an ' 'under-explored area of research. Models designed for ' 'prompt-specific AES rely heavily on prompt-specific knowledge ' 'and perform poorly in the cross-prompt setting, whereas current ' 'approaches to cross...
https://python.langchain.com/en/latest/modules/agents/tools/examples/searx_search.html
a383afda21f9-6
'example selection. We further explore the use of monolingual ' 'data and the feasibility of cross-lingual, cross-domain, and ' 'sentence-to-document transfer learning in prompting. Extensive ' 'experiments with GLM-130B (Zeng et al., 2022) as the testbed ' 'show that...
https://python.langchain.com/en/latest/modules/agents/tools/examples/searx_search.html
a383afda21f9-7
'effective, especially when the prompts are natural language. In ' 'this paper, we investigate common attributes shared by effective ' 'prompts. We first propose a human readable prompt tuning method ' '(F LUENT P ROMPT) based on Langevin dynamics that incorporates a ' ...
https://python.langchain.com/en/latest/modules/agents/tools/examples/searx_search.html
a383afda21f9-8
'In this work, we discuss methods of prompt programming, ' 'emphasizing the usefulness of considering prompts through the ' 'lens of natural language. We explore techniques for exploiting ' 'the capacity of narratives and cultural anchors to encode ' 'nuanced intentio...
https://python.langchain.com/en/latest/modules/agents/tools/examples/searx_search.html