id
stringlengths 14
16
| text
stringlengths 45
2.05k
| source
stringlengths 53
111
|
---|---|---|
f4c3591fe870-0 | .ipynb
.pdf
Bash
Bash#
It can often be useful to have an LLM generate bash commands, and then run them. A common use case for this is letting the LLM interact with your local file system. We provide an easy util to execute bash commands.
from langchain.utilities import BashProcess
bash = BashProcess()
print(bash.run("ls"))
bash.ipynb
google_search.ipynb
python.ipynb
requests.ipynb
serpapi.ipynb
previous
Generic Utilities
next
Bing Search
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Mar 24, 2023. | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\bash.html" |
ab8c014c3024-0 | .ipynb
.pdf
Bing Search
Contents
Number of results
Metadata Results
Bing Search#
This notebook goes over how to use the bing search component.
First, you need to set up the proper API keys and environment variables. To set it up, follow the instructions found here.
Then we will need to set some environment variables.
import os
os.environ["BING_SUBSCRIPTION_KEY"] = ""
os.environ["BING_SEARCH_URL"] = ""
from langchain.utilities import BingSearchAPIWrapper
search = BingSearchAPIWrapper()
search.run("python") | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\bing_search.html" |
ab8c014c3024-1 | 'Thanks to the flexibility of <b>Python</b> and the powerful ecosystem of packages, the Azure CLI supports features such as autocompletion (in shells that support it), persistent credentials, JMESPath result parsing, lazy initialization, network-less unit tests, and more. Building an open-source and cross-platform Azure CLI with <b>Python</b> by Dan Taylor. <b>Python</b> releases by version number: Release version Release date Click for more. <b>Python</b> 3.11.1 Dec. 6, 2022 Download Release Notes. <b>Python</b> 3.10.9 Dec. 6, 2022 Download Release Notes. <b>Python</b> 3.9.16 Dec. 6, 2022 Download Release Notes. <b>Python</b> 3.8.16 Dec. 6, 2022 Download Release Notes. <b>Python</b> 3.7.16 Dec. 6, 2022 Download Release Notes. In this lesson, we will look at the += operator in <b>Python</b> and see how it works with several simple examples.. The operator ‘+=’ is a shorthand for the addition assignment operator.It adds two values and assigns the sum | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\bing_search.html" |
ab8c014c3024-2 | assignment operator.It adds two values and assigns the sum to a variable (left operand). W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, <b>Python</b>, SQL, Java, and many, many more. This tutorial introduces the reader informally to the basic concepts and features of the <b>Python</b> language and system. It helps to have a <b>Python</b> interpreter handy for hands-on experience, but all examples are self-contained, so the tutorial can be read off-line as well. For a description of standard objects and modules, see The <b>Python</b> Standard ... <b>Python</b> is a general-purpose, versatile, and powerful programming language. It's a great first language because <b>Python</b> code is concise and easy to read. Whatever you want to do, <b>python</b> can do it. From web development to machine learning to data science, <b>Python</b> is the language for you. To install <b>Python</b> using the Microsoft Store: | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\bing_search.html" |
ab8c014c3024-3 | To install <b>Python</b> using the Microsoft Store: Go to your Start menu (lower left Windows icon), type "Microsoft Store", select the link to open the store. Once the store is open, select Search from the upper-right menu and enter "<b>Python</b>". Select which version of <b>Python</b> you would like to use from the results under Apps. Under the “<b>Python</b> Releases for Mac OS X” heading, click the link for the Latest <b>Python</b> 3 Release - <b>Python</b> 3.x.x. As of this writing, the latest version was <b>Python</b> 3.8.4. Scroll to the bottom and click macOS 64-bit installer to start the download. When the installer is finished downloading, move on to the next step. Step 2: Run the Installer' | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\bing_search.html" |
ab8c014c3024-4 | Number of results#
You can use the k parameter to set the number of results
search = BingSearchAPIWrapper(k=1)
search.run("python")
'Thanks to the flexibility of <b>Python</b> and the powerful ecosystem of packages, the Azure CLI supports features such as autocompletion (in shells that support it), persistent credentials, JMESPath result parsing, lazy initialization, network-less unit tests, and more. Building an open-source and cross-platform Azure CLI with <b>Python</b> by Dan Taylor.'
Metadata Results#
Run query through BingSearch and return snippet, title, and link metadata.
Snippet: The description of the result.
Title: The title of the result.
Link: The link to the result.
search = BingSearchAPIWrapper()
search.results("apples", 5)
[{'snippet': 'Lady Alice. Pink Lady <b>apples</b> aren’t the only lady in the apple family. Lady Alice <b>apples</b> were discovered growing, thanks to bees pollinating, in Washington. They are smaller and slightly more stout in appearance than other varieties. Their skin color appears to have red and yellow stripes running from stem to butt.',
'title': '25 Types of Apples - Jessica Gavin',
'link': 'https://www.jessicagavin.com/types-of-apples/'},
{'snippet': '<b>Apples</b> can do a lot for you, thanks to plant chemicals called flavonoids. And they have pectin, a fiber that breaks down in your gut. If you take off the apple’s skin before eating it, you won ...',
'title': 'Apples: Nutrition & Health Benefits - WebMD',
'link': 'https://www.webmd.com/food-recipes/benefits-apples'}, | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\bing_search.html" |
ab8c014c3024-5 | {'snippet': '<b>Apples</b> boast many vitamins and minerals, though not in high amounts. However, <b>apples</b> are usually a good source of vitamin C. Vitamin C. Also called ascorbic acid, this vitamin is a common ...',
'title': 'Apples 101: Nutrition Facts and Health Benefits',
'link': 'https://www.healthline.com/nutrition/foods/apples'},
{'snippet': 'Weight management. The fibers in <b>apples</b> can slow digestion, helping one to feel greater satisfaction after eating. After following three large prospective cohorts of 133,468 men and women for 24 years, researchers found that higher intakes of fiber-rich fruits with a low glycemic load, particularly <b>apples</b> and pears, were associated with the least amount of weight gain over time.',
'title': 'Apples | The Nutrition Source | Harvard T.H. Chan School of Public Health',
'link': 'https://www.hsph.harvard.edu/nutritionsource/food-features/apples/'}]
previous
Bash
next
Google Search
Contents
Number of results
Metadata Results
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Mar 24, 2023. | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\bing_search.html" |
c4ce34af7a28-0 | .ipynb
.pdf
Google Search
Contents
Number of Results
Metadata Results
Google Search#
This notebook goes over how to use the google search component.
First, you need to set up the proper API keys and environment variables. To set it up, follow the instructions found here.
Then we will need to set some environment variables.
import os
os.environ["GOOGLE_CSE_ID"] = ""
os.environ["GOOGLE_API_KEY"] = ""
from langchain.utilities import GoogleSearchAPIWrapper
search = GoogleSearchAPIWrapper()
search.run("Obama's first name?") | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\google_search.html" |
c4ce34af7a28-1 | '1 Child\'s First Name. 2. 6. 7d. Street Address. 71. (Type or print). BARACK. Sex. 3. This Birth. 4. If Twin or Triplet,. Was Child Born. Barack Hussein Obama II is an American retired politician who served as the 44th president of the United States from 2009 to 2017. His full name is Barack Hussein Obama II. Since the “II” is simply because he was named for his father, his last name is Obama. Feb 9, 2015 ... Michael Jordan misspelled Barack Obama\'s first name on 50th-birthday gift ... Knowing Obama is a Chicagoan and huge basketball fan,\xa0... Aug 18, 2017 ... It took him several seconds and multiple clues to remember former President Barack Obama\'s first name. Miller knew that every answer had to end\xa0... First Lady Michelle LaVaughn Robinson Obama is a lawyer, writer, and the wife of the 44th President, Barack Obama. She is the first African-American First\xa0... 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\xa0... When Barack Obama was elected president in 2008, he became the first African American to hold ... The Middle East remained a key foreign policy challenge. Feb 27, 2020 ... President Barack Obama was born Barack Hussein Obama, II, as shown here on his birth certificate here . As reported by Reuters here , his\xa0... Jan 16, 2007 ... 4, 1961, in Honolulu. His first name means "one who is blessed" in Swahili. While Obama\'s father, Barack Hussein Obama Sr., was from Kenya, his\xa0...' | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\google_search.html" |
c4ce34af7a28-2 | Number of Results#
You can use the k parameter to set the number of results
search = GoogleSearchAPIWrapper(k=1)
search.run("python")
'The official home of the Python Programming Language.'
‘The official home of the Python Programming Language.’
Metadata Results#
Run query through GoogleSearch and return snippet, title, and link metadata.
Snippet: The description of the result.
Title: The title of the result.
Link: The link to the result.
search = GoogleSearchAPIWrapper()
search.results("apples", 5)
[{'snippet': 'Discover the innovative world of Apple and shop everything iPhone, iPad, Apple Watch, Mac, and Apple TV, plus explore accessories, entertainment,\xa0...',
'title': 'Apple',
'link': 'https://www.apple.com/'},
{'snippet': "Jul 10, 2022 ... Whether or not you're up on your apple trivia, no doubt you know how delicious this popular fruit is, and how nutritious. Apples are rich in\xa0...",
'title': '25 Types of Apples and What to Make With Them - Parade ...',
'link': 'https://parade.com/1330308/bethlipton/types-of-apples/'},
{'snippet': 'An apple is an edible fruit produced by an apple tree (Malus domestica). Apple trees are cultivated worldwide and are the most widely grown species in the\xa0...',
'title': 'Apple - Wikipedia',
'link': 'https://en.wikipedia.org/wiki/Apple'},
{'snippet': 'Apples are a popular fruit. They contain antioxidants, vitamins, dietary fiber, and a range of other nutrients. Due to their varied nutrient content,\xa0...',
'title': 'Apples: Benefits, nutrition, and tips', | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\google_search.html" |
c4ce34af7a28-3 | 'title': 'Apples: Benefits, nutrition, and tips',
'link': 'https://www.medicalnewstoday.com/articles/267290'},
{'snippet': "An apple is a crunchy, bright-colored fruit, one of the most popular in the United States. You've probably heard the age-old saying, “An apple a day keeps\xa0...",
'title': 'Apples: Nutrition & Health Benefits',
'link': 'https://www.webmd.com/food-recipes/benefits-apples'}]
previous
Bing Search
next
Google Serper API
Contents
Number of Results
Metadata Results
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Mar 24, 2023. | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\google_search.html" |
286a15e232f6-0 | .ipynb
.pdf
Google Serper API
Contents
As part of a Self Ask With Search Chain
Google Serper API#
This 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 os
os.environ["SERPER_API_KEY"] = ""
from langchain.utilities import GoogleSerperAPIWrapper
search = 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 GoogleSerperAPIWrapper
from langchain.llms.openai import OpenAI
from langchain.agents import initialize_agent, Tool
llm = OpenAI(temperature=0)
search = GoogleSerperAPIWrapper()
tools = [
Tool(
name="Intermediate Answer",
func=search.run,
description="useful for when you need to ask with search"
)
]
self_ask_with_search = initialize_agent(tools, llm, agent="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'
previous
Google Search
next
IFTTT WebHooks
Contents | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\google_serper.html" |
286a15e232f6-1 | previous
Google Search
next
IFTTT WebHooks
Contents
As part of a Self Ask With Search Chain
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Mar 24, 2023. | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\google_serper.html" |
b256b33a62ab-0 | .ipynb
.pdf
IFTTT WebHooks
Contents
IFTTT WebHooks
Creating a webhook
Configuring the “If This”
Configuring the “Then That”
Finishing up
IFTTT WebHooks#
This notebook shows how to use IFTTT Webhooks.
From https://github.com/SidU/teams-langchain-js/wiki/Connecting-IFTTT-Services.
Creating a webhook#
Go to https://ifttt.com/create
Configuring the “If This”#
Click on the “If This” button in the IFTTT interface.
Search for “Webhooks” in the search bar.
Choose the first option for “Receive a web request with a JSON payload.”
Choose an Event Name that is specific to the service you plan to connect to.
This will make it easier for you to manage the webhook URL.
For example, if you’re connecting to Spotify, you could use “Spotify” as your
Event Name.
Click the “Create Trigger” button to save your settings and create your webhook.
Configuring the “Then That”#
Tap on the “Then That” button in the IFTTT interface.
Search for the service you want to connect, such as Spotify.
Choose an action from the service, such as “Add track to a playlist”.
Configure the action by specifying the necessary details, such as the playlist name,
e.g., “Songs from AI”.
Reference the JSON Payload received by the Webhook in your action. For the Spotify
scenario, choose “{{JsonPayload}}” as your search query.
Tap the “Create Action” button to save your action settings.
Once you have finished configuring your action, click the “Finish” button to
complete the setup.
Congratulations! You have successfully connected the Webhook to the desired | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\ifttt.html" |
b256b33a62ab-1 | complete the setup.
Congratulations! You have successfully connected the Webhook to the desired
service, and you’re ready to start receiving data and triggering actions 🎉
Finishing up#
To get your webhook URL go to https://ifttt.com/maker_webhooks/settings
Copy the IFTTT key value from there. The URL is of the form
https://maker.ifttt.com/use/YOUR_IFTTT_KEY. Grab the YOUR_IFTTT_KEY value.
from langchain.tools.ifttt import IFTTTWebhook
import os
key = os.environ["IFTTTKey"]
url = f"https://maker.ifttt.com/trigger/spotify/json/with/key/{key}"
tool = IFTTTWebhook(name="Spotify", description="Add a song to spotify playlist", url=url)
tool.run("taylor swift")
"Congratulations! You've fired the spotify JSON event"
previous
Google Serper API
next
Python REPL
Contents
IFTTT WebHooks
Creating a webhook
Configuring the “If This”
Configuring the “Then That”
Finishing up
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Mar 24, 2023. | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\ifttt.html" |
d8427f84a977-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 commands in.
This interface will only return things that are printed - therefor, if you want to use it to calculate an answer, make sure to have it print out the answer.
from langchain.utilities import PythonREPL
python_repl = PythonREPL()
python_repl.run("print(1+1)")
'2\n'
previous
IFTTT WebHooks
next
Requests
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Mar 24, 2023. | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\python.html" |
d574b78eb052-0 | .ipynb
.pdf
Requests
Requests#
The 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.
from langchain.utilities import RequestsWrapper
requests = RequestsWrapper()
requests.get("https://www.google.com") | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\requests.html" |
d574b78eb052-1 | '<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en"><head><meta content="Search the world\'s information, including webpages, images, videos and more. Google has many special features to help you find exactly what you\'re looking for." name="description"><meta content="noodp" name="robots"><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"><meta content="/logos/doodles/2023/international-womens-day-2023-6753651837109578-l.png" itemprop="image"><meta content="International Women\'s Day 2023" property="twitter:title"><meta content="International Women\'s Day 2023! #GoogleDoodle" property="twitter:description"><meta content="International Women\'s Day 2023! #GoogleDoodle" property="og:description"><meta content="summary_large_image" property="twitter:card"><meta content="@GoogleDoodles" property="twitter:site"><meta content="https://www.google.com/logos/doodles/2023/international-womens-day-2023-6753651837109578-2x.png" property="twitter:image"><meta content="https://www.google.com/logos/doodles/2023/international-womens-day-2023-6753651837109578-2x.png" property="og:image"><meta content="1000" property="og:image:width"><meta content="400" property="og:image:height"><title>Google</title><script | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\requests.html" |
d574b78eb052-2 | nonce="skA52jTjrFARNMkurZZTjQ">(function(){window.google={kEI:\'5dkIZP3HJ4WPur8PmJ23iAc\',kEXPI:\'0,18168,772936,568305,6059,206,4804,2316,383,246,5,1129120,1197787,614,165,379924,16115,28684,22431,1361,12313,17586,4998,13228,37471,4820,887,1985,2891,3926,7828,606,29842,826,19390,10632,15324,432,3,346,1244,1,5444,149,11323,2652,4,1528,2304,29062,9871,3194,11443,2215,2980,10815,7428,5821,2536,4094, | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\requests.html" |
d574b78eb052-3 | 7428,5821,2536,4094,7596,1,42154,2,14022,2373,342,23024,5679,1021,31121,4569,6258,23418,1252,5835,14967,4333,7484,445,2,2,1,24626,2006,8155,7381,2,3,15965,872,9626,10008,7,1922,5784,3995,19130,2261,14763,6304,2008,18192,927,14678,4531,14,82,16514,3692,109,1513,899,879,2226,2751,1854,1931,156,8524,2426,721,1021,904,1423,4415,988,3030,426,5684,1411,23,867,2685,4720,1300,504,567,6974,9,184,26,469,223 | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\requests.html" |
d574b78eb052-4 | 974,9,184,26,469,2238,5,1648,109,1127,450,6708,5318,1002,258,3392,1991,4,29,212,2,375,537,1046,314,1720,78,890,1861,1,1172,2275,129,29,632,274,599,731,1305,392,307,536,592,87,113,762,845,2552,3788,220,669,3,750,1174,601,310,611,27,54,49,398,51,238,1079,67,3232,710,1652,82,5,667,2077,544,3,15,2,24,497,977,40,338,224,119,101,149,4,4,129,218,25,683,1,378,533,382,284,189,143,5,204,393,1137,781,4,81,15 | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\requests.html" |
d574b78eb052-5 | 393,1137,781,4,81,1558,241,104,5232351,297,152,8798692,3311,141,795,19735,302,46,23950484,553,4041590,1964,1008,15665,2893,512,5738,12560,1540,1218,146,1415332\',kBL:\'Td3a\'};google.sn=\'webhp\';google.kHL=\'en\';})();(function(){\nvar | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\requests.html" |
d574b78eb052-6 | f=this||self;var h,k=[];function l(a){for(var b;a&&(!a.getAttribute||!(b=a.getAttribute("eid")));)a=a.parentNode;return b||h}function m(a){for(var b=null;a&&(!a.getAttribute||!(b=a.getAttribute("leid")));)a=a.parentNode;return b}\nfunction n(a,b,c,d,g){var e="";c||-1!==b.search("&ei=")||(e="&ei="+l(d),-1===b.search("&lei=")&&(d=m(d))&&(e+="&lei="+d));d="";!c&&f._cshid&&-1===b.search("&cshid=")&&"slh"!==a&&(d="&cshid="+f._cshid);c=c||"/"+(g||"gen_204")+"?atyp=i&ct="+a+"&cad="+b+e+"&zx="+Date.now()+d;/^http:/i.test(c)&&"https:"===window.location.protocol&&(google.ml&&google.ml(Error("a"),!1,{src:c,glmm:1}),c="");return c};h=google.kEI;google.getEI=l;google.getLEI=m;google.ml=function(){return null};google.log=function(a,b,c,d,g){if(c=n(a,b,c,d,g)){a=new Image;var e=k.length;k[e]=a;a.onerror=a.onload=a.onabort=function(){delete k[e]};a.src=c}};google.logUrl=n;}).call(this);(function(){google.y={};google.sy=[];google.x=function(a,b){if(a)var c=a.id;else{do | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\requests.html" |
d574b78eb052-7 | c=a.id;else{do c=Math.random();while(google.y[c])}google.y[c]=[a,b];return!1};google.sx=function(a){google.sy.push(a)};google.lm=[];google.plm=function(a){google.lm.push.apply(google.lm,a)};google.lq=[];google.load=function(a,b,c){google.lq.push([[a],b,c])};google.loadAll=function(a,b){google.lq.push([a,b])};google.bx=!1;google.lx=function(){};}).call(this);google.f={};(function(){\ndocument.documentElement.addEventListener("submit",function(b){var a;if(a=b.target){var c=a.getAttribute("data-submitfalse");a="1"===c||"q"===c&&!a.elements.q.value?!0:!1}else a=!1;a&&(b.preventDefault(),b.stopPropagation())},!0);document.documentElement.addEventListener("click",function(b){var a;a:{for(a=b.target;a&&a!==document.documentElement;a=a.parentElement)if("A"===a.tagName){a="1"===a.getAttribute("data-nohref");break a}a=!1}a&&b.preventDefault()},!0);}).call(this);</script><style>#gbar,#guser{font-size:13px;padding-top:1px !important;}#gbar{height:22px}#guser{padding-bottom:7px !important;text-align:right}.gbh,.gbd{border-top:1px solid #c9d7f1;font-size:1px}.gbh{height:0;position:absolute;top:24px;width:100%}@media all{.gb1{height:22px;margin-right:.5em;vertical-align:top}#gbar{float:left}}a.gb1,a.gb4{text-decoration:underline | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\requests.html" |
d574b78eb052-8 | !important}a.gb1,a.gb4{color:#00c !important}.gbi .gb4{color:#dd8e27 !important}.gbf .gb4{color:#900 !important}\n</style><style>body,td,a,p,.h{font-family:arial,sans-serif}body{margin:0;overflow-y:scroll}#gog{padding:3px 8px 0}td{line-height:.8em}.gac_m td{line-height:17px}form{margin-bottom:20px}.h{color:#1558d6}em{font-weight:bold;font-style:normal}.lst{height:25px;width:496px}.gsfi,.lst{font:18px arial,sans-serif}.gsfs{font:17px arial,sans-serif}.ds{display:inline-box;display:inline-block;margin:3px 0 4px;margin-left:4px}input{font-family:inherit}body{background:#fff;color:#000}a{color:#4b11a8;text-decoration:none}a:hover,a:active{text-decoration:underline}.fl a{color:#1558d6}a:visited{color:#4b11a8}.sblc{padding-top:5px}.sblc a{display:block;margin:2px 0;margin-left:13px;font-size:11px}.lsbb{background:#f8f9fa;border:solid 1px;border-color:#dadce0 #70757a #70757a #dadce0;height:30px}.lsbb{display:block}#WqQANb a{display:inline-block;margin:0 12px}.lsb{background:url(/images/nav_logo229.png) 0 -261px | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\requests.html" |
d574b78eb052-9 | 0 -261px repeat-x;border:none;color:#000;cursor:pointer;height:30px;margin:0;outline:0;font:15px arial,sans-serif;vertical-align:top}.lsb:active{background:#dadce0}.lst:focus{outline:none}</style><script nonce="skA52jTjrFARNMkurZZTjQ">(function(){window.google.erd={jsr:1,bv:1756,de:true};\nvar h=this||self;var k,l=null!=(k=h.mei)?k:1,n,p=null!=(n=h.sdo)?n:!0,q=0,r,t=google.erd,v=t.jsr;google.ml=function(a,b,d,m,e){e=void 0===e?2:e;b&&(r=a&&a.message);if(google.dl)return google.dl(a,e,d),null;if(0>v){window.console&&console.error(a,d);if(-2===v)throw a;b=!1}else b=!a||!a.message||"Error loading script"===a.message||q>=l&&!m?!1:!0;if(!b)return null;q++;d=d||{};b=encodeURIComponent;var c="/gen_204?atyp=i&ei="+b(google.kEI);google.kEXPI&&(c+="&jexpid="+b(google.kEXPI));c+="&srcpg="+b(google.sn)+"&jsr="+b(t.jsr)+"&bver="+b(t.bv);var f=a.lineNumber;void 0!==f&&(c+="&line="+f);var | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\requests.html" |
d574b78eb052-10 | f=a.lineNumber;void 0!==f&&(c+="&line="+f);var g=\na.fileName;g&&(0<g.indexOf("-extension:/")&&(e=3),c+="&script="+b(g),f&&g===window.location.href&&(f=document.documentElement.outerHTML.split("\\n")[f],c+="&cad="+b(f?f.substring(0,300):"No script found.")));c+="&jsel="+e;for(var u in d)c+="&",c+=b(u),c+="=",c+=b(d[u]);c=c+"&emsg="+b(a.name+": "+a.message);c=c+"&jsst="+b(a.stack||"N/A");12288<=c.length&&(c=c.substr(0,12288));a=c;m||google.log(0,"",a);return a};window.onerror=function(a,b,d,m,e){r!==a&&(a=e instanceof Error?e:Error(a),void 0===d||"lineNumber"in a||(a.lineNumber=d),void 0===b||"fileName"in a||(a.fileName=b),google.ml(a,!1,void 0,!1,"SyntaxError"===a.name||"SyntaxError"===a.message.substring(0,11)||-1!==a.message.indexOf("Script error")?3:0));r=null;p&&q>=l&&(window.onerror=null)};})();</script></head><body bgcolor="#fff"><script nonce="skA52jTjrFARNMkurZZTjQ">(function(){var src=\'/images/nav_logo229.png\';var iesg=false;document.body.onload = function(){window.n && window.n();if (document.images){new Image().src=src;}\nif | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\requests.html" |
d574b78eb052-11 | window.n();if (document.images){new Image().src=src;}\nif (!iesg){document.f&&document.f.q.focus();document.gbqf&&document.gbqf.q.focus();}\n}\n})();</script><div id="mngb"><div id=gbar><nobr><b class=gb1>Search</b> <a class=gb1 href="https://www.google.com/imghp?hl=en&tab=wi">Images</a> <a class=gb1 href="https://maps.google.com/maps?hl=en&tab=wl">Maps</a> <a class=gb1 href="https://play.google.com/?hl=en&tab=w8">Play</a> <a class=gb1 href="https://www.youtube.com/?tab=w1">YouTube</a> <a class=gb1 href="https://news.google.com/?tab=wn">News</a> <a class=gb1 href="https://mail.google.com/mail/?tab=wm">Gmail</a> <a class=gb1 href="https://drive.google.com/?tab=wo">Drive</a> <a class=gb1 style="text-decoration:none" href="https://www.google.com/intl/en/about/products?tab=wh"><u>More</u> »</a></nobr></div><div id=guser width=100%><nobr><span id=gbn class=gbi></span><span id=gbf class=gbf></span><span id=gbe></span><a href="http://www.google.com/history/optout?hl=en" class=gb4>Web History</a> | <a | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\requests.html" |
d574b78eb052-12 | class=gb4>Web History</a> | <a href="/preferences?hl=en" class=gb4>Settings</a> | <a target=_top id=gb_70 href="https://accounts.google.com/ServiceLogin?hl=en&passive=true&continue=https://www.google.com/&ec=GAZAAQ" class=gb4>Sign in</a></nobr></div><div class=gbh style=left:0></div><div class=gbh style=right:0></div></div><center><br clear="all" id="lgpd"><div id="lga"><a href="/search?ie=UTF-8&q=International+Women%27s+Day&oi=ddle&ct=207425752&hl=en&si=AEcPFx5y3cpWB8t3QIlw940Bbgd-HLN-aNYSTraERzz0WyAsdPcV8QlbA9KRIH1_r1H1b32dXlTjZQe5B0MVNeLogkXOiBOkfs-S-hFQywzzxlKEI54jx7H2iV6NSfskfTE00IkUfobnZU0dHdFeGABAmixr9Gj6a8WKVaZeEhYyauqHyAnlpd4%3D&sa=X&ved=0ahUKEwi9zuH2gM39AhWFh-4BHZjODXEQPQgD"><img alt="International Women\'s Day 2023" border="0" height="200" | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\requests.html" |
d574b78eb052-13 | Women\'s Day 2023" border="0" height="200" src="/logos/doodles/2023/international-womens-day-2023-6753651837109578-l.png" title="International Women\'s Day 2023" width="500" id="hplogo"><br></a><br></div><form action="/search" name="f"><table cellpadding="0" cellspacing="0"><tr valign="top"><td width="25%"> </td><td align="center" nowrap=""><input name="ie" value="ISO-8859-1" type="hidden"><input value="en" name="hl" type="hidden"><input name="source" type="hidden" value="hp"><input name="biw" type="hidden"><input name="bih" type="hidden"><div class="ds" style="height:32px;margin:4px 0"><input class="lst" style="margin:0;padding:5px 8px 0 6px;vertical-align:top;color:#000" autocomplete="off" value="" title="Google Search" maxlength="2048" name="q" size="57"></div><br style="line-height:0"><span class="ds"><span class="lsbb"><input class="lsb" value="Google Search" name="btnG" type="submit"></span></span><span class="ds"><span class="lsbb"><input class="lsb" id="tsuid_1" value="I\'m Feeling Lucky" name="btnI" type="submit"><script | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\requests.html" |
d574b78eb052-14 | Feeling Lucky" name="btnI" type="submit"><script nonce="skA52jTjrFARNMkurZZTjQ">(function(){var id=\'tsuid_1\';document.getElementById(id).onclick = function(){if (this.form.q.value){this.checked = 1;if (this.form.iflsig)this.form.iflsig.disabled = false;}\nelse top.location=\'/doodles/\';};})();</script><input value="AK50M_UAAAAAZAjn9T7DxAH0-e8rhw3d8palbJFsdibi" name="iflsig" type="hidden"></span></span></td><td class="fl sblc" align="left" nowrap="" width="25%"><a href="/advanced_search?hl=en&authuser=0">Advanced search</a></td></tr></table><input id="gbv" name="gbv" type="hidden" value="1"><script nonce="skA52jTjrFARNMkurZZTjQ">(function(){var a,b="1";if(document&&document.getElementById)if("undefined"!=typeof XMLHttpRequest)b="2";else if("undefined"!=typeof ActiveXObject){var c,d,e=["MSXML2.XMLHTTP.6.0","MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP","Microsoft.XMLHTTP"];for(c=0;d=e[c++];)try{new ActiveXObject(d),b="2"}catch(h){}}a=b;if("2"==a&&-1==location.search.indexOf("&gbv=2")){var | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\requests.html" |
d574b78eb052-15 | f=google.gbvu,g=document.getElementById("gbv");g&&(g.value=a);f&&window.setTimeout(function(){location.href=f},0)};}).call(this);</script></form><div id="gac_scont"></div><div style="font-size:83%;min-height:3.5em"><br><div id="prm"><style>.szppmdbYutt__middle-slot-promo{font-size:small;margin-bottom:32px}.szppmdbYutt__middle-slot-promo a.ZIeIlb{display:inline-block;text-decoration:none}.szppmdbYutt__middle-slot-promo img{border:none;margin-right:5px;vertical-align:middle}</style><div class="szppmdbYutt__middle-slot-promo" data-ved="0ahUKEwi9zuH2gM39AhWFh-4BHZjODXEQnIcBCAQ"><span>Celebrate </span><a class="NKcBbd" href="https://www.google.com/url?q=https://artsandculture.google.com/project/women-in-culture%3Futm_source%3Dgoogle%26utm_medium%3Dhppromo%26utm_campaign%3Dinternationalwomensday23&source=hpp&id=19034031&ct=3&usg=AOvVaw1Q51Nb9U7JNUznM352o8BF&sa=X&ved=0ahUKEwi9zuH2gM39AhWFh-4BHZjODXEQ8IcBCAU" rel="nofollow">International Women\'s Day</a><span> with Google</span></div></div></div><span id="footer"><div style="font-size:10pt"><div | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\requests.html" |
d574b78eb052-16 | id="footer"><div style="font-size:10pt"><div style="margin:19px auto;text-align:center" id="WqQANb"><a href="/intl/en/ads/">Advertising</a><a href="/services/">Business Solutions</a><a href="/intl/en/about.html">About Google</a></div></div><p style="font-size:8pt;color:#70757a">© 2023 - <a href="/intl/en/policies/privacy/">Privacy</a> - <a href="/intl/en/policies/terms/">Terms</a></p></span></center><script nonce="skA52jTjrFARNMkurZZTjQ">(function(){window.google.cdo={height:757,width:1440};(function(){var a=window.innerWidth,b=window.innerHeight;if(!a||!b){var c=window.document,d="CSS1Compat"==c.compatMode?c.documentElement:c.body;a=d.clientWidth;b=d.clientHeight}a&&b&&(a!=google.cdo.width||b!=google.cdo.height)&&google.log("","","/client_204?&atyp=i&biw="+a+"&bih="+b+"&ei="+google.kEI);}).call(this);})();</script> <script nonce="skA52jTjrFARNMkurZZTjQ">(function(){google.xjs={ck:\'xjs.hp.Y2W3KAJ0Jco.L.X.O\',cs:\'ACT90oEk9pJxm1OOdkVmpGo-yLFc4v5z8w\',excm:[]};})();</script> <script nonce="skA52jTjrFARNMkurZZTjQ">(function(){var | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\requests.html" |
d574b78eb052-17 | nonce="skA52jTjrFARNMkurZZTjQ">(function(){var u=\'/xjs/_/js/k\\x3dxjs.hp.en.ObwAV4EjOBQ.O/am\\x3dAACgEwBAAYAF/d\\x3d1/ed\\x3d1/rs\\x3dACT90oGDUDSLlBIGF3CSmUWoHe0AKqeZ6w/m\\x3dsb_he,d\';var amd=0;\nvar d=this||self,e=function(a){return a};var g;var l=function(a,b){this.g=b===h?a:""};l.prototype.toString=function(){return this.g+""};var h={};\nfunction m(){var a=u;google.lx=function(){p(a);google.lx=function(){}};google.bx||google.lx()}\nfunction p(a){google.timers&&google.timers.load&&google.tick&&google.tick("load","xjsls");var b=document;var c="SCRIPT";"application/xhtml+xml"===b.contentType&&(c=c.toLowerCase());c=b.createElement(c);a=null===a?"null":void 0===a?"undefined":a;if(void 0===g){b=null;var k=d.trustedTypes;if(k&&k.createPolicy){try{b=k.createPolicy("goog#html",{createHTML:e,createScript:e,createScriptURL:e})}catch(q){d.console&&d.console.error(q.message)}g=b}else g=b}a=(b=g)?b.createScriptURL(a):a;a=new l(a,h);c.src=\na instanceof l&&a.constructor===l?a.g:"type_error:TrustedResourceUrl";var | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\requests.html" |
d574b78eb052-18 | l&&a.constructor===l?a.g:"type_error:TrustedResourceUrl";var f,n;(f=(a=null==(n=(f=(c.ownerDocument&&c.ownerDocument.defaultView||window).document).querySelector)?void 0:n.call(f,"script[nonce]"))?a.nonce||a.getAttribute("nonce")||"":"")&&c.setAttribute("nonce",f);document.body.appendChild(c);google.psa=!0};google.xjsu=u;setTimeout(function(){0<amd?google.caft(function(){return m()},amd):m()},0);})();function _DumpException(e){throw e;}\nfunction _F_installCss(c){}\n(function(){google.jl={blt:\'none\',chnk:0,dw:false,dwu:true,emtn:0,end:0,ico:false,ikb:0,ine:false,injs:\'none\',injt:0,injth:0,injv2:false,lls:\'default\',pdt:0,rep:0,snet:true,strt:0,ubm:false,uwp:true};})();(function(){var pmc=\'{\\x22d\\x22:{},\\x22sb_he\\x22:{\\x22agen\\x22:true,\\x22cgen\\x22:true,\\x22client\\x22:\\x22heirloom-hp\\x22,\\x22dh\\x22:true,\\x22ds\\x22:\\x22\\x22,\\x22fl\\x22:true,\\x22host\\x22:\\x22google.com\\x22,\\x22jsonp\\x22:true,\\x22msgs\\x22:{\\x22cibl\\x22:\\x22Clear Search\\x22,\\x22dym\\x22:\\x22Did you | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\requests.html" |
d574b78eb052-19 | Search\\x22,\\x22dym\\x22:\\x22Did you mean:\\x22,\\x22lcky\\x22:\\x22I\\\\u0026#39;m Feeling Lucky\\x22,\\x22lml\\x22:\\x22Learn more\\x22,\\x22psrc\\x22:\\x22This search was removed from your \\\\u003Ca href\\x3d\\\\\\x22/history\\\\\\x22\\\\u003EWeb History\\\\u003C/a\\\\u003E\\x22,\\x22psrl\\x22:\\x22Remove\\x22,\\x22sbit\\x22:\\x22Search by image\\x22,\\x22srch\\x22:\\x22Google Search\\x22},\\x22ovr\\x22:{},\\x22pq\\x22:\\x22\\x22,\\x22rfs\\x22:[],\\x22sbas\\x22:\\x220 3px 8px 0 rgba(0,0,0,0.2),0 0 0 1px rgba(0,0,0,0.08)\\x22,\\x22stok\\x22:\\x222J2TpqBbW29n4YEWhckcWkIgvqM\\x22}}\';google.pmc=JSON.parse(pmc);})();</script> </body></html>' | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\requests.html" |
d574b78eb052-20 | previous
Python REPL
next
SearxNG Search API
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Mar 24, 2023. | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\requests.html" |
aec52e22b7f2-0 | .ipynb
.pdf
SearxNG Search API
Contents
SearxNG Search API
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 SearxSearchWrapper
search = SearxSearchWrapper(searx_host="http://127.0.0.1:8888")
For some engines, if a direct answer is available the warpper will print the answer instead of the full list of search results. You can use the results method of the wrapper if you want to obtain all the results.
search.run("What is the capital of France")
'Paris is the capital of France, the largest country of Europe with 550 000 km2 (65 millions inhabitants). Paris has 2.234 million inhabitants end 2011. She is the core of Ile de France region (12 million people).'
Custom Parameters#
SearxNG supports up to 139 search engines. You can also customize the Searx wrapper with arbitrary named parameters that will be passed to the Searx search API . In the below example we will making a more interesting use of custom search parameters from searx search api.
In this example we will be using the engines parameters to query wikipedia
search = SearxSearchWrapper(searx_host="http://127.0.0.1:8888", k=5) # k is for max number of items
search.run("large language model ", engines=['wiki']) | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\searx_search.html" |
aec52e22b7f2-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 capabilities.\n\nGPT-3 can translate language, write essays, generate computer code, and more — all with limited to no supervision. In July 2020, OpenAI unveiled GPT-3, a language model that was easily the largest known at the time. Put simply, GPT-3 is trained to predict the next word in a sentence, much like how a text message autocomplete feature works.\n\nA large language model, or LLM, is a deep learning algorithm that can recognize, summarize, translate, predict and generate text and other content based on knowledge gained from massive datasets. Large language models are among the most successful applications of transformer models.\n\nAll of today’s well-known language models—e.g., GPT-3 from OpenAI, PaLM or LaMDA from Google, Galactica or OPT from Meta, Megatron-Turing from Nvidia/Microsoft, Jurassic-1 from AI21 Labs—are...\n\nLarge language models (LLMs) such as GPT-3are increasingly being used to generate text. These tools should be used with care, since they can generate content that is biased, non-verifiable, constitutes original research, or violates copyrights.'
Passing other Searx parameters for searx like language
search = SearxSearchWrapper(searx_host="http://127.0.0.1:8888", k=1)
search.run("deep learning", language='es', engines=['wiki']) | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\searx_search.html" |
aec52e22b7f2-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 lineales múltiples e iterativas de datos expresados en forma matricial o tensorial. 1'
Obtaining results with metadata#
In this example we will be looking for scientific paper using the categories parameter and limiting the results to a time_range (not all engines support the time range option).
We also would like to obtain the results in a structured way including metadata. For this we will be using the results method of the wrapper.
search = SearxSearchWrapper(searx_host="http://127.0.0.1:8888")
results = search.results("Large Language Model prompt", num_results=5, categories='science', time_range='year')
pprint.pp(results)
[{'snippet': '… on natural language instructions, large language models (… the '
'prompt used to steer the model, and most effective prompts … to '
'prompt engineering, we propose Automatic Prompt …',
'title': 'Large language models are human-level prompt engineers',
'link': 'https://arxiv.org/abs/2211.01910',
'engines': ['google scholar'],
'category': 'science'},
{'snippet': '… Large language models (LLMs) have introduced new possibilities '
'for prototyping with AI [18]. Pre-trained on a large amount of '
'text data, models … language instructions called prompts. …',
'title': 'Promptchainer: Chaining large language model prompts through ' | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\searx_search.html" |
aec52e22b7f2-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 '
'ϕ0(X) and the model h0 from T01. However, instead of fully '
'fine-tuning T0 during co-training, we focus on soft prompt '
'tuning, …',
'title': 'Co-training improves prompt-based learning for large language '
'models',
'link': 'https://proceedings.mlr.press/v162/lang22a.html',
'engines': ['google scholar'],
'category': 'science'},
{'snippet': '… With the success of large language models (LLMs) of code and '
'their use as … prompt design process become important. In this '
'work, we propose a framework called Repo-Level Prompt …',
'title': 'Repository-level prompt generation for large language models of '
'code',
'link': 'https://arxiv.org/abs/2206.12839',
'engines': ['google scholar'],
'category': 'science'},
{'snippet': '… Figure 2 | The benefits of different components of a prompt '
'for the largest language model (Gopher), as estimated from '
'hierarchical logistic regression. Each point estimates the '
'unique …',
'title': 'Can language models learn from explanations in context?',
'link': 'https://arxiv.org/abs/2204.02329', | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\searx_search.html" |
aec52e22b7f2-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 '
'models, prompt-based fine-tuning is shown to be effective on a '
'variety of downstream tasks. Though many prompting methods have '
'been investigated, it remains unknown which type of prompts are '
'the most effective among three types of prompts (i.e., '
'human-designed prompts, schema prompts and null prompts). In '
'this work, we empirically compare the three types of prompts '
'under both few-shot and fully-supervised settings. Our '
'experimental results show that schema prompts are the most '
'effective in general. Besides, the performance gaps tend to '
'diminish when the scale of training data grows large.',
'title': 'Do Prompts Solve NLP Tasks Using Natural Language?',
'link': 'http://arxiv.org/abs/2203.00902v1',
'engines': ['arxiv'],
'category': 'science'},
{'snippet': 'Cross-prompt automated essay scoring (AES) requires the system '
'to use non target-prompt essays to award scores to a '
'target-prompt essay. Since obtaining a large quantity of '
'pre-graded essays to a particular prompt is often difficult and '
'unrealistic, the task of cross-prompt AES is vital for the '
'development of real-world AES systems, yet it remains an ' | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\searx_search.html" |
aec52e22b7f2-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-prompt AES either require a certain quantity '
'of labelled target-prompt essays or require a large quantity of '
'unlabelled target-prompt essays to perform transfer learning in '
'a multi-step manner. To address these issues, we introduce '
'Prompt Agnostic Essay Scorer (PAES) for cross-prompt AES. Our '
'method requires no access to labelled or unlabelled '
'target-prompt data during training and is a single-stage '
'approach. PAES is easy to apply in practice and achieves '
'state-of-the-art performance on the Automated Student Assessment '
'Prize (ASAP) dataset.',
'title': 'Prompt Agnostic Essay Scorer: A Domain Generalization Approach to '
'Cross-prompt Automated Essay Scoring',
'link': 'http://arxiv.org/abs/2008.01441v1',
'engines': ['arxiv'],
'category': 'science'},
{'snippet': 'Research on prompting has shown excellent performance with '
'little or even no supervised training across many tasks. '
'However, prompting for machine translation is still '
'under-explored in the literature. We fill this gap by offering a '
'systematic study on prompting strategies for translation, '
'examining various factors for prompt template and demonstration '
'example selection. We further explore the use of monolingual ' | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\searx_search.html" |
aec52e22b7f2-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 1) the number and the quality of prompt examples '
'matter, where using suboptimal examples degenerates translation; '
'2) several features of prompt examples, such as semantic '
'similarity, show significant Spearman correlation with their '
'prompting performance; yet, none of the correlations are strong '
'enough; 3) using pseudo parallel prompt examples constructed '
'from monolingual data via zero-shot prompting could improve '
'translation; and 4) improved performance is achievable by '
'transferring knowledge from prompt examples selected in other '
'settings. We finally provide an analysis on the model outputs '
'and discuss several problems that prompting still suffers from.',
'title': 'Prompting Large Language Model for Machine Translation: A Case '
'Study',
'link': 'http://arxiv.org/abs/2301.07069v2',
'engines': ['arxiv'],
'category': 'science'},
{'snippet': 'Large language models can perform new tasks in a zero-shot '
'fashion, given natural language prompts that specify the desired '
'behavior. Such prompts are typically hand engineered, but can '
'also be learned with gradient-based methods from labeled data. '
'However, it is underexplored what factors make the prompts '
'effective, especially when the prompts are natural language. In ' | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\searx_search.html" |
aec52e22b7f2-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 '
'fluency constraint to find a diverse distribution of effective '
'and fluent prompts. Our analysis reveals that effective prompts '
'are topically related to the task domain and calibrate the prior '
'probability of label words. Based on these findings, we also '
'propose a method for generating prompts using only unlabeled '
'data, outperforming strong baselines by an average of 7.0% '
'accuracy across three tasks.',
'title': "Toward Human Readable Prompt Tuning: Kubrick's The Shining is a "
'good movie, and a good prompt too?',
'link': 'http://arxiv.org/abs/2212.10539v1',
'engines': ['arxiv'],
'category': 'science'},
{'snippet': 'Prevailing methods for mapping large generative language models '
"to supervised tasks may fail to sufficiently probe models' novel "
'capabilities. Using GPT-3 as a case study, we show that 0-shot '
'prompts can significantly outperform few-shot prompts. We '
'suggest that the function of few-shot examples in these cases is '
'better described as locating an already learned task rather than '
'meta-learning. This analysis motivates rethinking the role of '
'prompts in controlling and evaluating powerful language models. '
'In this work, we discuss methods of prompt programming, ' | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\searx_search.html" |
aec52e22b7f2-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 intentions and techniques for encouraging deconstruction '
'of a problem into components before producing a verdict. '
'Informed by this more encompassing theory of prompt programming, '
'we also introduce the idea of a metaprompt that seeds the model '
'to generate its own natural language prompts for a range of '
'tasks. Finally, we discuss how these more general methods of '
'interacting with language models can be incorporated into '
'existing and future benchmarks and practical applications.',
'title': 'Prompt Programming for Large Language Models: Beyond the Few-Shot '
'Paradigm',
'link': 'http://arxiv.org/abs/2102.07350v1',
'engines': ['arxiv'],
'category': 'science'}]
In this example we query for large language models under the it category. We then filter the results that come from github.
results = search.results("large language model", num_results = 20, categories='it')
pprint.pp(list(filter(lambda r: r['engines'][0] == 'github', results)))
[{'snippet': 'Guide to using pre-trained large language models of source code',
'title': 'Code-LMs',
'link': 'https://github.com/VHellendoorn/Code-LMs',
'engines': ['github'],
'category': 'it'},
{'snippet': 'Dramatron uses large language models to generate coherent '
'scripts and screenplays.', | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\searx_search.html" |
aec52e22b7f2-9 | 'scripts and screenplays.',
'title': 'dramatron',
'link': 'https://github.com/deepmind/dramatron',
'engines': ['github'],
'category': 'it'}]
We could also directly query for results from github and other source forges.
results = search.results("large language model", num_results = 20, engines=['github', 'gitlab'])
pprint.pp(results)
[{'snippet': "Implementation of 'A Watermark for Large Language Models' paper "
'by Kirchenbauer & Geiping et. al.',
'title': 'Peutlefaire / LMWatermark',
'link': 'https://gitlab.com/BrianPulfer/LMWatermark',
'engines': ['gitlab'],
'category': 'it'},
{'snippet': 'Guide to using pre-trained large language models of source code',
'title': 'Code-LMs',
'link': 'https://github.com/VHellendoorn/Code-LMs',
'engines': ['github'],
'category': 'it'},
{'snippet': '',
'title': 'Simen Burud / Large-scale Language Models for Conversational '
'Speech Recognition',
'link': 'https://gitlab.com/BrianPulfer',
'engines': ['gitlab'],
'category': 'it'},
{'snippet': 'Dramatron uses large language models to generate coherent '
'scripts and screenplays.',
'title': 'dramatron',
'link': 'https://github.com/deepmind/dramatron',
'engines': ['github'],
'category': 'it'}, | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\searx_search.html" |
aec52e22b7f2-10 | 'engines': ['github'],
'category': 'it'},
{'snippet': 'Code for loralib, an implementation of "LoRA: Low-Rank '
'Adaptation of Large Language Models"',
'title': 'LoRA',
'link': 'https://github.com/microsoft/LoRA',
'engines': ['github'],
'category': 'it'},
{'snippet': 'Code for the paper "Evaluating Large Language Models Trained on '
'Code"',
'title': 'human-eval',
'link': 'https://github.com/openai/human-eval',
'engines': ['github'],
'category': 'it'},
{'snippet': 'A trend starts from "Chain of Thought Prompting Elicits '
'Reasoning in Large Language Models".',
'title': 'Chain-of-ThoughtsPapers',
'link': 'https://github.com/Timothyxxx/Chain-of-ThoughtsPapers',
'engines': ['github'],
'category': 'it'},
{'snippet': 'Mistral: A strong, northwesterly wind: Framework for transparent '
'and accessible large-scale language model training, built with '
'Hugging Face 🤗 Transformers.',
'title': 'mistral',
'link': 'https://github.com/stanford-crfm/mistral',
'engines': ['github'],
'category': 'it'},
{'snippet': 'A prize for finding tasks that cause large language models to '
'show inverse scaling',
'title': 'prize',
'link': 'https://github.com/inverse-scaling/prize',
'engines': ['github'], | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\searx_search.html" |
aec52e22b7f2-11 | 'engines': ['github'],
'category': 'it'},
{'snippet': 'Optimus: the first large-scale pre-trained VAE language model',
'title': 'Optimus',
'link': 'https://github.com/ChunyuanLI/Optimus',
'engines': ['github'],
'category': 'it'},
{'snippet': 'Seminar on Large Language Models (COMP790-101 at UNC Chapel '
'Hill, Fall 2022)',
'title': 'llm-seminar',
'link': 'https://github.com/craffel/llm-seminar',
'engines': ['github'],
'category': 'it'},
{'snippet': 'A central, open resource for data and tools related to '
'chain-of-thought reasoning in large language models. Developed @ '
'Samwald research group: https://samwald.info/',
'title': 'ThoughtSource',
'link': 'https://github.com/OpenBioLink/ThoughtSource',
'engines': ['github'],
'category': 'it'},
{'snippet': 'A comprehensive list of papers using large language/multi-modal '
'models for Robotics/RL, including papers, codes, and related '
'websites',
'title': 'Awesome-LLM-Robotics',
'link': 'https://github.com/GT-RIPL/Awesome-LLM-Robotics',
'engines': ['github'],
'category': 'it'},
{'snippet': 'Tools for curating biomedical training data for large-scale '
'language modeling',
'title': 'biomedical',
'link': 'https://github.com/bigscience-workshop/biomedical', | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\searx_search.html" |
aec52e22b7f2-12 | 'link': 'https://github.com/bigscience-workshop/biomedical',
'engines': ['github'],
'category': 'it'},
{'snippet': 'ChatGPT @ Home: Large Language Model (LLM) chatbot application, '
'written by ChatGPT',
'title': 'ChatGPT-at-Home',
'link': 'https://github.com/Sentdex/ChatGPT-at-Home',
'engines': ['github'],
'category': 'it'},
{'snippet': 'Design and Deploy Large Language Model Apps',
'title': 'dust',
'link': 'https://github.com/dust-tt/dust',
'engines': ['github'],
'category': 'it'},
{'snippet': 'Polyglot: Large Language Models of Well-balanced Competence in '
'Multi-languages',
'title': 'polyglot',
'link': 'https://github.com/EleutherAI/polyglot',
'engines': ['github'],
'category': 'it'},
{'snippet': 'Code release for "Learning Video Representations from Large '
'Language Models"',
'title': 'LaViLa',
'link': 'https://github.com/facebookresearch/LaViLa',
'engines': ['github'],
'category': 'it'},
{'snippet': 'SmoothQuant: Accurate and Efficient Post-Training Quantization '
'for Large Language Models',
'title': 'smoothquant',
'link': 'https://github.com/mit-han-lab/smoothquant',
'engines': ['github'],
'category': 'it'}, | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\searx_search.html" |
aec52e22b7f2-13 | 'engines': ['github'],
'category': 'it'},
{'snippet': 'This repository contains the code, data, and models of the paper '
'titled "XL-Sum: Large-Scale Multilingual Abstractive '
'Summarization for 44 Languages" published in Findings of the '
'Association for Computational Linguistics: ACL-IJCNLP 2021.',
'title': 'xl-sum',
'link': 'https://github.com/csebuetnlp/xl-sum',
'engines': ['github'],
'category': 'it'}]
previous
Requests
next
SerpAPI
Contents
SearxNG Search API
Custom Parameters
Obtaining results with metadata
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Mar 24, 2023. | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\searx_search.html" |
c09de65dff34-0 | .ipynb
.pdf
SerpAPI
Contents
Custom Parameters
SerpAPI#
This notebook goes over how to use the SerpAPI component to search the web.
from langchain.utilities import SerpAPIWrapper
search = SerpAPIWrapper()
search.run("Obama's first name?")
'Barack Hussein Obama II'
Custom Parameters#
You can also customize the SerpAPI wrapper with arbitrary parameters. For example, in the below example we will use bing instead of google.
params = {
"engine": "bing",
"gl": "us",
"hl": "en",
}
search = SerpAPIWrapper(params=params)
search.run("Obama's first name?")
'Barack Hussein Obama II is an American politician who served as the 44th president of the United States from 2009 to 2017. A member of the Democratic Party, Obama was the first African-American presi…New content will be added above the current area of focus upon selectionBarack Hussein Obama II is an American politician who served as the 44th president of the United States from 2009 to 2017. A member of the Democratic Party, Obama was the first African-American president of the United States. He previously served as a U.S. senator from Illinois from 2005 to 2008 and as an Illinois state senator from 1997 to 2004, and previously worked as a civil rights lawyer before entering politics.Wikipediabarackobama.com'
previous
SearxNG Search API
next
Wolfram Alpha
Contents
Custom Parameters
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Mar 24, 2023. | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\serpapi.html" |
287fb305192e-0 | .ipynb
.pdf
Wolfram Alpha
Wolfram Alpha#
This notebook goes over how to use the wolfram alpha component.
First, you need to set up your Wolfram Alpha developer account and get your APP ID:
Go to wolfram alpha and sign up for a developer account here
Create an app and get your APP ID
pip install wolframalpha
Then we will need to set some environment variables:
Save your APP ID into WOLFRAM_ALPHA_APPID env variable
pip install wolframalpha
import os
os.environ["WOLFRAM_ALPHA_APPID"] = ""
from langchain.utilities.wolfram_alpha import WolframAlphaAPIWrapper
wolfram = WolframAlphaAPIWrapper()
wolfram.run("What is 2x+5 = -3x + 7?")
'x = 2/5'
previous
SerpAPI
next
Zapier Natural Language Actions API
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Mar 24, 2023. | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\wolfram_alpha.html" |
715df4c75fc7-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 Zapier’s platform through a natural language API interface.
NLA supports apps like Gmail, Salesforce, Trello, Slack, Asana, HubSpot, Google Sheets, Microsoft Teams, and thousands more apps: https://zapier.com/apps
Zapier NLA handles ALL the underlying API auth and translation from natural language –> underlying API call –> return simplified output for LLMs. The key idea is you, or your users, expose a set of actions via an oauth-like setup window, which you can then query and execute via a REST API.
NLA offers both API Key and OAuth for signing NLA API requests.
Server-side (API Key): for quickly getting started, testing, and production scenarios where LangChain will only use actions exposed in the developer’s Zapier account (and will use the developer’s connected accounts on Zapier.com)
User-facing (Oauth): for production scenarios where you are deploying an end-user facing application and LangChain needs access to end-user’s exposed actions and connected accounts on Zapier.com
This quick start will focus on the server-side use case for brevity. Review full docs or reach out to [email protected] for user-facing oauth developer support.
This example goes over how to use the Zapier integration with a SimpleSequentialChain, then an Agent.
In code, below:
%load_ext autoreload
%autoreload 2
import os
# get from https://platform.openai.com/ | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\zapier.html" |
715df4c75fc7-1 | %autoreload 2
import os
# get from https://platform.openai.com/
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 below.
from langchain.llms import OpenAI
from langchain.agents import initialize_agent
from langchain.agents.agent_toolkits import ZapierToolkit
from langchain.utilities.zapier import ZapierNLAWrapper
## step 0. expose gmail 'find email' and slack 'send channel message' actions
# first go here, log in, expose (enable) the two actions: https://nla.zapier.com/demo/start -- for this example, can leave all fields "Have AI guess"
# in an oauth scenario, you'd get your own <provider> id (instead of 'demo') which you route your users through first
llm = OpenAI(temperature=0)
zapier = ZapierNLAWrapper()
toolkit = ZapierToolkit.from_zapier_nla_wrapper(zapier)
agent = initialize_agent(toolkit.get_tools(), llm, agent="zero-shot-react-description", verbose=True)
agent.run("Summarize the last email I received regarding Silicon Valley Bank. Send the summary to the #test-zapier channel in slack.")
> Entering new AgentExecutor chain...
I need to find the email and summarize it.
Action: Gmail: Find Email
Action Input: Find the latest email from Silicon Valley Bank | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\zapier.html" |
715df4c75fc7-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": "[email protected]", "body_plain": "Dear Clients, After chaotic, tumultuous & stressful days, we have clarity on path for SVB, FDIC is fully insuring all deposits & have an ask for clients & partners as we rebuild. Tim Mayopoulos <https://eml.svb.com/NjEwLUtBSy0yNjYAAAGKgoxUeBCLAyF_NxON97X4rKEaNBLG", "reply_to__email": "[email protected]", "subject": "Meet the new CEO Tim Mayopoulos", "date": "Tue, 14 Mar 2023 23:42:29 -0500 (CDT)", "message_url": "https://mail.google.com/mail/u/0/#inbox/186e393b13cfdf0a", "attachment_count": "0", "to__emails": "[email protected]", "message_id": "186e393b13cfdf0a", "labels": "IMPORTANT, CATEGORY_UPDATES, INBOX"}
Thought: I need to summarize the email and send it to the #test-zapier channel in Slack.
Action: Slack: Send Channel Message
Action Input: Send a slack message to the #test-zapier channel with the 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." | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\zapier.html" |
715df4c75fc7-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", "message__bot_profile__name": "Zapier", "message__team": "T04F8K3FZB5", "message__bot_id": "B04TRV4R74K", "message__bot_profile__deleted": "false", "message__bot_profile__app_id": "A024R9PQM", "ts_time": "2023-03-15T05:58:52Z", "message__bot_profile__icons__image_36": "https://avatars.slack-edge.com/2022-08-02/3888649620612_f864dc1bb794cf7d82b0_36.png", "message__blocks[]block_id": "kdZZ", "message__blocks[]elements[]type": "['rich_text_section']"}
Thought: I now know the final answer.
Final Answer: I have sent a summary of the last email from Silicon Valley Bank to the #test-zapier channel in Slack.
> Finished chain.
'I have sent a summary of the last email from Silicon Valley Bank to the #test-zapier channel in Slack.'
Example with SimpleSequentialChain#
If you need more explicit control, use a chain, like below.
from langchain.llms import OpenAI
from langchain.chains import LLMChain, TransformChain, SimpleSequentialChain
from langchain.prompts import PromptTemplate
from langchain.tools.zapier.tool import ZapierNLARunAction | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\zapier.html" |
715df4c75fc7-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 fields "Have AI guess"
# in an oauth scenario, you'd get your own <provider> id (instead of 'demo') which you route your users through first
actions = ZapierNLAWrapper().list()
## step 1. gmail find email
GMAIL_SEARCH_INSTRUCTIONS = "Grab the latest email from Silicon Valley Bank"
def nla_gmail(inputs):
action = next((a for a in actions if a["description"].startswith("Gmail: Find Email")), None)
return {"email_data": ZapierNLARunAction(action_id=action["id"], zapier_description=action["description"], params_schema=action["params"]).run(inputs["instructions"])}
gmail_chain = TransformChain(input_variables=["instructions"], output_variables=["email_data"], transform=nla_gmail)
## step 2. generate draft reply
template = """You are an assisstant who drafts replies to an incoming email. Output draft reply in plain text (not JSON).
Incoming email:
{email_data}
Draft email reply:"""
prompt_template = PromptTemplate(input_variables=["email_data"], template=template)
reply_chain = LLMChain(llm=OpenAI(temperature=.7), prompt=prompt_template)
## step 3. send draft reply via a slack direct message
SLACK_HANDLE = "@Ankush Gola"
def nla_slack(inputs): | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\zapier.html" |
715df4c75fc7-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_description=action["description"], params_schema=action["params"]).run(instructions)}
slack_chain = TransformChain(input_variables=["draft_reply"], output_variables=["slack_data"], transform=nla_slack)
## finally, execute
overall_chain = SimpleSequentialChain(chains=[gmail_chain, reply_chain, slack_chain], verbose=True)
overall_chain.run(GMAIL_SEARCH_INSTRUCTIONS)
> Entering new SimpleSequentialChain chain... | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\zapier.html" |
715df4c75fc7-6 | overall_chain.run(GMAIL_SEARCH_INSTRUCTIONS)
> Entering new SimpleSequentialChain chain...
{"from__name": "Silicon Valley Bridge Bank, N.A.", "from__email": "[email protected]", "body_plain": "Dear Clients, After chaotic, tumultuous & stressful days, we have clarity on path for SVB, FDIC is fully insuring all deposits & have an ask for clients & partners as we rebuild. Tim Mayopoulos <https://eml.svb.com/NjEwLUtBSy0yNjYAAAGKgoxUeBCLAyF_NxON97X4rKEaNBLG", "reply_to__email": "[email protected]", "subject": "Meet the new CEO Tim Mayopoulos", "date": "Tue, 14 Mar 2023 23:42:29 -0500 (CDT)", "message_url": "https://mail.google.com/mail/u/0/#inbox/186e393b13cfdf0a", "attachment_count": "0", "to__emails": "[email protected]", "message_id": "186e393b13cfdf0a", "labels": "IMPORTANT, CATEGORY_UPDATES, INBOX"}
Dear Silicon Valley Bridge Bank,
Thank 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.
Best regards,
[Your Name] | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\zapier.html" |
715df4c75fc7-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[Your Name]", "message__permalink": "https://langchain.slack.com/archives/D04TKF5BBHU/p1678859968241629", "channel": "D04TKF5BBHU", "message__bot_profile__name": "Zapier", "message__team": "T04F8K3FZB5", "message__bot_id": "B04TRV4R74K", "message__bot_profile__deleted": "false", "message__bot_profile__app_id": "A024R9PQM", "ts_time": "2023-03-15T05:59:28Z", "message__blocks[]block_id": "p7i", "message__blocks[]elements[]elements[]type": "[['text']]", "message__blocks[]elements[]type": "['rich_text_section']"}
> Finished chain. | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\zapier.html" |
715df4c75fc7-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[Your Name]", "message__permalink": "https://langchain.slack.com/archives/D04TKF5BBHU/p1678859968241629", "channel": "D04TKF5BBHU", "message__bot_profile__name": "Zapier", "message__team": "T04F8K3FZB5", "message__bot_id": "B04TRV4R74K", "message__bot_profile__deleted": "false", "message__bot_profile__app_id": "A024R9PQM", "ts_time": "2023-03-15T05:59:28Z", "message__blocks[]block_id": "p7i", "message__blocks[]elements[]elements[]type": "[[\'text\']]", "message__blocks[]elements[]type": "[\'rich_text_section\']"}'
previous
Wolfram Alpha
next
Utilities
Contents
Zapier Natural Language Actions API
Example with Agent
Example with SimpleSequentialChain
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Mar 24, 2023. | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\modules\\utils\\examples\\zapier.html" |
651a4f35b5e2-0 | .md
.pdf
Installation
Contents
Official Releases
Installing from source
Installation#
Official Releases#
LangChain is available on PyPi, so to it is easily installable with:
pip install langchain
That will install the bare minimum requirements of LangChain.
A lot of the value of LangChain comes when integrating it with various model providers, datastores, etc.
By default, the dependencies needed to do that are NOT installed.
However, there are two other ways to install LangChain that do bring in those dependencies.
To install modules needed for the common LLM providers, run:
pip install langchain[llms]
To install all modules needed for all integrations, run:
pip install langchain[all]
Note that if you are using zsh, you’ll need to quote square brackets when passing them as an argument to a command, for example:
pip install 'langchain[all]'
Installing from source#
If you want to install from source, you can do so by cloning the repo and running:
pip install -e .
previous
Model Comparison
next
Integrations
Contents
Official Releases
Installing from source
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Mar 24, 2023. | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\reference\\installation.html" |
8fe4c29c4a8c-0 | .md
.pdf
Integrations
Integrations#
Besides the installation of this python package, you will also need to install packages and set environment variables depending on which chains you want to use.
Note: the reason these packages are not included in the dependencies by default is that as we imagine scaling this package, we do not want to force dependencies that are not needed.
The following use cases require specific installs and api keys:
OpenAI:
Install requirements with pip install openai
Get an OpenAI api key and either set it as an environment variable (OPENAI_API_KEY) or pass it to the LLM constructor as openai_api_key.
Cohere:
Install requirements with pip install cohere
Get a Cohere api key and either set it as an environment variable (COHERE_API_KEY) or pass it to the LLM constructor as cohere_api_key.
GooseAI:
Install requirements with pip install openai
Get an GooseAI api key and either set it as an environment variable (GOOSEAI_API_KEY) or pass it to the LLM constructor as gooseai_api_key.
Hugging Face Hub
Install requirements with pip install huggingface_hub
Get a Hugging Face Hub api token and either set it as an environment variable (HUGGINGFACEHUB_API_TOKEN) or pass it to the LLM constructor as huggingfacehub_api_token.
Petals:
Install requirements with pip install petals
Get an GooseAI api key and either set it as an environment variable (HUGGINGFACE_API_KEY) or pass it to the LLM constructor as huggingface_api_key.
CerebriumAI:
Install requirements with pip install cerebrium
Get a Cerebrium api key and either set it as an environment variable (CEREBRIUMAI_API_KEY) or pass it to the LLM constructor as cerebriumai_api_key. | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\reference\\integrations.html" |
8fe4c29c4a8c-1 | PromptLayer:
Install requirements with pip install promptlayer (be sure to be on version 0.1.62 or higher)
Get an API key from promptlayer.com and set it using promptlayer.api_key=<API KEY>
SerpAPI:
Install requirements with pip install google-search-results
Get a SerpAPI api key and either set it as an environment variable (SERPAPI_API_KEY) or pass it to the LLM constructor as serpapi_api_key.
GoogleSearchAPI:
Install requirements with pip install google-api-python-client
Get a Google api key and either set it as an environment variable (GOOGLE_API_KEY) or pass it to the LLM constructor as google_api_key. You will also need to set the GOOGLE_CSE_ID environment variable to your custom search engine id. You can pass it to the LLM constructor as google_cse_id as well.
WolframAlphaAPI:
Install requirements with pip install wolframalpha
Get a Wolfram Alpha api key and either set it as an environment variable (WOLFRAM_ALPHA_APPID) or pass it to the LLM constructor as wolfram_alpha_appid.
NatBot:
Install requirements with pip install playwright
Wikipedia:
Install requirements with pip install wikipedia
Elasticsearch:
Install requirements with pip install elasticsearch
Set up Elasticsearch backend. If you want to do locally, this is a good guide.
FAISS:
Install requirements with pip install faiss for Python 3.7 and pip install faiss-cpu for Python 3.10+.
Manifest:
Install requirements with pip install manifest-ml (Note: this is only available in Python 3.8+ currently).
OpenSearch:
Install requirements with pip install opensearch-py
If you want to set up OpenSearch on your local, here
DeepLake:
Install requirements with pip install deeplake | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\reference\\integrations.html" |
8fe4c29c4a8c-2 | DeepLake:
Install requirements with pip install deeplake
If you are using the NLTKTextSplitter or the SpacyTextSplitter, you will also need to install the appropriate models. For example, if you want to use the SpacyTextSplitter, you will need to install the en_core_web_sm model with python -m spacy download en_core_web_sm. Similarly, if you want to use the NLTKTextSplitter, you will need to install the punkt model with python -m nltk.downloader punkt.
previous
Installation
next
API References
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Mar 24, 2023. | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\reference\\integrations.html" |
e1fa3588078f-0 | .rst
.pdf
Prompts
Prompts#
The reference guides here all relate to objects for working with Prompts.
PromptTemplates
Example Selector
previous
Output Parsers
next
PromptTemplates
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Mar 24, 2023. | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\reference\\prompts.html" |
67117ae38908-0 | .rst
.pdf
Utilities
Utilities#
There are a lot of different utilities that LangChain provides integrations for
These guides go over how to use them.
These can largely be grouped into two categories: generic utilities, and then utilities for working with larger text documents.
Generic Utilities
Python REPL
SerpAPI
SearxNG Search
Utilities for working with Documents
Docstore
Text Splitter
Embeddings
VectorStores
previous
Zapier Natural Language Actions API
next
Python REPL
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Mar 24, 2023. | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\reference\\utils.html" |
9d7728c99c60-0 | .rst
.pdf
Agents
Agents#
Interface for agents.
pydantic model langchain.agents.Agent[source]#
Class responsible for calling the language model and deciding the action.
This is driven by an LLMChain. The prompt in the LLMChain MUST include
a variable called “agent_scratchpad” where the agent can put its
intermediary work.
field allowed_tools: Optional[List[str]] = None#
field llm_chain: langchain.chains.llm.LLMChain [Required]#
field return_values: List[str] = ['output']#
async aplan(intermediate_steps: List[Tuple[langchain.schema.AgentAction, str]], **kwargs: Any) → Union[langchain.schema.AgentAction, langchain.schema.AgentFinish][source]#
Given input, decided what to do.
Parameters
intermediate_steps – Steps the LLM has taken to date,
along with observations
**kwargs – User inputs.
Returns
Action specifying what tool to use.
abstract classmethod create_prompt(tools: Sequence[langchain.tools.base.BaseTool]) → langchain.prompts.base.BasePromptTemplate[source]#
Create a prompt for this class.
dict(**kwargs: Any) → Dict[source]#
Return dictionary representation of agent.
classmethod from_llm_and_tools(llm: langchain.llms.base.BaseLLM, tools: Sequence[langchain.tools.base.BaseTool], callback_manager: Optional[langchain.callbacks.base.BaseCallbackManager] = None, **kwargs: Any) → langchain.agents.agent.Agent[source]#
Construct an agent from an LLM and tools.
get_full_inputs(intermediate_steps: List[Tuple[langchain.schema.AgentAction, str]], **kwargs: Any) → Dict[str, Any][source]#
Create the full inputs for the LLMChain from intermediate steps. | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\reference\\modules\\agents.html" |
9d7728c99c60-1 | Create the full inputs for the LLMChain from intermediate steps.
plan(intermediate_steps: List[Tuple[langchain.schema.AgentAction, str]], **kwargs: Any) → Union[langchain.schema.AgentAction, langchain.schema.AgentFinish][source]#
Given input, decided what to do.
Parameters
intermediate_steps – Steps the LLM has taken to date,
along with observations
**kwargs – User inputs.
Returns
Action specifying what tool to use.
prepare_for_new_call() → None[source]#
Prepare the agent for new call, if needed.
return_stopped_response(early_stopping_method: str, intermediate_steps: List[Tuple[langchain.schema.AgentAction, str]], **kwargs: Any) → langchain.schema.AgentFinish[source]#
Return response when agent has been stopped due to max iterations.
save(file_path: Union[pathlib.Path, str]) → None[source]#
Save the agent.
Parameters
file_path – Path to file to save the agent to.
Example:
.. code-block:: python
# If working with agent executor
agent.agent.save(file_path=”path/agent.yaml”)
property finish_tool_name: str#
Name of the tool to use to finish the chain.
abstract property llm_prefix: str#
Prefix to append the LLM call with.
abstract property observation_prefix: str#
Prefix to append the observation with.
pydantic model langchain.agents.AgentExecutor[source]#
Consists of an agent using tools.
Validators
set_callback_manager » callback_manager
set_verbose » verbose
validate_tools » all fields
field agent: Agent [Required]#
field early_stopping_method: str = 'force'#
field max_iterations: Optional[int] = 15#
field return_intermediate_steps: bool = False#
field tools: Sequence[BaseTool] [Required]# | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\reference\\modules\\agents.html" |
9d7728c99c60-2 | field tools: Sequence[BaseTool] [Required]#
classmethod from_agent_and_tools(agent: langchain.agents.agent.Agent, tools: Sequence[langchain.tools.base.BaseTool], callback_manager: Optional[langchain.callbacks.base.BaseCallbackManager] = None, **kwargs: Any) → langchain.agents.agent.AgentExecutor[source]#
Create from agent and tools.
save(file_path: Union[pathlib.Path, str]) → None[source]#
Raise error - saving not supported for Agent Executors.
save_agent(file_path: Union[pathlib.Path, str]) → None[source]#
Save the underlying agent.
pydantic model langchain.agents.ConversationalAgent[source]#
An agent designed to hold a conversation in addition to using tools.
field ai_prefix: str = 'AI'# | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\reference\\modules\\agents.html" |
9d7728c99c60-3 | classmethod create_prompt(tools: Sequence[langchain.tools.base.BaseTool], prefix: str = 'Assistant is a large language model trained by OpenAI.\n\nAssistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.\n\nAssistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.\n\nOverall, Assistant is a powerful tool that can help with a wide range of | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\reference\\modules\\agents.html" |
9d7728c99c60-4 | powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.\n\nTOOLS:\n------\n\nAssistant has access to the following tools:', suffix: str = 'Begin!\n\nPrevious conversation history:\n{chat_history}\n\nNew input: {input}\n{agent_scratchpad}', format_instructions: str = 'To use a tool, please use the following format:\n\n```\nThought: Do I need to use a tool? Yes\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n```\n\nWhen you have a response to say to the Human, or if you do not need to use a tool, you MUST use the format:\n\n```\nThought: Do I need to use a tool? No\n{ai_prefix}: [your response here]\n```', ai_prefix: str = 'AI', human_prefix: str = 'Human', input_variables: | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\reference\\modules\\agents.html" |
9d7728c99c60-5 | 'AI', human_prefix: str = 'Human', input_variables: Optional[List[str]] = None) → langchain.prompts.prompt.PromptTemplate[source]# | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\reference\\modules\\agents.html" |
9d7728c99c60-6 | Create prompt in the style of the zero shot agent.
Parameters
tools – List of tools the agent will have access to, used to format the
prompt.
prefix – String to put before the list of tools.
suffix – String to put after the list of tools.
ai_prefix – String to use before AI output.
human_prefix – String to use before human output.
input_variables – List of input variables the final prompt will expect.
Returns
A PromptTemplate with the template assembled from the pieces here. | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\reference\\modules\\agents.html" |
9d7728c99c60-7 | classmethod from_llm_and_tools(llm: langchain.llms.base.BaseLLM, tools: Sequence[langchain.tools.base.BaseTool], callback_manager: Optional[langchain.callbacks.base.BaseCallbackManager] = None, prefix: str = 'Assistant is a large language model trained by OpenAI.\n\nAssistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.\n\nAssistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\reference\\modules\\agents.html" |
9d7728c99c60-8 | and provide explanations and descriptions on a wide range of topics.\n\nOverall, Assistant is a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.\n\nTOOLS:\n------\n\nAssistant has access to the following tools:', suffix: str = 'Begin!\n\nPrevious conversation history:\n{chat_history}\n\nNew input: {input}\n{agent_scratchpad}', format_instructions: str = 'To use a tool, please use the following format:\n\n```\nThought: Do I need to use a tool? Yes\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n```\n\nWhen you have a response to say to the Human, or if you do not need to use a tool, you MUST use the format:\n\n```\nThought: Do I need to use a tool? No\n{ai_prefix}: [your response | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\reference\\modules\\agents.html" |
9d7728c99c60-9 | to use a tool? No\n{ai_prefix}: [your response here]\n```', ai_prefix: str = 'AI', human_prefix: str = 'Human', input_variables: Optional[List[str]] = None, **kwargs: Any) → langchain.agents.agent.Agent[source]# | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\reference\\modules\\agents.html" |
9d7728c99c60-10 | Construct an agent from an LLM and tools.
property finish_tool_name: str#
Name of the tool to use to finish the chain.
property llm_prefix: str#
Prefix to append the llm call with.
property observation_prefix: str#
Prefix to append the observation with.
pydantic model langchain.agents.MRKLChain[source]#
Chain that implements the MRKL system.
Example
from langchain import OpenAI, MRKLChain
from langchain.chains.mrkl.base import ChainConfig
llm = OpenAI(temperature=0)
prompt = PromptTemplate(...)
chains = [...]
mrkl = MRKLChain.from_chains(llm=llm, prompt=prompt)
Validators
set_callback_manager » callback_manager
set_verbose » verbose
validate_tools » all fields
field agent: Agent [Required]#
field callback_manager: BaseCallbackManager [Optional]#
field early_stopping_method: str = 'force'#
field max_iterations: Optional[int] = 15#
field memory: Optional[BaseMemory] = None#
field return_intermediate_steps: bool = False#
field tools: Sequence[BaseTool] [Required]#
field verbose: bool [Optional]#
classmethod from_chains(llm: langchain.llms.base.BaseLLM, chains: List[langchain.agents.mrkl.base.ChainConfig], **kwargs: Any) → langchain.agents.agent.AgentExecutor[source]#
User friendly way to initialize the MRKL chain.
This is intended to be an easy way to get up and running with the
MRKL chain.
Parameters
llm – The LLM to use as the agent LLM.
chains – The chains the MRKL system has access to.
**kwargs – parameters to be passed to initialization.
Returns
An initialized MRKL chain.
Example | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\reference\\modules\\agents.html" |
9d7728c99c60-11 | Returns
An initialized MRKL chain.
Example
from langchain import LLMMathChain, OpenAI, SerpAPIWrapper, MRKLChain
from langchain.chains.mrkl.base import ChainConfig
llm = OpenAI(temperature=0)
search = SerpAPIWrapper()
llm_math_chain = LLMMathChain(llm=llm)
chains = [
ChainConfig(
action_name = "Search",
action=search.search,
action_description="useful for searching"
),
ChainConfig(
action_name="Calculator",
action=llm_math_chain.run,
action_description="useful for doing math"
)
]
mrkl = MRKLChain.from_chains(llm, chains)
pydantic model langchain.agents.ReActChain[source]#
Chain that implements the ReAct paper.
Example
from langchain import ReActChain, OpenAI
react = ReAct(llm=OpenAI())
Validators
set_callback_manager » callback_manager
set_verbose » verbose
validate_tools » all fields
field agent: Agent [Required]#
field callback_manager: BaseCallbackManager [Optional]#
field early_stopping_method: str = 'force'#
field max_iterations: Optional[int] = 15#
field memory: Optional[BaseMemory] = None#
field return_intermediate_steps: bool = False#
field tools: Sequence[BaseTool] [Required]#
field verbose: bool [Optional]#
pydantic model langchain.agents.ReActTextWorldAgent[source]#
Agent for the ReAct TextWorld chain.
field i: int = 1#
classmethod create_prompt(tools: Sequence[langchain.tools.base.BaseTool]) → langchain.prompts.base.BasePromptTemplate[source]#
Return default prompt. | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\reference\\modules\\agents.html" |
9d7728c99c60-12 | Return default prompt.
pydantic model langchain.agents.SelfAskWithSearchChain[source]#
Chain that does self ask with search.
Example
from langchain import SelfAskWithSearchChain, OpenAI, GoogleSerperAPIWrapper
search_chain = GoogleSerperAPIWrapper()
self_ask = SelfAskWithSearchChain(llm=OpenAI(), search_chain=search_chain)
Validators
set_callback_manager » callback_manager
set_verbose » verbose
validate_tools » all fields
field agent: Agent [Required]#
field callback_manager: BaseCallbackManager [Optional]#
field early_stopping_method: str = 'force'#
field max_iterations: Optional[int] = 15#
field memory: Optional[BaseMemory] = None#
field return_intermediate_steps: bool = False#
field tools: Sequence[BaseTool] [Required]#
field verbose: bool [Optional]#
pydantic model langchain.agents.Tool[source]#
Tool that takes in function or coroutine directly.
Validators
set_callback_manager » callback_manager
field coroutine: Optional[Callable[[str], Awaitable[str]]] = None#
field description: str = ''#
field func: Callable[[str], str] [Required]#
pydantic model langchain.agents.ZeroShotAgent[source]#
Agent for the MRKL chain.
field allowed_tools: Optional[List[str]] = None#
field llm_chain: langchain.chains.llm.LLMChain [Required]#
field return_values: List[str] = ['output']# | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\reference\\modules\\agents.html" |
9d7728c99c60-13 | field return_values: List[str] = ['output']#
classmethod create_prompt(tools: Sequence[langchain.tools.base.BaseTool], prefix: str = 'Answer the following questions as best you can. You have access to the following tools:', suffix: str = 'Begin!\n\nQuestion: {input}\nThought:{agent_scratchpad}', format_instructions: str = 'Use the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question', input_variables: Optional[List[str]] = None) → langchain.prompts.prompt.PromptTemplate[source]#
Create prompt in the style of the zero shot agent.
Parameters
tools – List of tools the agent will have access to, used to format the
prompt.
prefix – String to put before the list of tools.
suffix – String to put after the list of tools.
input_variables – List of input variables the final prompt will expect.
Returns
A PromptTemplate with the template assembled from the pieces here. | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\reference\\modules\\agents.html" |
9d7728c99c60-14 | Returns
A PromptTemplate with the template assembled from the pieces here.
classmethod from_llm_and_tools(llm: langchain.llms.base.BaseLLM, tools: Sequence[langchain.tools.base.BaseTool], callback_manager: Optional[langchain.callbacks.base.BaseCallbackManager] = None, prefix: str = 'Answer the following questions as best you can. You have access to the following tools:', suffix: str = 'Begin!\n\nQuestion: {input}\nThought:{agent_scratchpad}', format_instructions: str = 'Use the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question', input_variables: Optional[List[str]] = None, **kwargs: Any) → langchain.agents.agent.Agent[source]#
Construct an agent from an LLM and tools.
property llm_prefix: str#
Prefix to append the llm call with.
property observation_prefix: str#
Prefix to append the observation with.
langchain.agents.create_csv_agent(llm: langchain.llms.base.BaseLLM, path: str, pandas_kwargs: Optional[dict] = None, **kwargs: Any) → langchain.agents.agent.AgentExecutor[source]#
Create csv agent by loading to a dataframe and using pandas agent. | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\reference\\modules\\agents.html" |
9d7728c99c60-15 | langchain.agents.create_json_agent(llm: langchain.llms.base.BaseLLM, toolkit: langchain.agents.agent_toolkits.json.toolkit.JsonToolkit, callback_manager: Optional[langchain.callbacks.base.BaseCallbackManager] = None, prefix: str = 'You are an agent designed to interact with JSON.\nYour goal is to return a final answer by interacting with the JSON.\nYou have access to the following tools which help you learn more about the JSON you are interacting with.\nOnly use the below tools. Only use the information returned by the below tools to construct your final answer.\nDo not make up any information that is not contained in the JSON.\nYour input to the tools should be in the form of `data["key"][0]` where `data` is the JSON blob you are interacting with, and the syntax used is Python. \nYou should only use keys that you know for a fact exist. You must validate that a key exists by seeing it previously when calling `json_spec_list_keys`. \nIf you have not seen a key in one of those responses, you cannot use it.\nYou should only add one key at | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\reference\\modules\\agents.html" |
9d7728c99c60-16 | cannot use it.\nYou should only add one key at a time to the path. You cannot add multiple keys at once.\nIf you encounter a "KeyError", go back to the previous key, look at the available keys, and try again.\n\nIf the question does not seem to be related to the JSON, just return "I don\'t know" as the answer.\nAlways begin your interaction with the `json_spec_list_keys` tool with input "data" to see what keys exist in the JSON.\n\nNote that sometimes the value at a given path is large. In this case, you will get an error "Value is a large dictionary, should explore its keys directly".\nIn this case, you should ALWAYS follow up by using the `json_spec_list_keys` tool to see what keys exist at that path.\nDo not simply refer the user to the JSON or a section of the JSON, as this is not a valid answer. Keep digging until you find the answer and explicitly return it.\n', suffix: str = 'Begin!"\n\nQuestion: {input}\nThought: I | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\reference\\modules\\agents.html" |
9d7728c99c60-17 | = 'Begin!"\n\nQuestion: {input}\nThought: I should look at the keys that exist in data to see what I have access to\n{agent_scratchpad}', format_instructions: str = 'Use the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question', input_variables: Optional[List[str]] = None, verbose: bool = False, **kwargs: Any) → langchain.agents.agent.AgentExecutor[source]# | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\reference\\modules\\agents.html" |
9d7728c99c60-18 | Construct a json agent from an LLM and tools. | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\reference\\modules\\agents.html" |
9d7728c99c60-19 | langchain.agents.create_openapi_agent(llm: langchain.llms.base.BaseLLM, toolkit: langchain.agents.agent_toolkits.openapi.toolkit.OpenAPIToolkit, callback_manager: Optional[langchain.callbacks.base.BaseCallbackManager] = None, prefix: str = "You are an agent designed to answer questions by making web requests to an API given the openapi spec.\n\nIf the question does not seem related to the API, return I don't know. Do not make up an answer.\nOnly use information provided by the tools to construct your response.\n\nFirst, find the base URL needed to make the request.\n\nSecond, find the relevant paths needed to answer the question. Take note that, sometimes, you might need to make more than one request to more than one path to answer the question.\n\nThird, find the required parameters needed to make the request. For GET requests, these are usually URL parameters and for POST requests, these are request body parameters.\n\nFourth, make the requests needed to answer the question. Ensure that you are sending the correct parameters to the request by checking which parameters are required. For parameters with a fixed set | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\reference\\modules\\agents.html" |
9d7728c99c60-20 | which parameters are required. For parameters with a fixed set of values, please use the spec to look at which values are allowed.\n\nUse the exact parameter names as listed in the spec, do not make up any names or abbreviate the names of parameters.\nIf you get a not found error, ensure that you are using a path that actually exists in the spec.\n", suffix: str = 'Begin!"\n\nQuestion: {input}\nThought: I should explore the spec to find the base url for the API.\n{agent_scratchpad}', format_instructions: str = 'Use the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question', input_variables: Optional[List[str]] = None, verbose: bool = False, **kwargs: Any) → | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\reference\\modules\\agents.html" |
9d7728c99c60-21 | verbose: bool = False, **kwargs: Any) → langchain.agents.agent.AgentExecutor[source]# | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\reference\\modules\\agents.html" |
9d7728c99c60-22 | Construct a json agent from an LLM and tools.
langchain.agents.create_pandas_dataframe_agent(llm: langchain.llms.base.BaseLLM, df: Any, callback_manager: Optional[langchain.callbacks.base.BaseCallbackManager] = None, prefix: str = '\nYou are working with a pandas dataframe in Python. The name of the dataframe is `df`.\nYou should use the tools below to answer the question posed of you:', suffix: str = '\nThis is the result of `print(df.head())`:\n{df}\n\nBegin!\nQuestion: {input}\n{agent_scratchpad}', input_variables: Optional[List[str]] = None, verbose: bool = False, **kwargs: Any) → langchain.agents.agent.AgentExecutor[source]#
Construct a pandas agent from an LLM and dataframe. | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\reference\\modules\\agents.html" |
9d7728c99c60-23 | langchain.agents.create_sql_agent(llm: langchain.llms.base.BaseLLM, toolkit: langchain.agents.agent_toolkits.sql.toolkit.SQLDatabaseToolkit, callback_manager: Optional[langchain.callbacks.base.BaseCallbackManager] = None, prefix: str = 'You are an agent designed to interact with a SQL database.\nGiven an input question, create a syntactically correct {dialect} query to run, then look at the results of the query and return the answer.\nUnless the user specifies a specific number of examples they wish to obtain, always limit your query to at most {top_k} results.\nYou can order the results by a relevant column to return the most interesting examples in the database.\nNever query for all the columns from a specific table, only ask for a the few relevant columns given the question.\nYou have access to tools for interacting with the database.\nOnly use the below tools. Only use the information returned by the below tools to construct your final answer.\nYou MUST double check your query before executing it. If you get an error while executing a query, rewrite the query and try again.\n\nDO | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\reference\\modules\\agents.html" |
9d7728c99c60-24 | a query, rewrite the query and try again.\n\nDO NOT make any DML statements (INSERT, UPDATE, DELETE, DROP etc.) to the database.\n\nIf the question does not seem related to the database, just return "I don\'t know" as the answer.\n', suffix: str = 'Begin!\n\nQuestion: {input}\nThought: I should look at the tables in the database to see what I can query.\n{agent_scratchpad}', format_instructions: str = 'Use the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question', input_variables: Optional[List[str]] = None, top_k: int = 10, verbose: bool = False, **kwargs: Any) → langchain.agents.agent.AgentExecutor[source]# | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\reference\\modules\\agents.html" |
9d7728c99c60-25 | Construct a sql agent from an LLM and tools.
langchain.agents.create_vectorstore_agent(llm: langchain.llms.base.BaseLLM, toolkit: langchain.agents.agent_toolkits.vectorstore.toolkit.VectorStoreToolkit, callback_manager: Optional[langchain.callbacks.base.BaseCallbackManager] = None, prefix: str = 'You are an agent designed to answer questions about sets of documents.\nYou have access to tools for interacting with the documents, and the inputs to the tools are questions.\nSometimes, you will be asked to provide sources for your questions, in which case you should use the appropriate tool to do so.\nIf the question does not seem relevant to any of the tools provided, just return "I don\'t know" as the answer.\n', verbose: bool = False, **kwargs: Any) → langchain.agents.agent.AgentExecutor[source]#
Construct a vectorstore agent from an LLM and tools.
langchain.agents.create_vectorstore_router_agent(llm: langchain.llms.base.BaseLLM, toolkit: langchain.agents.agent_toolkits.vectorstore.toolkit.VectorStoreRouterToolkit, callback_manager: Optional[langchain.callbacks.base.BaseCallbackManager] = None, prefix: str = 'You are an agent designed to answer questions.\nYou have access to tools for interacting with different sources, and the inputs to the tools are questions.\nYour main task is to decide which of the tools is relevant for answering question at hand.\nFor complex questions, you can break the question down into sub questions and use tools to answers the sub questions.\n', verbose: bool = False, **kwargs: Any) → langchain.agents.agent.AgentExecutor[source]#
Construct a vectorstore router agent from an LLM and tools.
langchain.agents.get_all_tool_names() → List[str][source]#
Get a list of all possible tool names. | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\reference\\modules\\agents.html" |
9d7728c99c60-26 | Get a list of all possible tool names.
langchain.agents.initialize_agent(tools: Sequence[langchain.tools.base.BaseTool], llm: langchain.llms.base.BaseLLM, agent: Optional[str] = None, callback_manager: Optional[langchain.callbacks.base.BaseCallbackManager] = None, agent_path: Optional[str] = None, agent_kwargs: Optional[dict] = None, **kwargs: Any) → langchain.agents.agent.AgentExecutor[source]#
Load an agent executor given tools and LLM.
Parameters
tools – List of tools this agent has access to.
llm – Language model to use as the agent.
agent –
A string that specified the agent type to use. Valid options are:zero-shot-react-description
react-docstore
self-ask-with-search
conversational-react-description
chat-zero-shot-react-description,
chat-conversational-react-description,
If None and agent_path is also None, will default tozero-shot-react-description.
callback_manager – CallbackManager to use. Global callback manager is used if
not provided. Defaults to None.
agent_path – Path to serialized agent to use.
agent_kwargs – Additional key word arguments to pass to the underlying agent
**kwargs – Additional key word arguments passed to the agent executor
Returns
An agent executor
langchain.agents.load_agent(path: Union[str, pathlib.Path], **kwargs: Any) → langchain.agents.agent.Agent[source]#
Unified method for loading a agent from LangChainHub or local fs.
langchain.agents.load_tools(tool_names: List[str], llm: Optional[langchain.llms.base.BaseLLM] = None, callback_manager: Optional[langchain.callbacks.base.BaseCallbackManager] = None, **kwargs: Any) → List[langchain.tools.base.BaseTool][source]#
Load tools based on their name.
Parameters | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\reference\\modules\\agents.html" |
9d7728c99c60-27 | Load tools based on their name.
Parameters
tool_names – name of tools to load.
llm – Optional language model, may be needed to initialize certain tools.
callback_manager – Optional callback manager. If not provided, default global callback manager will be used.
Returns
List of tools.
langchain.agents.tool(*args: Union[str, Callable], return_direct: bool = False) → Callable[source]#
Make tools out of functions, can be used with or without arguments.
Requires:
Function must be of type (str) -> str
Function must have a docstring
Examples
@tool
def search_api(query: str) -> str:
# Searches the API for the query.
return
@tool("search", return_direct=True)
def search_api(query: str) -> str:
# Searches the API for the query.
return
previous
Self Ask With Search
next
Memory
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Mar 24, 2023. | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\reference\\modules\\agents.html" |
6cd8144926f9-0 | .rst
.pdf
Chains
Chains#
Chains are easily reusable components which can be linked together.
pydantic model langchain.chains.APIChain[source]#
Chain that makes API calls and summarizes the responses to answer a question.
Validators
set_callback_manager » callback_manager
set_verbose » verbose
validate_api_answer_prompt » all fields
validate_api_request_prompt » all fields
field api_answer_chain: LLMChain [Required]#
field api_docs: str [Required]#
field api_request_chain: LLMChain [Required]#
field requests_wrapper: RequestsWrapper [Required]# | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\reference\\modules\\chains.html" |
6cd8144926f9-1 | field requests_wrapper: RequestsWrapper [Required]#
classmethod from_llm_and_api_docs(llm: langchain.schema.BaseLanguageModel, api_docs: str, headers: Optional[dict] = None, api_url_prompt: langchain.prompts.base.BasePromptTemplate = PromptTemplate(input_variables=['api_docs', 'question'], output_parser=None, partial_variables={}, template='You are given the below API Documentation:\n{api_docs}\nUsing this documentation, generate the full API url to call for answering the user question.\nYou should build the API url in order to get a response that is as short as possible, while still getting the necessary information to answer the question. Pay attention to deliberately exclude any unnecessary pieces of data in the API call.\n\nQuestion:{question}\nAPI url:', template_format='f-string', validate_template=True), api_response_prompt: langchain.prompts.base.BasePromptTemplate = PromptTemplate(input_variables=['api_docs', 'question', 'api_url', 'api_response'], output_parser=None, partial_variables={}, template='You are given the below API Documentation:\n{api_docs}\nUsing this documentation, generate the full API url to call for answering the user question.\nYou should build the API url in order to get a response that is as short as possible, while still getting the necessary information to answer the question. Pay attention to deliberately exclude any unnecessary pieces of data in the API call.\n\nQuestion:{question}\nAPI url: {api_url}\n\nHere is the response from the API:\n\n{api_response}\n\nSummarize this response to answer the original question.\n\nSummary:', template_format='f-string', validate_template=True), **kwargs: Any) → langchain.chains.api.base.APIChain[source]#
Load chain from just an LLM and the api docs.
pydantic model langchain.chains.AnalyzeDocumentChain[source]# | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\reference\\modules\\chains.html" |
6cd8144926f9-2 | pydantic model langchain.chains.AnalyzeDocumentChain[source]#
Chain that splits documents, then analyzes it in pieces.
Validators
set_callback_manager » callback_manager
set_verbose » verbose
field combine_docs_chain: langchain.chains.combine_documents.base.BaseCombineDocumentsChain [Required]#
field text_splitter: langchain.text_splitter.TextSplitter [Optional]#
pydantic model langchain.chains.ChatVectorDBChain[source]#
Chain for chatting with a vector database.
Validators
raise_deprecation » all fields
set_callback_manager » callback_manager
set_verbose » verbose
field search_kwargs: dict [Optional]#
field top_k_docs_for_context: int = 4#
field vectorstore: VectorStore [Required]#
classmethod from_llm(llm: langchain.schema.BaseLanguageModel, vectorstore: langchain.vectorstores.base.VectorStore, condense_question_prompt: langchain.prompts.base.BasePromptTemplate = PromptTemplate(input_variables=['chat_history', 'question'], output_parser=None, partial_variables={}, template='Given the following conversation and a follow up question, rephrase the follow up question to be a standalone question.\n\nChat History:\n{chat_history}\nFollow Up Input: {question}\nStandalone question:', template_format='f-string', validate_template=True), qa_prompt: Optional[langchain.prompts.base.BasePromptTemplate] = None, chain_type: str = 'stuff', **kwargs: Any) → langchain.chains.conversational_retrieval.base.BaseConversationalRetrievalChain[source]#
Load chain from LLM.
pydantic model langchain.chains.ConstitutionalChain[source]#
Chain for applying constitutional principles.
Example
from langchain.llms import OpenAI
from langchain.chains import LLMChain, ConstitutionalChain
qa_prompt = PromptTemplate(
template="Q: {question} A:", | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\reference\\modules\\chains.html" |
6cd8144926f9-3 | qa_prompt = PromptTemplate(
template="Q: {question} A:",
input_variables=["question"],
)
qa_chain = LLMChain(llm=OpenAI(), prompt=qa_prompt)
constitutional_chain = ConstitutionalChain.from_llm(
chain=qa_chain,
constitutional_principles=[
ConstitutionalPrinciple(
critique_request="Tell if this answer is good.",
revision_request="Give a better answer.",
)
],
)
constitutional_chain.run(question="What is the meaning of life?")
Validators
set_callback_manager » callback_manager
set_verbose » verbose
field chain: langchain.chains.llm.LLMChain [Required]#
field constitutional_principles: List[langchain.chains.constitutional_ai.models.ConstitutionalPrinciple] [Required]#
field critique_chain: langchain.chains.llm.LLMChain [Required]#
field revision_chain: langchain.chains.llm.LLMChain [Required]# | ERROR: type should be string, got "https://langchain.readthedocs.io\\en\\latest\\reference\\modules\\chains.html" |
Subsets and Splits