id
stringlengths 14
15
| text
stringlengths 23
2.21k
| source
stringlengths 52
97
|
---|---|---|
9b61bfd69c8f-2 | Check here to get or create a PAT.Dependencies# Install required dependenciespip install clarifaiImportsHere we will be setting the personal access token. You can find your PAT under settings/security in your Clarifai account.# Please login and get your API key from https://clarifai.com/settings/securityfrom getpass import getpassCLARIFAI_PAT = getpass() ········# Import the required modulesfrom langchain.embeddings import ClarifaiEmbeddingsfrom langchain import PromptTemplate, LLMChainInputCreate a prompt template to be used with the LLM Chain:template = """Question: {question}Answer: Let's think step by step."""prompt = PromptTemplate(template=template, input_variables=["question"])SetupSet the user id and app id to the application in which the model resides. You can find a list of public models on https://clarifai.com/explore/modelsYou will have to also initialize the model id and if needed, the model version id. Some models have many versions, you can choose the one appropriate for your task.USER_ID = "openai"APP_ID = "embed"MODEL_ID = "text-embedding-ada"# You can provide a specific model version as the model_version_id arg.# MODEL_VERSION_ID = "MODEL_VERSION_ID"# Initialize a Clarifai embedding modelembeddings = ClarifaiEmbeddings( pat=CLARIFAI_PAT, user_id=USER_ID, app_id=APP_ID, model_id=MODEL_ID)text = "This is a test document."query_result = embeddings.embed_query(text)doc_result = embeddings.embed_documents([text])PreviousBedrock EmbeddingsNextCohereCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc. | https://python.langchain.com/docs/integrations/text_embedding/clarifai |
1f8a349dcb04-0 | AzureOpenAI | 🦜�🔗 Langchain
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAleph AlphaAzureOpenAIBedrock EmbeddingsClarifaiCohereDashScopeDeepInfraElasticsearchEmbaasFake EmbeddingsGoogle Cloud Platform Vertex AI PaLMGPT4AllHugging Face HubInstructEmbeddingsJinaLlama-cppLocalAIMiniMaxModelScopeMosaicML embeddingsNLP CloudOpenAISageMaker Endpoint EmbeddingsSelf Hosted EmbeddingsSentence Transformers EmbeddingsSpacy EmbeddingTensorflowHubAgent toolkitsToolsVector storesGrouped by providerIntegrationsText embedding modelsAzureOpenAIAzureOpenAILet's load the OpenAI Embedding class with environment variables set to indicate to use Azure endpoints.# set the environment variables needed for openai package to know to reach out to azureimport osos.environ["OPENAI_API_TYPE"] = "azure"os.environ["OPENAI_API_BASE"] = "https://<your-endpoint.openai.azure.com/"os.environ["OPENAI_API_KEY"] = "your AzureOpenAI key"os.environ["OPENAI_API_VERSION"] = "2023-05-15"from langchain.embeddings import OpenAIEmbeddingsembeddings = OpenAIEmbeddings(deployment="your-embeddings-deployment-name")text = "This is a test document."query_result = embeddings.embed_query(text)doc_result = embeddings.embed_documents([text])PreviousAleph AlphaNextBedrock EmbeddingsCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc. | https://python.langchain.com/docs/integrations/text_embedding/azureopenai |
c68bbe4138b6-0 | DeepInfra | 🦜�🔗 Langchain | https://python.langchain.com/docs/integrations/text_embedding/deepinfra |
c68bbe4138b6-1 | Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAleph AlphaAzureOpenAIBedrock EmbeddingsClarifaiCohereDashScopeDeepInfraElasticsearchEmbaasFake EmbeddingsGoogle Cloud Platform Vertex AI PaLMGPT4AllHugging Face HubInstructEmbeddingsJinaLlama-cppLocalAIMiniMaxModelScopeMosaicML embeddingsNLP CloudOpenAISageMaker Endpoint EmbeddingsSelf Hosted EmbeddingsSentence Transformers EmbeddingsSpacy EmbeddingTensorflowHubAgent toolkitsToolsVector storesGrouped by providerIntegrationsText embedding modelsDeepInfraDeepInfraDeepInfra is a serverless inference as a service that provides access to a variety of LLMs and embeddings models. This notebook goes over how to use LangChain with DeepInfra for text embeddings.# sign up for an account: https://deepinfra.com/login?utm_source=langchainfrom getpass import getpassDEEPINFRA_API_TOKEN = getpass() ········import osos.environ["DEEPINFRA_API_TOKEN"] = DEEPINFRA_API_TOKENfrom langchain.embeddings import DeepInfraEmbeddingsembeddings = DeepInfraEmbeddings( model_id="sentence-transformers/clip-ViT-B-32", query_instruction="", embed_instruction="",)docs = ["Dog is not a cat", "Beta is the second letter of Greek alphabet"]document_result = embeddings.embed_documents(docs)query = "What is the first letter of Greek alphabet"query_result = embeddings.embed_query(query)import numpy as npquery_numpy = np.array(query_result)for doc_res, doc | https://python.langchain.com/docs/integrations/text_embedding/deepinfra |
c68bbe4138b6-2 | numpy as npquery_numpy = np.array(query_result)for doc_res, doc in zip(document_result, docs): document_numpy = np.array(doc_res) similarity = np.dot(query_numpy, document_numpy) / ( np.linalg.norm(query_numpy) * np.linalg.norm(document_numpy) ) print(f'Cosine similarity between "{doc}" and query: {similarity}') Cosine similarity between "Dog is not a cat" and query: 0.7489097144129355 Cosine similarity between "Beta is the second letter of Greek alphabet" and query: 0.9519380640702013PreviousDashScopeNextElasticsearchCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc. | https://python.langchain.com/docs/integrations/text_embedding/deepinfra |
19becf89d37a-0 | Sentence Transformers Embeddings | 🦜�🔗 Langchain | https://python.langchain.com/docs/integrations/text_embedding/sentence_transformers |
19becf89d37a-1 | Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAleph AlphaAzureOpenAIBedrock EmbeddingsClarifaiCohereDashScopeDeepInfraElasticsearchEmbaasFake EmbeddingsGoogle Cloud Platform Vertex AI PaLMGPT4AllHugging Face HubInstructEmbeddingsJinaLlama-cppLocalAIMiniMaxModelScopeMosaicML embeddingsNLP CloudOpenAISageMaker Endpoint EmbeddingsSelf Hosted EmbeddingsSentence Transformers EmbeddingsSpacy EmbeddingTensorflowHubAgent toolkitsToolsVector storesGrouped by providerIntegrationsText embedding modelsSentence Transformers EmbeddingsSentence Transformers EmbeddingsSentenceTransformers embeddings are called using the HuggingFaceEmbeddings integration. We have also added an alias for SentenceTransformerEmbeddings for users who are more familiar with directly using that package.SentenceTransformers is a python package that can generate text and image embeddings, originating from Sentence-BERTpip install sentence_transformers > /dev/null [notice] A new release of pip is available: 23.0.1 -> 23.1.1 [notice] To update, run: pip install --upgrade pipfrom langchain.embeddings import HuggingFaceEmbeddings, SentenceTransformerEmbeddingsembeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")# Equivalent to SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2")text = "This is a test document."query_result = embeddings.embed_query(text)doc_result = embeddings.embed_documents([text, "This is not a test document."])PreviousSelf Hosted EmbeddingsNextSpacy | https://python.langchain.com/docs/integrations/text_embedding/sentence_transformers |
19becf89d37a-2 | "This is not a test document."])PreviousSelf Hosted EmbeddingsNextSpacy EmbeddingCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc. | https://python.langchain.com/docs/integrations/text_embedding/sentence_transformers |
02bd788d7267-0 | NLP Cloud | 🦜�🔗 Langchain | https://python.langchain.com/docs/integrations/text_embedding/nlp_cloud |
02bd788d7267-1 | Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAleph AlphaAzureOpenAIBedrock EmbeddingsClarifaiCohereDashScopeDeepInfraElasticsearchEmbaasFake EmbeddingsGoogle Cloud Platform Vertex AI PaLMGPT4AllHugging Face HubInstructEmbeddingsJinaLlama-cppLocalAIMiniMaxModelScopeMosaicML embeddingsNLP CloudOpenAISageMaker Endpoint EmbeddingsSelf Hosted EmbeddingsSentence Transformers EmbeddingsSpacy EmbeddingTensorflowHubAgent toolkitsToolsVector storesGrouped by providerIntegrationsText embedding modelsNLP CloudNLP CloudNLP Cloud is an artificial intelligence platform that allows you to use the most advanced AI engines, and even train your own engines with your own data. The embeddings endpoint offers several models:paraphrase-multilingual-mpnet-base-v2: Paraphrase Multilingual MPNet Base V2 is a very fast model based on Sentence Transformers that is perfectly suited for embeddings extraction in more than 50 languages (see the full list here).gpt-j: GPT-J returns advanced embeddings. It might return better results than Sentence Transformers based models (see above) but it is also much slower.dolphin: Dolphin returns advanced embeddings. It might return better results than Sentence Transformers based models (see above) but it is also much slower. It natively understands the following languages: Bulgarian, Catalan, Chinese, Croatian, Czech, Danish, Dutch, English, French, German, Hungarian, Italian, Japanese, Polish, Portuguese, Romanian, Russian, Serbian, Slovenian, Spanish, Swedish, and Ukrainian.pip install nlpcloudfrom langchain.embeddings import NLPCloudEmbeddingsimport osos.environ["NLPCLOUD_API_KEY"] | https://python.langchain.com/docs/integrations/text_embedding/nlp_cloud |
02bd788d7267-2 | import NLPCloudEmbeddingsimport osos.environ["NLPCLOUD_API_KEY"] = "xxx"nlpcloud_embd = NLPCloudEmbeddings()text = "This is a test document."query_result = nlpcloud_embd.embed_query(text)doc_result = nlpcloud_embd.embed_documents([text])PreviousMosaicML embeddingsNextOpenAICommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc. | https://python.langchain.com/docs/integrations/text_embedding/nlp_cloud |
afb6d96612e7-0 | Hugging Face Hub | 🦜�🔗 Langchain
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAleph AlphaAzureOpenAIBedrock EmbeddingsClarifaiCohereDashScopeDeepInfraElasticsearchEmbaasFake EmbeddingsGoogle Cloud Platform Vertex AI PaLMGPT4AllHugging Face HubInstructEmbeddingsJinaLlama-cppLocalAIMiniMaxModelScopeMosaicML embeddingsNLP CloudOpenAISageMaker Endpoint EmbeddingsSelf Hosted EmbeddingsSentence Transformers EmbeddingsSpacy EmbeddingTensorflowHubAgent toolkitsToolsVector storesGrouped by providerIntegrationsText embedding modelsHugging Face HubHugging Face HubLet's load the Hugging Face Embedding class.from langchain.embeddings import HuggingFaceEmbeddingsembeddings = HuggingFaceEmbeddings()text = "This is a test document."query_result = embeddings.embed_query(text)doc_result = embeddings.embed_documents([text])PreviousGPT4AllNextInstructEmbeddingsCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc. | https://python.langchain.com/docs/integrations/text_embedding/huggingfacehub |
a2b0acbf399d-0 | Jina | 🦜�🔗 Langchain
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAleph AlphaAzureOpenAIBedrock EmbeddingsClarifaiCohereDashScopeDeepInfraElasticsearchEmbaasFake EmbeddingsGoogle Cloud Platform Vertex AI PaLMGPT4AllHugging Face HubInstructEmbeddingsJinaLlama-cppLocalAIMiniMaxModelScopeMosaicML embeddingsNLP CloudOpenAISageMaker Endpoint EmbeddingsSelf Hosted EmbeddingsSentence Transformers EmbeddingsSpacy EmbeddingTensorflowHubAgent toolkitsToolsVector storesGrouped by providerIntegrationsText embedding modelsJinaJinaLet's load the Jina Embedding class.from langchain.embeddings import JinaEmbeddingsembeddings = JinaEmbeddings( jina_auth_token=jina_auth_token, model_name="ViT-B-32::openai")text = "This is a test document."query_result = embeddings.embed_query(text)doc_result = embeddings.embed_documents([text])In the above example, ViT-B-32::openai, OpenAI's pretrained ViT-B-32 model is used. For a full list of models, see here.PreviousInstructEmbeddingsNextLlama-cppCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc. | https://python.langchain.com/docs/integrations/text_embedding/jina |
2670fa9ca3b6-0 | InstructEmbeddings | 🦜�🔗 Langchain
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAleph AlphaAzureOpenAIBedrock EmbeddingsClarifaiCohereDashScopeDeepInfraElasticsearchEmbaasFake EmbeddingsGoogle Cloud Platform Vertex AI PaLMGPT4AllHugging Face HubInstructEmbeddingsJinaLlama-cppLocalAIMiniMaxModelScopeMosaicML embeddingsNLP CloudOpenAISageMaker Endpoint EmbeddingsSelf Hosted EmbeddingsSentence Transformers EmbeddingsSpacy EmbeddingTensorflowHubAgent toolkitsToolsVector storesGrouped by providerIntegrationsText embedding modelsInstructEmbeddingsInstructEmbeddingsLet's load the HuggingFace instruct Embeddings class.from langchain.embeddings import HuggingFaceInstructEmbeddingsembeddings = HuggingFaceInstructEmbeddings( query_instruction="Represent the query for retrieval: ") load INSTRUCTOR_Transformer max_seq_length 512text = "This is a test document."query_result = embeddings.embed_query(text)PreviousHugging Face HubNextJinaCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc. | https://python.langchain.com/docs/integrations/text_embedding/instruct_embeddings |
db7f24559a92-0 | Llama-cpp | 🦜�🔗 Langchain
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAleph AlphaAzureOpenAIBedrock EmbeddingsClarifaiCohereDashScopeDeepInfraElasticsearchEmbaasFake EmbeddingsGoogle Cloud Platform Vertex AI PaLMGPT4AllHugging Face HubInstructEmbeddingsJinaLlama-cppLocalAIMiniMaxModelScopeMosaicML embeddingsNLP CloudOpenAISageMaker Endpoint EmbeddingsSelf Hosted EmbeddingsSentence Transformers EmbeddingsSpacy EmbeddingTensorflowHubAgent toolkitsToolsVector storesGrouped by providerIntegrationsText embedding modelsLlama-cppLlama-cppThis notebook goes over how to use Llama-cpp embeddings within LangChainpip install llama-cpp-pythonfrom langchain.embeddings import LlamaCppEmbeddingsllama = LlamaCppEmbeddings(model_path="/path/to/model/ggml-model-q4_0.bin")text = "This is a test document."query_result = llama.embed_query(text)doc_result = llama.embed_documents([text])PreviousJinaNextLocalAICommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc. | https://python.langchain.com/docs/integrations/text_embedding/llamacpp |
ed2226654081-0 | MiniMax | 🦜�🔗 Langchain | https://python.langchain.com/docs/integrations/text_embedding/minimax |
ed2226654081-1 | Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAleph AlphaAzureOpenAIBedrock EmbeddingsClarifaiCohereDashScopeDeepInfraElasticsearchEmbaasFake EmbeddingsGoogle Cloud Platform Vertex AI PaLMGPT4AllHugging Face HubInstructEmbeddingsJinaLlama-cppLocalAIMiniMaxModelScopeMosaicML embeddingsNLP CloudOpenAISageMaker Endpoint EmbeddingsSelf Hosted EmbeddingsSentence Transformers EmbeddingsSpacy EmbeddingTensorflowHubAgent toolkitsToolsVector storesGrouped by providerIntegrationsText embedding modelsMiniMaxMiniMaxMiniMax offers an embeddings service.This example goes over how to use LangChain to interact with MiniMax Inference for text embedding.import osos.environ["MINIMAX_GROUP_ID"] = "MINIMAX_GROUP_ID"os.environ["MINIMAX_API_KEY"] = "MINIMAX_API_KEY"from langchain.embeddings import MiniMaxEmbeddingsembeddings = MiniMaxEmbeddings()query_text = "This is a test query."query_result = embeddings.embed_query(query_text)document_text = "This is a test document."document_result = embeddings.embed_documents([document_text])import numpy as npquery_numpy = np.array(query_result)document_numpy = np.array(document_result[0])similarity = np.dot(query_numpy, document_numpy) / ( np.linalg.norm(query_numpy) * np.linalg.norm(document_numpy))print(f"Cosine similarity between document and query: {similarity}") Cosine similarity between document and query: 0.1573236279277012PreviousLocalAINextModelScopeCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc. | https://python.langchain.com/docs/integrations/text_embedding/minimax |
bd19b592c9e4-0 | Embaas | 🦜�🔗 Langchain | https://python.langchain.com/docs/integrations/text_embedding/embaas |
bd19b592c9e4-1 | Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAleph AlphaAzureOpenAIBedrock EmbeddingsClarifaiCohereDashScopeDeepInfraElasticsearchEmbaasFake EmbeddingsGoogle Cloud Platform Vertex AI PaLMGPT4AllHugging Face HubInstructEmbeddingsJinaLlama-cppLocalAIMiniMaxModelScopeMosaicML embeddingsNLP CloudOpenAISageMaker Endpoint EmbeddingsSelf Hosted EmbeddingsSentence Transformers EmbeddingsSpacy EmbeddingTensorflowHubAgent toolkitsToolsVector storesGrouped by providerIntegrationsText embedding modelsEmbaasOn this pageEmbaasembaas is a fully managed NLP API service that offers features like embedding generation, document text extraction, document to embeddings and more. You can choose a variety of pre-trained models.In this tutorial, we will show you how to use the embaas Embeddings API to generate embeddings for a given text.Prerequisites​Create your free embaas account at https://embaas.io/register and generate an API key.# Set API keyembaas_api_key = "YOUR_API_KEY"# or set environment variableos.environ["EMBAAS_API_KEY"] = "YOUR_API_KEY"from langchain.embeddings import EmbaasEmbeddingsembeddings = EmbaasEmbeddings()# Create embeddings for a single documentdoc_text = "This is a test document."doc_text_embedding = embeddings.embed_query(doc_text)# Print created embeddingprint(doc_text_embedding)# Create embeddings for multiple documentsdoc_texts = ["This is a test document.", "This is another test document."]doc_texts_embeddings = embeddings.embed_documents(doc_texts)# Print created embeddingsfor i, doc_text_embedding in enumerate(doc_texts_embeddings): | https://python.langchain.com/docs/integrations/text_embedding/embaas |
bd19b592c9e4-2 | Print created embeddingsfor i, doc_text_embedding in enumerate(doc_texts_embeddings): print(f"Embedding for document {i + 1}: {doc_text_embedding}")# Using a different model and/or custom instructionembeddings = EmbaasEmbeddings( model="instructor-large", instruction="Represent the Wikipedia document for retrieval",)For more detailed information about the embaas Embeddings API, please refer to the official embaas API documentation.PreviousElasticsearchNextFake EmbeddingsPrerequisitesCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc. | https://python.langchain.com/docs/integrations/text_embedding/embaas |
2f9d1c00b0d2-0 | Fake Embeddings | 🦜�🔗 Langchain
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAleph AlphaAzureOpenAIBedrock EmbeddingsClarifaiCohereDashScopeDeepInfraElasticsearchEmbaasFake EmbeddingsGoogle Cloud Platform Vertex AI PaLMGPT4AllHugging Face HubInstructEmbeddingsJinaLlama-cppLocalAIMiniMaxModelScopeMosaicML embeddingsNLP CloudOpenAISageMaker Endpoint EmbeddingsSelf Hosted EmbeddingsSentence Transformers EmbeddingsSpacy EmbeddingTensorflowHubAgent toolkitsToolsVector storesGrouped by providerIntegrationsText embedding modelsFake EmbeddingsFake EmbeddingsLangChain also provides a fake embedding class. You can use this to test your pipelines.from langchain.embeddings import FakeEmbeddingsembeddings = FakeEmbeddings(size=1352)query_result = embeddings.embed_query("foo")doc_results = embeddings.embed_documents(["foo"])PreviousEmbaasNextGoogle Cloud Platform Vertex AI PaLMCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc. | https://python.langchain.com/docs/integrations/text_embedding/fake |
fada6034a465-0 | Agent toolkits | 🦜�🔗 Langchain | https://python.langchain.com/docs/integrations/toolkits/ |
fada6034a465-1 | Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsAmadeus ToolkitAzure Cognitive Services ToolkitCSV AgentDocument ComparisonGitHubGmail ToolkitJiraJSON AgentMultion ToolkitOffice365 ToolkitOpenAPI agentsNatural Language APIsPandas Dataframe AgentPlayWright Browser ToolkitPowerBI Dataset AgentPython AgentSpark Dataframe AgentSpark SQL AgentSQL Database AgentVectorstore AgentXorbits AgentToolsVector storesGrouped by providerIntegrationsAgent toolkitsAgent toolkits📄� Amadeus ToolkitThis notebook walks you through connecting LangChain to the Amadeus travel information API📄� Azure Cognitive Services ToolkitThis toolkit is used to interact with the Azure Cognitive Services API to achieve some multimodal capabilities.📄� CSV AgentThis notebook shows how to use agents to interact with a csv. It is mostly optimized for question answering.📄� Document ComparisonThis notebook shows how to use an agent to compare two documents.📄� GitHubThis notebook goes over how to use the GitHub tool.📄� Gmail ToolkitThis notebook walks through connecting a LangChain email to the Gmail API.📄� JiraThis notebook goes over how to use the Jira tool.📄� JSON AgentThis notebook showcases an agent designed to interact with large JSON/dict objects. This is useful when you want to answer questions about a JSON blob that's too large to fit in the context window of an LLM. The agent is able to iteratively explore the blob to find what it needs to answer the user's | https://python.langchain.com/docs/integrations/toolkits/ |
fada6034a465-2 | The agent is able to iteratively explore the blob to find what it needs to answer the user's question.📄� Multion ToolkitThis notebook walks you through connecting LangChain to the MultiOn Client in your browser📄� Office365 ToolkitThis notebook walks through connecting LangChain to Office365 email and calendar.📄� OpenAPI agentsWe can construct agents to consume arbitrary APIs, here APIs conformant to the OpenAPI/Swagger specification.📄� Natural Language APIsNatural Language API Toolkits (NLAToolkits) permit LangChain Agents to efficiently plan and combine calls across endpoints. This notebook demonstrates a sample composition of the Speak, Klarna, and Spoonacluar APIs.📄� Pandas Dataframe AgentThis notebook shows how to use agents to interact with a pandas dataframe. It is mostly optimized for question answering.📄� PlayWright Browser ToolkitThis toolkit is used to interact with the browser. While other tools (like the Requests tools) are fine for static sites, Browser toolkits let your agent navigate the web and interact with dynamically rendered sites. Some tools bundled within the Browser toolkit include:📄� PowerBI Dataset AgentThis notebook showcases an agent designed to interact with a Power BI Dataset. The agent is designed to answer more general questions about a dataset, as well as recover from errors.📄� Python AgentThis notebook showcases an agent designed to write and execute python code to answer a question.📄� Spark Dataframe AgentThis notebook shows how to use agents to interact with a Spark dataframe and Spark Connect. It is mostly optimized for question answering.📄� Spark SQL AgentThis notebook shows how to use agents to interact | https://python.langchain.com/docs/integrations/toolkits/ |
fada6034a465-3 | Spark SQL AgentThis notebook shows how to use agents to interact with a Spark SQL. Similar to SQL Database Agent, it is designed to address general inquiries about Spark SQL and facilitate error recovery.📄� SQL Database AgentThis notebook showcases an agent designed to interact with a sql databases. The agent builds off of SQLDatabaseChain and is designed to answer more general questions about a database, as well as recover from errors.📄� Vectorstore AgentThis notebook showcases an agent designed to retrieve information from one or more vectorstores, either with or without sources.📄� Xorbits AgentThis notebook shows how to use agents to interact with Xorbits Pandas dataframe and Xorbits Numpy ndarray. It is mostly optimized for question answering.PreviousTensorflowHubNextAmadeus ToolkitCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc. | https://python.langchain.com/docs/integrations/toolkits/ |
8310ca4ca42c-0 | Spark Dataframe Agent | 🦜�🔗 Langchain | https://python.langchain.com/docs/integrations/toolkits/spark |
8310ca4ca42c-1 | Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsAmadeus ToolkitAzure Cognitive Services ToolkitCSV AgentDocument ComparisonGitHubGmail ToolkitJiraJSON AgentMultion ToolkitOffice365 ToolkitOpenAPI agentsNatural Language APIsPandas Dataframe AgentPlayWright Browser ToolkitPowerBI Dataset AgentPython AgentSpark Dataframe AgentSpark SQL AgentSQL Database AgentVectorstore AgentXorbits AgentToolsVector storesGrouped by providerIntegrationsAgent toolkitsSpark Dataframe AgentOn this pageSpark Dataframe AgentThis notebook shows how to use agents to interact with a Spark dataframe and Spark Connect. It is mostly optimized for question answering.NOTE: this agent calls the Python agent under the hood, which executes LLM generated Python code - this can be bad if the LLM generated Python code is harmful. Use cautiously.import osos.environ["OPENAI_API_KEY"] = "...input your openai api key here..."from langchain.llms import OpenAIfrom pyspark.sql import SparkSessionfrom langchain.agents import create_spark_dataframe_agentspark = SparkSession.builder.getOrCreate()csv_file_path = "titanic.csv"df = spark.read.csv(csv_file_path, header=True, inferSchema=True)df.show() 23/05/15 20:33:10 WARN Utils: Your hostname, Mikes-Mac-mini.local resolves to a loopback address: 127.0.0.1; using 192.168.68.115 instead (on interface en1) 23/05/15 20:33:10 WARN Utils: Set SPARK_LOCAL_IP if you need to bind to another address Setting default log level to "WARN". To adjust logging level use | https://python.langchain.com/docs/integrations/toolkits/spark |
8310ca4ca42c-2 | address Setting default log level to "WARN". To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel). 23/05/15 20:33:10 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable +-----------+--------+------+--------------------+------+----+-----+-----+----------------+-------+-----+--------+ |PassengerId|Survived|Pclass| Name| Sex| Age|SibSp|Parch| Ticket| Fare|Cabin|Embarked| +-----------+--------+------+--------------------+------+----+-----+-----+----------------+-------+-----+--------+ | 1| 0| 3|Braund, Mr. Owen ...| male|22.0| 1| 0| A/5 21171| 7.25| null| S| | 2| 1| 1|Cumings, Mrs. Joh...|female|38.0| 1| 0| PC 17599|71.2833| C85| C| | 3| 1| | https://python.langchain.com/docs/integrations/toolkits/spark |
8310ca4ca42c-3 | 3| 1| 3|Heikkinen, Miss. ...|female|26.0| 0| 0|STON/O2. 3101282| 7.925| null| S| | 4| 1| 1|Futrelle, Mrs. Ja...|female|35.0| 1| 0| 113803| 53.1| C123| S| | 5| 0| 3|Allen, Mr. Willia...| male|35.0| 0| 0| 373450| 8.05| null| S| | 6| 0| 3| Moran, Mr. James| male|null| 0| 0| 330877| 8.4583| null| Q| | 7| 0| 1|McCarthy, Mr. Tim...| male|54.0| 0| | https://python.langchain.com/docs/integrations/toolkits/spark |
8310ca4ca42c-4 | Tim...| male|54.0| 0| 0| 17463|51.8625| E46| S| | 8| 0| 3|Palsson, Master. ...| male| 2.0| 3| 1| 349909| 21.075| null| S| | 9| 1| 3|Johnson, Mrs. Osc...|female|27.0| 0| 2| 347742|11.1333| null| S| | 10| 1| 2|Nasser, Mrs. Nich...|female|14.0| 1| 0| 237736|30.0708| null| C| | 11| 1| 3|Sandstrom, Miss. ...|female| 4.0| 1| 1| PP 9549| 16.7| G6| S| | https://python.langchain.com/docs/integrations/toolkits/spark |
8310ca4ca42c-5 | 16.7| G6| S| | 12| 1| 1|Bonnell, Miss. El...|female|58.0| 0| 0| 113783| 26.55| C103| S| | 13| 0| 3|Saundercock, Mr. ...| male|20.0| 0| 0| A/5. 2151| 8.05| null| S| | 14| 0| 3|Andersson, Mr. An...| male|39.0| 1| 5| 347082| 31.275| null| S| | 15| 0| 3|Vestrom, Miss. Hu...|female|14.0| 0| 0| 350406| 7.8542| null| S| | 16| 1| | https://python.langchain.com/docs/integrations/toolkits/spark |
8310ca4ca42c-6 | 16| 1| 2|Hewlett, Mrs. (Ma...|female|55.0| 0| 0| 248706| 16.0| null| S| | 17| 0| 3|Rice, Master. Eugene| male| 2.0| 4| 1| 382652| 29.125| null| Q| | 18| 1| 2|Williams, Mr. Cha...| male|null| 0| 0| 244373| 13.0| null| S| | 19| 0| 3|Vander Planke, Mr...|female|31.0| 1| 0| 345763| 18.0| null| S| | 20| 1| 3|Masselmani, Mrs. ...|female|null| 0| 0| | https://python.langchain.com/docs/integrations/toolkits/spark |
8310ca4ca42c-7 | 0| 0| 2649| 7.225| null| C| +-----------+--------+------+--------------------+------+----+-----+-----+----------------+-------+-----+--------+ only showing top 20 rows agent = create_spark_dataframe_agent(llm=OpenAI(temperature=0), df=df, verbose=True)agent.run("how many rows are there?") > Entering new AgentExecutor chain... Thought: I need to find out how many rows are in the dataframe Action: python_repl_ast Action Input: df.count() Observation: 891 Thought: I now know the final answer Final Answer: There are 891 rows in the dataframe. > Finished chain. 'There are 891 rows in the dataframe.'agent.run("how many people have more than 3 siblings") > Entering new AgentExecutor chain... Thought: I need to find out how many people have more than 3 siblings Action: python_repl_ast Action Input: df.filter(df.SibSp > 3).count() Observation: 30 Thought: I now know the final answer Final Answer: 30 people have more than 3 siblings. > Finished chain. '30 people have more than 3 siblings.'agent.run("whats the square root of the average age?") > Entering new AgentExecutor chain... Thought: I need | https://python.langchain.com/docs/integrations/toolkits/spark |
8310ca4ca42c-8 | > Entering new AgentExecutor chain... Thought: I need to get the average age first Action: python_repl_ast Action Input: df.agg({"Age": "mean"}).collect()[0][0] Observation: 29.69911764705882 Thought: I now have the average age, I need to get the square root Action: python_repl_ast Action Input: math.sqrt(29.69911764705882) Observation: name 'math' is not defined Thought: I need to import math first Action: python_repl_ast Action Input: import math Observation: Thought: I now have the math library imported, I can get the square root Action: python_repl_ast Action Input: math.sqrt(29.69911764705882) Observation: 5.449689683556195 Thought: I now know the final answer Final Answer: 5.449689683556195 > Finished chain. '5.449689683556195'spark.stop()Spark Connect Example​# in apache-spark root directory. (tested here with "spark-3.4.0-bin-hadoop3 and later")# To launch Spark with support for Spark Connect sessions, run the start-connect-server.sh script../sbin/start-connect-server.sh --packages org.apache.spark:spark-connect_2.12:3.4.0from pyspark.sql import SparkSession# Now that the Spark server is running, we can connect to it remotely using Spark Connect. We do this by# creating a remote Spark session on the client where our application runs. Before we can do that, we need# to | https://python.langchain.com/docs/integrations/toolkits/spark |
8310ca4ca42c-9 | Spark session on the client where our application runs. Before we can do that, we need# to make sure to stop the existing regular Spark session because it cannot coexist with the remote# Spark Connect session we are about to create.SparkSession.builder.master("local[*]").getOrCreate().stop() 23/05/08 10:06:09 WARN Utils: Service 'SparkUI' could not bind on port 4040. Attempting port 4041.# The command we used above to launch the server configured Spark to run as localhost:15002.# So now we can create a remote Spark session on the client using the following command.spark = SparkSession.builder.remote("sc://localhost:15002").getOrCreate()csv_file_path = "titanic.csv"df = spark.read.csv(csv_file_path, header=True, inferSchema=True)df.show() +-----------+--------+------+--------------------+------+----+-----+-----+----------------+-------+-----+--------+ |PassengerId|Survived|Pclass| Name| Sex| Age|SibSp|Parch| Ticket| Fare|Cabin|Embarked| +-----------+--------+------+--------------------+------+----+-----+-----+----------------+-------+-----+--------+ | 1| 0| 3|Braund, Mr. Owen ...| male|22.0| 1| 0| A/5 21171| 7.25| null| S| | | https://python.langchain.com/docs/integrations/toolkits/spark |
8310ca4ca42c-10 | S| | 2| 1| 1|Cumings, Mrs. Joh...|female|38.0| 1| 0| PC 17599|71.2833| C85| C| | 3| 1| 3|Heikkinen, Miss. ...|female|26.0| 0| 0|STON/O2. 3101282| 7.925| null| S| | 4| 1| 1|Futrelle, Mrs. Ja...|female|35.0| 1| 0| 113803| 53.1| C123| S| | 5| 0| 3|Allen, Mr. Willia...| male|35.0| 0| 0| 373450| 8.05| null| S| | 6| 0| 3| Moran, Mr. James| | https://python.langchain.com/docs/integrations/toolkits/spark |
8310ca4ca42c-11 | 0| 3| Moran, Mr. James| male|null| 0| 0| 330877| 8.4583| null| Q| | 7| 0| 1|McCarthy, Mr. Tim...| male|54.0| 0| 0| 17463|51.8625| E46| S| | 8| 0| 3|Palsson, Master. ...| male| 2.0| 3| 1| 349909| 21.075| null| S| | 9| 1| 3|Johnson, Mrs. Osc...|female|27.0| 0| 2| 347742|11.1333| null| S| | 10| 1| 2|Nasser, Mrs. Nich...|female|14.0| 1| 0| | https://python.langchain.com/docs/integrations/toolkits/spark |
8310ca4ca42c-12 | 1| 0| 237736|30.0708| null| C| | 11| 1| 3|Sandstrom, Miss. ...|female| 4.0| 1| 1| PP 9549| 16.7| G6| S| | 12| 1| 1|Bonnell, Miss. El...|female|58.0| 0| 0| 113783| 26.55| C103| S| | 13| 0| 3|Saundercock, Mr. ...| male|20.0| 0| 0| A/5. 2151| 8.05| null| S| | 14| 0| 3|Andersson, Mr. An...| male|39.0| 1| 5| 347082| 31.275| null| S| | | https://python.langchain.com/docs/integrations/toolkits/spark |
8310ca4ca42c-13 | null| S| | 15| 0| 3|Vestrom, Miss. Hu...|female|14.0| 0| 0| 350406| 7.8542| null| S| | 16| 1| 2|Hewlett, Mrs. (Ma...|female|55.0| 0| 0| 248706| 16.0| null| S| | 17| 0| 3|Rice, Master. Eugene| male| 2.0| 4| 1| 382652| 29.125| null| Q| | 18| 1| 2|Williams, Mr. Cha...| male|null| 0| 0| 244373| 13.0| null| S| | 19| 0| 3|Vander Planke, Mr...|female|31.0| | https://python.langchain.com/docs/integrations/toolkits/spark |
8310ca4ca42c-14 | 3|Vander Planke, Mr...|female|31.0| 1| 0| 345763| 18.0| null| S| | 20| 1| 3|Masselmani, Mrs. ...|female|null| 0| 0| 2649| 7.225| null| C| +-----------+--------+------+--------------------+------+----+-----+-----+----------------+-------+-----+--------+ only showing top 20 rows from langchain.agents import create_spark_dataframe_agentfrom langchain.llms import OpenAIimport osos.environ["OPENAI_API_KEY"] = "...input your openai api key here..."agent = create_spark_dataframe_agent(llm=OpenAI(temperature=0), df=df, verbose=True)agent.run( """who bought the most expensive ticket?You can find all supported function types in https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/dataframe.html""") > Entering new AgentExecutor chain... Thought: I need to find the row with the highest fare Action: python_repl_ast Action Input: df.sort(df.Fare.desc()).first() Observation: Row(PassengerId=259, Survived=1, Pclass=1, Name='Ward, Miss. Anna', Sex='female', Age=35.0, SibSp=0, | https://python.langchain.com/docs/integrations/toolkits/spark |
8310ca4ca42c-15 | Miss. Anna', Sex='female', Age=35.0, SibSp=0, Parch=0, Ticket='PC 17755', Fare=512.3292, Cabin=None, Embarked='C') Thought: I now know the name of the person who bought the most expensive ticket Final Answer: Miss. Anna Ward > Finished chain. 'Miss. Anna Ward'spark.stop()PreviousPython AgentNextSpark SQL AgentSpark Connect ExampleCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc. | https://python.langchain.com/docs/integrations/toolkits/spark |
c0a387cbb7ac-0 | Spark SQL Agent | 🦜�🔗 Langchain | https://python.langchain.com/docs/integrations/toolkits/spark_sql |
c0a387cbb7ac-1 | Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsAmadeus ToolkitAzure Cognitive Services ToolkitCSV AgentDocument ComparisonGitHubGmail ToolkitJiraJSON AgentMultion ToolkitOffice365 ToolkitOpenAPI agentsNatural Language APIsPandas Dataframe AgentPlayWright Browser ToolkitPowerBI Dataset AgentPython AgentSpark Dataframe AgentSpark SQL AgentSQL Database AgentVectorstore AgentXorbits AgentToolsVector storesGrouped by providerIntegrationsAgent toolkitsSpark SQL AgentOn this pageSpark SQL AgentThis notebook shows how to use agents to interact with a Spark SQL. Similar to SQL Database Agent, it is designed to address general inquiries about Spark SQL and facilitate error recovery.NOTE: Note that, as this agent is in active development, all answers might not be correct. Additionally, it is not guaranteed that the agent won't perform DML statements on your Spark cluster given certain questions. Be careful running it on sensitive data!Initialization​from langchain.agents import create_spark_sql_agentfrom langchain.agents.agent_toolkits import SparkSQLToolkitfrom langchain.chat_models import ChatOpenAIfrom langchain.utilities.spark_sql import SparkSQLfrom pyspark.sql import SparkSessionspark = SparkSession.builder.getOrCreate()schema = "langchain_example"spark.sql(f"CREATE DATABASE IF NOT EXISTS {schema}")spark.sql(f"USE {schema}")csv_file_path = "titanic.csv"table = "titanic"spark.read.csv(csv_file_path, header=True, inferSchema=True).write.saveAsTable(table)spark.table(table).show() Setting default log level to "WARN". To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel). | https://python.langchain.com/docs/integrations/toolkits/spark_sql |
c0a387cbb7ac-2 | use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel). 23/05/18 16:03:10 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable +-----------+--------+------+--------------------+------+----+-----+-----+----------------+-------+-----+--------+ |PassengerId|Survived|Pclass| Name| Sex| Age|SibSp|Parch| Ticket| Fare|Cabin|Embarked| +-----------+--------+------+--------------------+------+----+-----+-----+----------------+-------+-----+--------+ | 1| 0| 3|Braund, Mr. Owen ...| male|22.0| 1| 0| A/5 21171| 7.25| null| S| | 2| 1| 1|Cumings, Mrs. Joh...|female|38.0| 1| 0| PC 17599|71.2833| C85| C| | 3| 1| 3|Heikkinen, Miss. ...|female|26.0| | https://python.langchain.com/docs/integrations/toolkits/spark_sql |
c0a387cbb7ac-3 | Miss. ...|female|26.0| 0| 0|STON/O2. 3101282| 7.925| null| S| | 4| 1| 1|Futrelle, Mrs. Ja...|female|35.0| 1| 0| 113803| 53.1| C123| S| | 5| 0| 3|Allen, Mr. Willia...| male|35.0| 0| 0| 373450| 8.05| null| S| | 6| 0| 3| Moran, Mr. James| male|null| 0| 0| 330877| 8.4583| null| Q| | 7| 0| 1|McCarthy, Mr. Tim...| male|54.0| 0| 0| 17463|51.8625| E46| | https://python.langchain.com/docs/integrations/toolkits/spark_sql |
c0a387cbb7ac-4 | 17463|51.8625| E46| S| | 8| 0| 3|Palsson, Master. ...| male| 2.0| 3| 1| 349909| 21.075| null| S| | 9| 1| 3|Johnson, Mrs. Osc...|female|27.0| 0| 2| 347742|11.1333| null| S| | 10| 1| 2|Nasser, Mrs. Nich...|female|14.0| 1| 0| 237736|30.0708| null| C| | 11| 1| 3|Sandstrom, Miss. ...|female| 4.0| 1| 1| PP 9549| 16.7| G6| S| | 12| 1| | https://python.langchain.com/docs/integrations/toolkits/spark_sql |
c0a387cbb7ac-5 | 12| 1| 1|Bonnell, Miss. El...|female|58.0| 0| 0| 113783| 26.55| C103| S| | 13| 0| 3|Saundercock, Mr. ...| male|20.0| 0| 0| A/5. 2151| 8.05| null| S| | 14| 0| 3|Andersson, Mr. An...| male|39.0| 1| 5| 347082| 31.275| null| S| | 15| 0| 3|Vestrom, Miss. Hu...|female|14.0| 0| 0| 350406| 7.8542| null| S| | 16| 1| 2|Hewlett, Mrs. (Ma...|female|55.0| 0| | https://python.langchain.com/docs/integrations/toolkits/spark_sql |
c0a387cbb7ac-6 | (Ma...|female|55.0| 0| 0| 248706| 16.0| null| S| | 17| 0| 3|Rice, Master. Eugene| male| 2.0| 4| 1| 382652| 29.125| null| Q| | 18| 1| 2|Williams, Mr. Cha...| male|null| 0| 0| 244373| 13.0| null| S| | 19| 0| 3|Vander Planke, Mr...|female|31.0| 1| 0| 345763| 18.0| null| S| | 20| 1| 3|Masselmani, Mrs. ...|female|null| 0| 0| 2649| 7.225| null| C| | https://python.langchain.com/docs/integrations/toolkits/spark_sql |
c0a387cbb7ac-7 | 7.225| null| C| +-----------+--------+------+--------------------+------+----+-----+-----+----------------+-------+-----+--------+ only showing top 20 rows # Note, you can also connect to Spark via Spark connect. For example:# db = SparkSQL.from_uri("sc://localhost:15002", schema=schema)spark_sql = SparkSQL(schema=schema)llm = ChatOpenAI(temperature=0)toolkit = SparkSQLToolkit(db=spark_sql, llm=llm)agent_executor = create_spark_sql_agent(llm=llm, toolkit=toolkit, verbose=True)Example: describing a table​agent_executor.run("Describe the titanic table") > Entering new AgentExecutor chain... Action: list_tables_sql_db Action Input: Observation: titanic Thought:I found the titanic table. Now I need to get the schema and sample rows for the titanic table. Action: schema_sql_db Action Input: titanic Observation: CREATE TABLE langchain_example.titanic ( PassengerId INT, Survived INT, Pclass INT, Name STRING, Sex STRING, Age DOUBLE, SibSp INT, Parch INT, Ticket STRING, Fare DOUBLE, Cabin STRING, Embarked STRING) ; /* 3 rows from titanic table: PassengerId Survived | https://python.langchain.com/docs/integrations/toolkits/spark_sql |
c0a387cbb7ac-8 | 3 rows from titanic table: PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked 1 0 3 Braund, Mr. Owen Harris male 22.0 1 0 A/5 21171 7.25 None S 2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Thayer) female 38.0 1 0 PC 17599 71.2833 C85 C 3 1 3 Heikkinen, Miss. Laina female 26.0 0 0 STON/O2. 3101282 7.925 None S */ Thought:I now know the schema and sample rows for the titanic table. Final Answer: The titanic table has the following columns: PassengerId (INT), Survived (INT), Pclass (INT), Name (STRING), Sex (STRING), Age (DOUBLE), SibSp (INT), Parch (INT), Ticket (STRING), Fare (DOUBLE), Cabin (STRING), and Embarked (STRING). Here are some sample rows from the table: 1. PassengerId: 1, Survived: 0, Pclass: 3, Name: Braund, Mr. Owen Harris, Sex: male, Age: 22.0, SibSp: 1, Parch: | https://python.langchain.com/docs/integrations/toolkits/spark_sql |
c0a387cbb7ac-9 | male, Age: 22.0, SibSp: 1, Parch: 0, Ticket: A/5 21171, Fare: 7.25, Cabin: None, Embarked: S 2. PassengerId: 2, Survived: 1, Pclass: 1, Name: Cumings, Mrs. John Bradley (Florence Briggs Thayer), Sex: female, Age: 38.0, SibSp: 1, Parch: 0, Ticket: PC 17599, Fare: 71.2833, Cabin: C85, Embarked: C 3. PassengerId: 3, Survived: 1, Pclass: 3, Name: Heikkinen, Miss. Laina, Sex: female, Age: 26.0, SibSp: 0, Parch: 0, Ticket: STON/O2. 3101282, Fare: 7.925, Cabin: None, Embarked: S > Finished chain. 'The titanic table has the following columns: PassengerId (INT), Survived (INT), Pclass (INT), Name (STRING), Sex (STRING), Age (DOUBLE), SibSp (INT), Parch (INT), Ticket (STRING), Fare (DOUBLE), Cabin (STRING), and Embarked (STRING). Here are some sample rows from the table: \n\n1. PassengerId: 1, Survived: 0, Pclass: 3, Name: Braund, Mr. Owen Harris, Sex: male, Age: 22.0, SibSp: 1, Parch: 0, Ticket: A/5 21171, Fare: 7.25, Cabin: None, Embarked: S\n2. PassengerId: 2, | https://python.langchain.com/docs/integrations/toolkits/spark_sql |
c0a387cbb7ac-10 | Cabin: None, Embarked: S\n2. PassengerId: 2, Survived: 1, Pclass: 1, Name: Cumings, Mrs. John Bradley (Florence Briggs Thayer), Sex: female, Age: 38.0, SibSp: 1, Parch: 0, Ticket: PC 17599, Fare: 71.2833, Cabin: C85, Embarked: C\n3. PassengerId: 3, Survived: 1, Pclass: 3, Name: Heikkinen, Miss. Laina, Sex: female, Age: 26.0, SibSp: 0, Parch: 0, Ticket: STON/O2. 3101282, Fare: 7.925, Cabin: None, Embarked: S'Example: running queries​agent_executor.run("whats the square root of the average age?") > Entering new AgentExecutor chain... Action: list_tables_sql_db Action Input: Observation: titanic Thought:I should check the schema of the titanic table to see if there is an age column. Action: schema_sql_db Action Input: titanic Observation: CREATE TABLE langchain_example.titanic ( PassengerId INT, Survived INT, Pclass INT, Name STRING, Sex STRING, Age DOUBLE, SibSp INT, Parch INT, Ticket STRING, Fare DOUBLE, Cabin STRING, Embarked STRING) | https://python.langchain.com/docs/integrations/toolkits/spark_sql |
c0a387cbb7ac-11 | DOUBLE, Cabin STRING, Embarked STRING) ; /* 3 rows from titanic table: PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked 1 0 3 Braund, Mr. Owen Harris male 22.0 1 0 A/5 21171 7.25 None S 2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Thayer) female 38.0 1 0 PC 17599 71.2833 C85 C 3 1 3 Heikkinen, Miss. Laina female 26.0 0 0 STON/O2. 3101282 7.925 None S */ Thought:There is an Age column in the titanic table. I should write a query to calculate the average age and then find the square root of the result. Action: query_checker_sql_db Action Input: SELECT SQRT(AVG(Age)) as square_root_of_avg_age FROM titanic Observation: The original query seems to be correct. Here it is again: SELECT SQRT(AVG(Age)) as square_root_of_avg_age FROM titanic Thought:The query is correct, so I can execute it to find the square | https://python.langchain.com/docs/integrations/toolkits/spark_sql |
c0a387cbb7ac-12 | titanic Thought:The query is correct, so I can execute it to find the square root of the average age. Action: query_sql_db Action Input: SELECT SQRT(AVG(Age)) as square_root_of_avg_age FROM titanic Observation: [('5.449689683556195',)] Thought:I now know the final answer Final Answer: The square root of the average age is approximately 5.45. > Finished chain. 'The square root of the average age is approximately 5.45.'agent_executor.run("What's the name of the oldest survived passenger?") > Entering new AgentExecutor chain... Action: list_tables_sql_db Action Input: Observation: titanic Thought:I should check the schema of the titanic table to see what columns are available. Action: schema_sql_db Action Input: titanic Observation: CREATE TABLE langchain_example.titanic ( PassengerId INT, Survived INT, Pclass INT, Name STRING, Sex STRING, Age DOUBLE, SibSp INT, Parch INT, Ticket STRING, Fare DOUBLE, Cabin STRING, Embarked STRING) ; /* 3 rows from titanic table: PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin | https://python.langchain.com/docs/integrations/toolkits/spark_sql |
c0a387cbb7ac-13 | Sex Age SibSp Parch Ticket Fare Cabin Embarked 1 0 3 Braund, Mr. Owen Harris male 22.0 1 0 A/5 21171 7.25 None S 2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Thayer) female 38.0 1 0 PC 17599 71.2833 C85 C 3 1 3 Heikkinen, Miss. Laina female 26.0 0 0 STON/O2. 3101282 7.925 None S */ Thought:I can use the titanic table to find the oldest survived passenger. I will query the Name and Age columns, filtering by Survived and ordering by Age in descending order. Action: query_checker_sql_db Action Input: SELECT Name, Age FROM titanic WHERE Survived = 1 ORDER BY Age DESC LIMIT 1 Observation: SELECT Name, Age FROM titanic WHERE Survived = 1 ORDER BY Age DESC LIMIT 1 Thought:The query is correct. Now I will execute it to find the oldest survived passenger. Action: query_sql_db Action Input: SELECT Name, Age FROM titanic WHERE Survived = 1 ORDER BY Age DESC LIMIT 1 Observation: [('Barkworth, Mr. Algernon Henry Wilson', '80.0')] Thought:I now know the | https://python.langchain.com/docs/integrations/toolkits/spark_sql |
c0a387cbb7ac-14 | Algernon Henry Wilson', '80.0')] Thought:I now know the final answer. Final Answer: The oldest survived passenger is Barkworth, Mr. Algernon Henry Wilson, who was 80 years old. > Finished chain. 'The oldest survived passenger is Barkworth, Mr. Algernon Henry Wilson, who was 80 years old.'PreviousSpark Dataframe AgentNextSQL Database AgentInitializationExample: describing a tableExample: running queriesCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc. | https://python.langchain.com/docs/integrations/toolkits/spark_sql |
f4b7f78d0116-0 | Natural Language APIs | 🦜�🔗 Langchain | https://python.langchain.com/docs/integrations/toolkits/openapi_nla |
f4b7f78d0116-1 | Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsAmadeus ToolkitAzure Cognitive Services ToolkitCSV AgentDocument ComparisonGitHubGmail ToolkitJiraJSON AgentMultion ToolkitOffice365 ToolkitOpenAPI agentsNatural Language APIsPandas Dataframe AgentPlayWright Browser ToolkitPowerBI Dataset AgentPython AgentSpark Dataframe AgentSpark SQL AgentSQL Database AgentVectorstore AgentXorbits AgentToolsVector storesGrouped by providerIntegrationsAgent toolkitsNatural Language APIsOn this pageNatural Language APIsNatural Language API Toolkits (NLAToolkits) permit LangChain Agents to efficiently plan and combine calls across endpoints. This notebook demonstrates a sample composition of the Speak, Klarna, and Spoonacluar APIs.For a detailed walkthrough of the OpenAPI chains wrapped within the NLAToolkit, see the OpenAPI Operation Chain notebook.First, import dependencies and load the LLM​from typing import List, Optionalfrom langchain.chains import LLMChainfrom langchain.llms import OpenAIfrom langchain.prompts import PromptTemplatefrom langchain.requests import Requestsfrom langchain.tools import APIOperation, OpenAPISpecfrom langchain.agents import AgentType, Tool, initialize_agentfrom langchain.agents.agent_toolkits import NLAToolkit# Select the LLM to use. Here, we use text-davinci-003llm = OpenAI( temperature=0, max_tokens=700) # You can swap between different core LLM's here.Next, load the Natural Language API Toolkits​speak_toolkit = NLAToolkit.from_llm_and_url(llm, "https://api.speak.com/openapi.yaml")klarna_toolkit = | https://python.langchain.com/docs/integrations/toolkits/openapi_nla |
f4b7f78d0116-2 | "https://api.speak.com/openapi.yaml")klarna_toolkit = NLAToolkit.from_llm_and_url( llm, "https://www.klarna.com/us/shopping/public/openai/v0/api-docs/") Attempting to load an OpenAPI 3.0.1 spec. This may result in degraded performance. Convert your OpenAPI spec to 3.1.* spec for better support. Attempting to load an OpenAPI 3.0.1 spec. This may result in degraded performance. Convert your OpenAPI spec to 3.1.* spec for better support. Attempting to load an OpenAPI 3.0.1 spec. This may result in degraded performance. Convert your OpenAPI spec to 3.1.* spec for better support.Create the Agent​# Slightly tweak the instructions from the default agentopenapi_format_instructions = """Use the following format:Question: the input question you must answerThought: you should always think about what to doAction: the action to take, should be one of [{tool_names}]Action Input: what to instruct the AI Action representative.Observation: The Agent's response... (this Thought/Action/Action Input/Observation can repeat N times)Thought: I now know the final answer. User can't see any of my observations, API responses, links, or tools.Final Answer: the final answer to the original input question with the right amount of detailWhen responding with your Final Answer, remember that the person you are responding to CANNOT see any of your Thought/Action/Action Input/Observations, so if there is any relevant information there you need to include it explicitly in your response."""natural_language_tools = speak_toolkit.get_tools() + klarna_toolkit.get_tools()mrkl = initialize_agent( natural_language_tools, | https://python.langchain.com/docs/integrations/toolkits/openapi_nla |
f4b7f78d0116-3 | = initialize_agent( natural_language_tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True, agent_kwargs={"format_instructions": openapi_format_instructions},)mrkl.run( "I have an end of year party for my Italian class and have to buy some Italian clothes for it") > Entering new AgentExecutor chain... I need to find out what kind of Italian clothes are available Action: Open_AI_Klarna_product_Api.productsUsingGET Action Input: Italian clothes Observation: The API response contains two products from the Alé brand in Italian Blue. The first is the Alé Colour Block Short Sleeve Jersey Men - Italian Blue, which costs $86.49, and the second is the Alé Dolid Flash Jersey Men - Italian Blue, which costs $40.00. Thought: I now know what kind of Italian clothes are available and how much they cost. Final Answer: You can buy two products from the Alé brand in Italian Blue for your end of year party. The Alé Colour Block Short Sleeve Jersey Men - Italian Blue costs $86.49, and the Alé Dolid Flash Jersey Men - Italian Blue costs $40.00. > Finished chain. 'You can buy two products from the Alé brand in Italian Blue for your end of year party. The Alé Colour Block Short Sleeve Jersey Men - Italian Blue costs $86.49, and the Alé Dolid Flash Jersey Men - Italian Blue costs $40.00.'Using Auth + Adding more Endpoints​Some endpoints may require user authentication via things like access tokens. Here we show how to pass in the authentication | https://python.langchain.com/docs/integrations/toolkits/openapi_nla |
f4b7f78d0116-4 | endpoints may require user authentication via things like access tokens. Here we show how to pass in the authentication information via the Requests wrapper object.Since each NLATool exposes a concisee natural language interface to its wrapped API, the top level conversational agent has an easier job incorporating each endpoint to satisfy a user's request.Adding the Spoonacular endpoints.Go to the Spoonacular API Console and make a free account.Click on Profile and copy your API key below.spoonacular_api_key = "" # Copy from the API Consolerequests = Requests(headers={"x-api-key": spoonacular_api_key})spoonacular_toolkit = NLAToolkit.from_llm_and_url( llm, "https://spoonacular.com/application/frontend/downloads/spoonacular-openapi-3.json", requests=requests, max_text_length=1800, # If you want to truncate the response text) Attempting to load an OpenAPI 3.0.0 spec. This may result in degraded performance. Convert your OpenAPI spec to 3.1.* spec for better support. Unsupported APIPropertyLocation "header" for parameter Content-Type. Valid values are ['path', 'query'] Ignoring optional parameter Unsupported APIPropertyLocation "header" for parameter Accept. Valid values are ['path', 'query'] Ignoring optional parameter Unsupported APIPropertyLocation "header" for parameter Content-Type. Valid values are ['path', 'query'] Ignoring optional parameter Unsupported APIPropertyLocation "header" for parameter Accept. Valid values are ['path', 'query'] Ignoring optional parameter Unsupported APIPropertyLocation "header" for parameter Content-Type. Valid values are ['path', 'query'] Ignoring optional parameter Unsupported APIPropertyLocation "header" for parameter Accept. Valid values are ['path', 'query'] Ignoring optional parameter | https://python.langchain.com/docs/integrations/toolkits/openapi_nla |
f4b7f78d0116-5 | for parameter Accept. Valid values are ['path', 'query'] Ignoring optional parameter Unsupported APIPropertyLocation "header" for parameter Content-Type. Valid values are ['path', 'query'] Ignoring optional parameter Unsupported APIPropertyLocation "header" for parameter Accept. Valid values are ['path', 'query'] Ignoring optional parameter Unsupported APIPropertyLocation "header" for parameter Content-Type. Valid values are ['path', 'query'] Ignoring optional parameter Unsupported APIPropertyLocation "header" for parameter Content-Type. Valid values are ['path', 'query'] Ignoring optional parameter Unsupported APIPropertyLocation "header" for parameter Content-Type. Valid values are ['path', 'query'] Ignoring optional parameter Unsupported APIPropertyLocation "header" for parameter Content-Type. Valid values are ['path', 'query'] Ignoring optional parameter Unsupported APIPropertyLocation "header" for parameter Accept. Valid values are ['path', 'query'] Ignoring optional parameter Unsupported APIPropertyLocation "header" for parameter Content-Type. Valid values are ['path', 'query'] Ignoring optional parameter Unsupported APIPropertyLocation "header" for parameter Accept. Valid values are ['path', 'query'] Ignoring optional parameter Unsupported APIPropertyLocation "header" for parameter Accept. Valid values are ['path', 'query'] Ignoring optional parameter Unsupported APIPropertyLocation "header" for parameter Accept. Valid values are ['path', 'query'] Ignoring optional parameter Unsupported APIPropertyLocation "header" for parameter Content-Type. Valid values are ['path', 'query'] Ignoring optional parameternatural_language_api_tools = ( speak_toolkit.get_tools() + klarna_toolkit.get_tools() + spoonacular_toolkit.get_tools()[:30])print(f"{len(natural_language_api_tools)} | https://python.langchain.com/docs/integrations/toolkits/openapi_nla |
f4b7f78d0116-6 | spoonacular_toolkit.get_tools()[:30])print(f"{len(natural_language_api_tools)} tools loaded.") 34 tools loaded.# Create an agent with the new toolsmrkl = initialize_agent( natural_language_api_tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True, agent_kwargs={"format_instructions": openapi_format_instructions},)# Make the query more complex!user_input = ( "I'm learning Italian, and my language class is having an end of year party... " " Could you help me find an Italian outfit to wear and" " an appropriate recipe to prepare so I can present for the class in Italian?")mrkl.run(user_input) > Entering new AgentExecutor chain... I need to find a recipe and an outfit that is Italian-themed. Action: spoonacular_API.searchRecipes Action Input: Italian Observation: The API response contains 10 Italian recipes, including Turkey Tomato Cheese Pizza, Broccolini Quinoa Pilaf, Bruschetta Style Pork & Pasta, Salmon Quinoa Risotto, Italian Tuna Pasta, Roasted Brussels Sprouts With Garlic, Asparagus Lemon Risotto, Italian Steamed Artichokes, Crispy Italian Cauliflower Poppers Appetizer, and Pappa Al Pomodoro. Thought: I need to find an Italian-themed outfit. Action: Open_AI_Klarna_product_Api.productsUsingGET Action Input: Italian Observation: I found 10 products related to 'Italian' in the API response. These products include Italian Gold Sparkle Perfectina Necklace - Gold, Italian Design Miami Cuban Link Chain Necklace - Gold, Italian Gold Miami Cuban Link Chain Necklace - Gold, Italian Gold | https://python.langchain.com/docs/integrations/toolkits/openapi_nla |
f4b7f78d0116-7 | Miami Cuban Link Chain Necklace - Gold, Italian Gold Miami Cuban Link Chain Necklace - Gold, Italian Gold Herringbone Necklace - Gold, Italian Gold Claddagh Ring - Gold, Italian Gold Herringbone Chain Necklace - Gold, Garmin QuickFit 22mm Italian Vacchetta Leather Band, Macy's Italian Horn Charm - Gold, Dolce & Gabbana Light Blue Italian Love Pour Homme EdT 1.7 fl oz. Thought: I now know the final answer. Final Answer: To present for your Italian language class, you could wear an Italian Gold Sparkle Perfectina Necklace - Gold, an Italian Design Miami Cuban Link Chain Necklace - Gold, or an Italian Gold Miami Cuban Link Chain Necklace - Gold. For a recipe, you could make Turkey Tomato Cheese Pizza, Broccolini Quinoa Pilaf, Bruschetta Style Pork & Pasta, Salmon Quinoa Risotto, Italian Tuna Pasta, Roasted Brussels Sprouts With Garlic, Asparagus Lemon Risotto, Italian Steamed Artichokes, Crispy Italian Cauliflower Poppers Appetizer, or Pappa Al Pomodoro. > Finished chain. 'To present for your Italian language class, you could wear an Italian Gold Sparkle Perfectina Necklace - Gold, an Italian Design Miami Cuban Link Chain Necklace - Gold, or an Italian Gold Miami Cuban Link Chain Necklace - Gold. For a recipe, you could make Turkey Tomato Cheese Pizza, Broccolini Quinoa Pilaf, Bruschetta Style Pork & Pasta, Salmon Quinoa Risotto, Italian Tuna Pasta, Roasted Brussels Sprouts With Garlic, Asparagus Lemon Risotto, Italian Steamed Artichokes, Crispy Italian Cauliflower Poppers Appetizer, or Pappa Al Pomodoro.'Thank you!​natural_language_api_tools[1].run( "Tell the LangChain audience to 'enjoy the | https://python.langchain.com/docs/integrations/toolkits/openapi_nla |
f4b7f78d0116-8 | "Tell the LangChain audience to 'enjoy the meal' in Italian, please!") "In Italian, you can say 'Buon appetito' to someone to wish them to enjoy their meal. This phrase is commonly used in Italy when someone is about to eat, often at the beginning of a meal. It's similar to saying 'Bon appétit' in French or 'Guten Appetit' in German."PreviousOpenAPI agentsNextPandas Dataframe AgentFirst, import dependencies and load the LLMNext, load the Natural Language API ToolkitsCreate the AgentUsing Auth + Adding more EndpointsThank you!CommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc. | https://python.langchain.com/docs/integrations/toolkits/openapi_nla |
a1f8f1847f4b-0 | Jira | 🦜�🔗 Langchain | https://python.langchain.com/docs/integrations/toolkits/jira |
a1f8f1847f4b-1 | Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsAmadeus ToolkitAzure Cognitive Services ToolkitCSV AgentDocument ComparisonGitHubGmail ToolkitJiraJSON AgentMultion ToolkitOffice365 ToolkitOpenAPI agentsNatural Language APIsPandas Dataframe AgentPlayWright Browser ToolkitPowerBI Dataset AgentPython AgentSpark Dataframe AgentSpark SQL AgentSQL Database AgentVectorstore AgentXorbits AgentToolsVector storesGrouped by providerIntegrationsAgent toolkitsJiraJiraThis notebook goes over how to use the Jira tool.
The Jira tool allows agents to interact with a given Jira instance, performing actions such as searching for issues and creating issues, the tool wraps the atlassian-python-api library, for more see: https://atlassian-python-api.readthedocs.io/jira.htmlTo use this tool, you must first set as environment variables:
JIRA_API_TOKEN
JIRA_USERNAME | https://python.langchain.com/docs/integrations/toolkits/jira |
a1f8f1847f4b-2 | JIRA_API_TOKEN
JIRA_USERNAME
JIRA_INSTANCE_URL%pip install atlassian-python-apiimport osfrom langchain.agents import AgentTypefrom langchain.agents import initialize_agentfrom langchain.agents.agent_toolkits.jira.toolkit import JiraToolkitfrom langchain.llms import OpenAIfrom langchain.utilities.jira import JiraAPIWrapperos.environ["JIRA_API_TOKEN"] = "abc"os.environ["JIRA_USERNAME"] = "123"os.environ["JIRA_INSTANCE_URL"] = "https://jira.atlassian.com"os.environ["OPENAI_API_KEY"] = "xyz"llm = OpenAI(temperature=0)jira = JiraAPIWrapper()toolkit = JiraToolkit.from_jira_api_wrapper(jira)agent = initialize_agent( toolkit.get_tools(), llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)agent.run("make a new issue in project PW to remind me to make more fried rice") > Entering new AgentExecutor chain... I need to create an issue in project PW Action: Create Issue Action Input: {"summary": "Make more fried rice", "description": "Reminder to make more fried rice", "issuetype": {"name": "Task"}, "priority": {"name": "Low"}, "project": {"key": "PW"}} Observation: None Thought: I now know the final answer Final Answer: A new issue has been created in project PW with the summary "Make more fried rice" and description "Reminder to make more fried rice". > Finished chain. 'A new issue has been created in project PW with the summary "Make more fried rice" and description "Reminder to make more fried rice".'PreviousGmail ToolkitNextJSON AgentCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc. | https://python.langchain.com/docs/integrations/toolkits/jira |
300f32fa972a-0 | Python Agent | 🦜�🔗 Langchain | https://python.langchain.com/docs/integrations/toolkits/python |
300f32fa972a-1 | Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsAmadeus ToolkitAzure Cognitive Services ToolkitCSV AgentDocument ComparisonGitHubGmail ToolkitJiraJSON AgentMultion ToolkitOffice365 ToolkitOpenAPI agentsNatural Language APIsPandas Dataframe AgentPlayWright Browser ToolkitPowerBI Dataset AgentPython AgentSpark Dataframe AgentSpark SQL AgentSQL Database AgentVectorstore AgentXorbits AgentToolsVector storesGrouped by providerIntegrationsAgent toolkitsPython AgentOn this pagePython AgentThis notebook showcases an agent designed to write and execute python code to answer a question.from langchain.agents.agent_toolkits import create_python_agentfrom langchain.tools.python.tool import PythonREPLToolfrom langchain.python import PythonREPLfrom langchain.llms.openai import OpenAIfrom langchain.agents.agent_types import AgentTypefrom langchain.chat_models import ChatOpenAIUsing ZERO_SHOT_REACT_DESCRIPTION​This shows how to initialize the agent using the ZERO_SHOT_REACT_DESCRIPTION agent type. Note that this is an alternative to the above.agent_executor = create_python_agent( llm=OpenAI(temperature=0, max_tokens=1000), tool=PythonREPLTool(), verbose=True, agent_type=AgentType.ZERO_SHOT_REACT_DESCRIPTION,)Using OpenAI Functions​This shows how to initialize the agent using the OPENAI_FUNCTIONS agent type. Note that this is an alternative to the above.agent_executor = create_python_agent( llm=ChatOpenAI(temperature=0, model="gpt-3.5-turbo-0613"), tool=PythonREPLTool(), verbose=True, | https://python.langchain.com/docs/integrations/toolkits/python |
300f32fa972a-2 | tool=PythonREPLTool(), verbose=True, agent_type=AgentType.OPENAI_FUNCTIONS, agent_executor_kwargs={"handle_parsing_errors": True},)Fibonacci Example​This example was created by John Wiseman.agent_executor.run("What is the 10th fibonacci number?") > Entering new chain... Invoking: `Python_REPL` with `def fibonacci(n): if n <= 0: return 0 elif n == 1: return 1 else: return fibonacci(n-1) + fibonacci(n-2) fibonacci(10)` The 10th Fibonacci number is 55. > Finished chain. 'The 10th Fibonacci number is 55.'Training neural net​This example was created by Samee Ur Rehman.agent_executor.run( """Understand, write a single neuron neural network in PyTorch.Take synthetic data for y=2x. Train for 1000 epochs and print every 100 epochs.Return prediction for x = 5""") > Entering new chain... Could not parse tool input: {'name': 'python', 'arguments': 'import torch\nimport torch.nn as nn\nimport torch.optim as optim\n\n# Define the neural network\nclass SingleNeuron(nn.Module):\n def | https://python.langchain.com/docs/integrations/toolkits/python |
300f32fa972a-3 | Define the neural network\nclass SingleNeuron(nn.Module):\n def __init__(self):\n super(SingleNeuron, self).__init__()\n self.linear = nn.Linear(1, 1)\n \n def forward(self, x):\n return self.linear(x)\n\n# Create the synthetic data\nx_train = torch.tensor([[1.0], [2.0], [3.0], [4.0]], dtype=torch.float32)\ny_train = torch.tensor([[2.0], [4.0], [6.0], [8.0]], dtype=torch.float32)\n\n# Create the neural network\nmodel = SingleNeuron()\n\n# Define the loss function and optimizer\ncriterion = nn.MSELoss()\noptimizer = optim.SGD(model.parameters(), lr=0.01)\n\n# Train the neural network\nfor epoch in range(1, 1001):\n # Forward pass\n y_pred = model(x_train)\n \n # Compute loss\n loss = criterion(y_pred, y_train)\n \n # Backward pass and optimization\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n \n # Print the loss every 100 epochs\n if epoch % 100 == 0:\n print(f"Epoch {epoch}: Loss = {loss.item()}")\n\n# Make a prediction for x = 5\nx_test = torch.tensor([[5.0]], dtype=torch.float32)\ny_pred = model(x_test)\ny_pred.item()'} | https://python.langchain.com/docs/integrations/toolkits/python |
300f32fa972a-4 | dtype=torch.float32)\ny_pred = model(x_test)\ny_pred.item()'} because the `arguments` is not valid JSON.Invalid or incomplete response Invoking: `Python_REPL` with `import torch import torch.nn as nn import torch.optim as optim # Define the neural network class SingleNeuron(nn.Module): def __init__(self): super(SingleNeuron, self).__init__() self.linear = nn.Linear(1, 1) def forward(self, x): return self.linear(x) # Create the synthetic data x_train = torch.tensor([[1.0], [2.0], [3.0], [4.0]], dtype=torch.float32) y_train = torch.tensor([[2.0], [4.0], [6.0], [8.0]], dtype=torch.float32) # Create the neural network model = SingleNeuron() # Define the loss function and optimizer criterion = nn.MSELoss() optimizer = optim.SGD(model.parameters(), lr=0.01) # Train the neural network for epoch in range(1, 1001): # Forward pass y_pred = model(x_train) # Compute loss loss = | https://python.langchain.com/docs/integrations/toolkits/python |
300f32fa972a-5 | # Compute loss loss = criterion(y_pred, y_train) # Backward pass and optimization optimizer.zero_grad() loss.backward() optimizer.step() # Print the loss every 100 epochs if epoch % 100 == 0: print(f"Epoch {epoch}: Loss = {loss.item()}") # Make a prediction for x = 5 x_test = torch.tensor([[5.0]], dtype=torch.float32) y_pred = model(x_test) y_pred.item()` Epoch 100: Loss = 0.03825576975941658 Epoch 200: Loss = 0.02100197970867157 Epoch 300: Loss = 0.01152981910854578 Epoch 400: Loss = 0.006329738534986973 Epoch 500: Loss = 0.0034749575424939394 Epoch 600: Loss = 0.0019077073084190488 Epoch 700: Loss = 0.001047312980517745 Epoch 800: Loss = 0.0005749554838985205 Epoch 900: Loss = 0.0003156439634039998 Epoch 1000: Loss = 0.00017328384274151176 Invoking: | https://python.langchain.com/docs/integrations/toolkits/python |
300f32fa972a-6 | 0.00017328384274151176 Invoking: `Python_REPL` with `x_test.item()` The prediction for x = 5 is 10.000173568725586. > Finished chain. 'The prediction for x = 5 is 10.000173568725586.'PreviousPowerBI Dataset AgentNextSpark Dataframe AgentUsing ZERO_SHOT_REACT_DESCRIPTIONUsing OpenAI FunctionsFibonacci ExampleTraining neural netCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc. | https://python.langchain.com/docs/integrations/toolkits/python |
7dee5fea66db-0 | Multion Toolkit | 🦜�🔗 Langchain | https://python.langchain.com/docs/integrations/toolkits/multion |
7dee5fea66db-1 | Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsAmadeus ToolkitAzure Cognitive Services ToolkitCSV AgentDocument ComparisonGitHubGmail ToolkitJiraJSON AgentMultion ToolkitOffice365 ToolkitOpenAPI agentsNatural Language APIsPandas Dataframe AgentPlayWright Browser ToolkitPowerBI Dataset AgentPython AgentSpark Dataframe AgentSpark SQL AgentSQL Database AgentVectorstore AgentXorbits AgentToolsVector storesGrouped by providerIntegrationsAgent toolkitsMultion ToolkitOn this pageMultion ToolkitThis notebook walks you through connecting LangChain to the MultiOn Client in your browserTo use this toolkit, you will need to add MultiOn Extension to your browser as explained in the MultiOn for Chrome.pip install --upgrade multion > /dev/nullMultiOn Setup​Login to establish connection with your extension.# Authorize connection to your Browser extentionimport multion multion.login()Use Multion Toolkit within an Agent​from langchain.agents.agent_toolkits import create_multion_agentfrom langchain.tools.multion.tool import MultionClientToolfrom langchain.agents.agent_types import AgentTypefrom langchain.chat_models import ChatOpenAIagent_executor = create_multion_agent( llm=ChatOpenAI(temperature=0), tool=MultionClientTool(), agent_type=AgentType.OPENAI_FUNCTIONS, verbose=True)agent.run("show me the weather today")agent.run( "Tweet about Elon Musk")PreviousJSON AgentNextOffice365 ToolkitMultiOn SetupUse Multion Toolkit within an AgentCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc. | https://python.langchain.com/docs/integrations/toolkits/multion |
eb7b2074c7cf-0 | Vectorstore Agent | 🦜�🔗 Langchain | https://python.langchain.com/docs/integrations/toolkits/vectorstore |
eb7b2074c7cf-1 | Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsAmadeus ToolkitAzure Cognitive Services ToolkitCSV AgentDocument ComparisonGitHubGmail ToolkitJiraJSON AgentMultion ToolkitOffice365 ToolkitOpenAPI agentsNatural Language APIsPandas Dataframe AgentPlayWright Browser ToolkitPowerBI Dataset AgentPython AgentSpark Dataframe AgentSpark SQL AgentSQL Database AgentVectorstore AgentXorbits AgentToolsVector storesGrouped by providerIntegrationsAgent toolkitsVectorstore AgentOn this pageVectorstore AgentThis notebook showcases an agent designed to retrieve information from one or more vectorstores, either with or without sources.Create the Vectorstores​from langchain.embeddings.openai import OpenAIEmbeddingsfrom langchain.vectorstores import Chromafrom langchain.text_splitter import CharacterTextSplitterfrom langchain import OpenAI, VectorDBQAllm = OpenAI(temperature=0)from langchain.document_loaders import TextLoaderloader = TextLoader("../../../state_of_the_union.txt")documents = loader.load()text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)texts = text_splitter.split_documents(documents)embeddings = OpenAIEmbeddings()state_of_union_store = Chroma.from_documents( texts, embeddings, collection_name="state-of-union") Running Chroma using direct local API. Using DuckDB in-memory for database. Data will be transient.from langchain.document_loaders import WebBaseLoaderloader = WebBaseLoader("https://beta.ruff.rs/docs/faq/")docs = loader.load()ruff_texts = text_splitter.split_documents(docs)ruff_store = Chroma.from_documents(ruff_texts, embeddings, collection_name="ruff") | https://python.langchain.com/docs/integrations/toolkits/vectorstore |
eb7b2074c7cf-2 | = Chroma.from_documents(ruff_texts, embeddings, collection_name="ruff") Running Chroma using direct local API. Using DuckDB in-memory for database. Data will be transient.Initialize Toolkit and Agent​First, we'll create an agent with a single vectorstore.from langchain.agents.agent_toolkits import ( create_vectorstore_agent, VectorStoreToolkit, VectorStoreInfo,)vectorstore_info = VectorStoreInfo( name="state_of_union_address", description="the most recent state of the Union adress", vectorstore=state_of_union_store,)toolkit = VectorStoreToolkit(vectorstore_info=vectorstore_info)agent_executor = create_vectorstore_agent(llm=llm, toolkit=toolkit, verbose=True)Examples​agent_executor.run( "What did biden say about ketanji brown jackson in the state of the union address?") > Entering new AgentExecutor chain... I need to find the answer in the state of the union address Action: state_of_union_address Action Input: What did biden say about ketanji brown jackson Observation: Biden said that Ketanji Brown Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence. Thought: I now know the final answer Final Answer: Biden said that Ketanji Brown Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence. > Finished chain. "Biden said that Ketanji Brown Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of | https://python.langchain.com/docs/integrations/toolkits/vectorstore |
eb7b2074c7cf-3 | one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence."agent_executor.run( "What did biden say about ketanji brown jackson in the state of the union address? List the source.") > Entering new AgentExecutor chain... I need to use the state_of_union_address_with_sources tool to answer this question. Action: state_of_union_address_with_sources Action Input: What did biden say about ketanji brown jackson Observation: {"answer": " Biden said that he nominated Circuit Court of Appeals Judge Ketanji Brown Jackson to the United States Supreme Court, and that she is one of the nation's top legal minds who will continue Justice Breyer's legacy of excellence.\n", "sources": "../../state_of_the_union.txt"} Thought: I now know the final answer Final Answer: Biden said that he nominated Circuit Court of Appeals Judge Ketanji Brown Jackson to the United States Supreme Court, and that she is one of the nation's top legal minds who will continue Justice Breyer's legacy of excellence. Sources: ../../state_of_the_union.txt > Finished chain. "Biden said that he nominated Circuit Court of Appeals Judge Ketanji Brown Jackson to the United States Supreme Court, and that she is one of the nation's top legal minds who will continue Justice Breyer's legacy of excellence. Sources: ../../state_of_the_union.txt"Multiple Vectorstores​We can also easily use this initialize an agent with multiple vectorstores and use the agent to route between them. To do this. This agent is optimized for routing, so it is a different toolkit and initializer.from langchain.agents.agent_toolkits import ( create_vectorstore_router_agent, | https://python.langchain.com/docs/integrations/toolkits/vectorstore |
eb7b2074c7cf-4 | langchain.agents.agent_toolkits import ( create_vectorstore_router_agent, VectorStoreRouterToolkit, VectorStoreInfo,)ruff_vectorstore_info = VectorStoreInfo( name="ruff", description="Information about the Ruff python linting library", vectorstore=ruff_store,)router_toolkit = VectorStoreRouterToolkit( vectorstores=[vectorstore_info, ruff_vectorstore_info], llm=llm)agent_executor = create_vectorstore_router_agent( llm=llm, toolkit=router_toolkit, verbose=True)Examples​agent_executor.run( "What did biden say about ketanji brown jackson in the state of the union address?") > Entering new AgentExecutor chain... I need to use the state_of_union_address tool to answer this question. Action: state_of_union_address Action Input: What did biden say about ketanji brown jackson Observation: Biden said that Ketanji Brown Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence. Thought: I now know the final answer Final Answer: Biden said that Ketanji Brown Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence. > Finished chain. "Biden said that Ketanji Brown Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence."agent_executor.run("What tool does ruff use to run over Jupyter Notebooks?") > Entering new AgentExecutor | https://python.langchain.com/docs/integrations/toolkits/vectorstore |
eb7b2074c7cf-5 | > Entering new AgentExecutor chain... I need to find out what tool ruff uses to run over Jupyter Notebooks Action: ruff Action Input: What tool does ruff use to run over Jupyter Notebooks? Observation: Ruff is integrated into nbQA, a tool for running linters and code formatters over Jupyter Notebooks. After installing ruff and nbqa, you can run Ruff over a notebook like so: > nbqa ruff Untitled.html Thought: I now know the final answer Final Answer: Ruff is integrated into nbQA, a tool for running linters and code formatters over Jupyter Notebooks. After installing ruff and nbqa, you can run Ruff over a notebook like so: > nbqa ruff Untitled.html > Finished chain. 'Ruff is integrated into nbQA, a tool for running linters and code formatters over Jupyter Notebooks. After installing ruff and nbqa, you can run Ruff over a notebook like so: > nbqa ruff Untitled.html'agent_executor.run( "What tool does ruff use to run over Jupyter Notebooks? Did the president mention that tool in the state of the union?") > Entering new AgentExecutor chain... I need to find out what tool ruff uses and if the president mentioned it in the state of the union. Action: ruff Action Input: What tool does ruff use to run over Jupyter Notebooks? Observation: Ruff is integrated into nbQA, a tool for running linters and code formatters over Jupyter Notebooks. After installing | https://python.langchain.com/docs/integrations/toolkits/vectorstore |
eb7b2074c7cf-6 | a tool for running linters and code formatters over Jupyter Notebooks. After installing ruff and nbqa, you can run Ruff over a notebook like so: > nbqa ruff Untitled.html Thought: I need to find out if the president mentioned nbQA in the state of the union. Action: state_of_union_address Action Input: Did the president mention nbQA in the state of the union? Observation: No, the president did not mention nbQA in the state of the union. Thought: I now know the final answer. Final Answer: No, the president did not mention nbQA in the state of the union. > Finished chain. 'No, the president did not mention nbQA in the state of the union.'PreviousSQL Database AgentNextXorbits AgentCreate the VectorstoresInitialize Toolkit and AgentExamplesMultiple VectorstoresExamplesCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc. | https://python.langchain.com/docs/integrations/toolkits/vectorstore |
0ad455347823-0 | Gmail Toolkit | 🦜�🔗 Langchain | https://python.langchain.com/docs/integrations/toolkits/gmail |
0ad455347823-1 | Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsAmadeus ToolkitAzure Cognitive Services ToolkitCSV AgentDocument ComparisonGitHubGmail ToolkitJiraJSON AgentMultion ToolkitOffice365 ToolkitOpenAPI agentsNatural Language APIsPandas Dataframe AgentPlayWright Browser ToolkitPowerBI Dataset AgentPython AgentSpark Dataframe AgentSpark SQL AgentSQL Database AgentVectorstore AgentXorbits AgentToolsVector storesGrouped by providerIntegrationsAgent toolkitsGmail ToolkitOn this pageGmail ToolkitThis notebook walks through connecting a LangChain email to the Gmail API.To use this toolkit, you will need to set up your credentials explained in the Gmail API docs. Once you've downloaded the credentials.json file, you can start using the Gmail API. Once this is done, we'll install the required libraries.pip install --upgrade google-api-python-client > /dev/nullpip install --upgrade google-auth-oauthlib > /dev/nullpip install --upgrade google-auth-httplib2 > /dev/nullpip install beautifulsoup4 > /dev/null # This is optional but is useful for parsing HTML messagesCreate the Toolkit​By default the toolkit reads the local credentials.json file. You can also manually provide a Credentials object.from langchain.agents.agent_toolkits import GmailToolkittoolkit = GmailToolkit()Customizing Authentication​Behind the scenes, a googleapi resource is created using the following methods. | https://python.langchain.com/docs/integrations/toolkits/gmail |
0ad455347823-2 | you can manually build a googleapi resource for more auth control. from langchain.tools.gmail.utils import build_resource_service, get_gmail_credentials# Can review scopes here https://developers.google.com/gmail/api/auth/scopes# For instance, readonly scope is 'https://www.googleapis.com/auth/gmail.readonly'credentials = get_gmail_credentials( token_file="token.json", scopes=["https://mail.google.com/"], client_secrets_file="credentials.json",)api_resource = build_resource_service(credentials=credentials)toolkit = GmailToolkit(api_resource=api_resource)tools = toolkit.get_tools()tools [GmailCreateDraft(name='create_gmail_draft', description='Use this tool to create a draft email with the provided message fields.', args_schema=<class 'langchain.tools.gmail.create_draft.CreateDraftSchema'>, return_direct=False, verbose=False, callbacks=None, callback_manager=None, api_resource=<googleapiclient.discovery.Resource object at 0x10e5c6d10>), GmailSendMessage(name='send_gmail_message', description='Use this tool to send email messages. The input is the message, recipents', args_schema=None, return_direct=False, verbose=False, callbacks=None, callback_manager=None, api_resource=<googleapiclient.discovery.Resource object at 0x10e5c6d10>), GmailSearch(name='search_gmail', description=('Use this tool to search for email messages or threads. The input must be a valid Gmail query. The output is a JSON list of the requested resource.',), args_schema=<class 'langchain.tools.gmail.search.SearchArgsSchema'>, return_direct=False, verbose=False, callbacks=None, callback_manager=None, api_resource=<googleapiclient.discovery.Resource object at 0x10e5c6d10>), | https://python.langchain.com/docs/integrations/toolkits/gmail |
0ad455347823-3 | object at 0x10e5c6d10>), GmailGetMessage(name='get_gmail_message', description='Use this tool to fetch an email by message ID. Returns the thread ID, snipet, body, subject, and sender.', args_schema=<class 'langchain.tools.gmail.get_message.SearchArgsSchema'>, return_direct=False, verbose=False, callbacks=None, callback_manager=None, api_resource=<googleapiclient.discovery.Resource object at 0x10e5c6d10>), GmailGetThread(name='get_gmail_thread', description=('Use this tool to search for email messages. The input must be a valid Gmail query. The output is a JSON list of messages.',), args_schema=<class 'langchain.tools.gmail.get_thread.GetThreadSchema'>, return_direct=False, verbose=False, callbacks=None, callback_manager=None, api_resource=<googleapiclient.discovery.Resource object at 0x10e5c6d10>)]Use within an Agent​from langchain import OpenAIfrom langchain.agents import initialize_agent, AgentTypellm = OpenAI(temperature=0)agent = initialize_agent( tools=toolkit.get_tools(), llm=llm, agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION,)agent.run( "Create a gmail draft for me to edit of a letter from the perspective of a sentient parrot" " who is looking to collaborate on some research with her" " estranged friend, a cat. Under no circumstances may you send the message, however.") WARNING:root:Failed to load default session, using empty session: 0 WARNING:root:Failed to persist run: {"detail":"Not Found"} 'I have created a draft email for you to | https://python.langchain.com/docs/integrations/toolkits/gmail |
0ad455347823-4 | {"detail":"Not Found"} 'I have created a draft email for you to edit. The draft Id is r5681294731961864018.'agent.run("Could you search in my drafts for the latest email?") WARNING:root:Failed to load default session, using empty session: 0 WARNING:root:Failed to persist run: {"detail":"Not Found"} "The latest email in your drafts is from [email protected] with the subject 'Collaboration Opportunity'. The body of the email reads: 'Dear [Friend], I hope this letter finds you well. I am writing to you in the hopes of rekindling our friendship and to discuss the possibility of collaborating on some research together. I know that we have had our differences in the past, but I believe that we can put them aside and work together for the greater good. I look forward to hearing from you. Sincerely, [Parrot]'"PreviousGitHubNextJiraCreate the ToolkitCustomizing AuthenticationUse within an AgentCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc. | https://python.langchain.com/docs/integrations/toolkits/gmail |
359f73b13b58-0 | Azure Cognitive Services Toolkit | 🦜�🔗 Langchain | https://python.langchain.com/docs/integrations/toolkits/azure_cognitive_services |
359f73b13b58-1 | Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsAmadeus ToolkitAzure Cognitive Services ToolkitCSV AgentDocument ComparisonGitHubGmail ToolkitJiraJSON AgentMultion ToolkitOffice365 ToolkitOpenAPI agentsNatural Language APIsPandas Dataframe AgentPlayWright Browser ToolkitPowerBI Dataset AgentPython AgentSpark Dataframe AgentSpark SQL AgentSQL Database AgentVectorstore AgentXorbits AgentToolsVector storesGrouped by providerIntegrationsAgent toolkitsAzure Cognitive Services ToolkitOn this pageAzure Cognitive Services ToolkitThis toolkit is used to interact with the Azure Cognitive Services API to achieve some multimodal capabilities.Currently There are four tools bundled in this toolkit:AzureCogsImageAnalysisTool: used to extract caption, objects, tags, and text from images. (Note: this tool is not available on Mac OS yet, due to the dependency on azure-ai-vision package, which is only supported on Windows and Linux currently.)AzureCogsFormRecognizerTool: used to extract text, tables, and key-value pairs from documents.AzureCogsSpeech2TextTool: used to transcribe speech to text.AzureCogsText2SpeechTool: used to synthesize text to speech.First, you need to set up an Azure account and create a Cognitive Services resource. You can follow the instructions here to create a resource. Then, you need to get the endpoint, key and region of your resource, and set them as environment variables. You can find them in the "Keys and Endpoint" page of your resource.# !pip install --upgrade azure-ai-formrecognizer > /dev/null# !pip install --upgrade azure-cognitiveservices-speech > /dev/null# For Windows/Linux# !pip install --upgrade azure-ai-vision > | https://python.langchain.com/docs/integrations/toolkits/azure_cognitive_services |
359f73b13b58-2 | > /dev/null# For Windows/Linux# !pip install --upgrade azure-ai-vision > /dev/nullimport osos.environ["OPENAI_API_KEY"] = "sk-"os.environ["AZURE_COGS_KEY"] = ""os.environ["AZURE_COGS_ENDPOINT"] = ""os.environ["AZURE_COGS_REGION"] = ""Create the Toolkit​from langchain.agents.agent_toolkits import AzureCognitiveServicesToolkittoolkit = AzureCognitiveServicesToolkit()[tool.name for tool in toolkit.get_tools()] ['Azure Cognitive Services Image Analysis', 'Azure Cognitive Services Form Recognizer', 'Azure Cognitive Services Speech2Text', 'Azure Cognitive Services Text2Speech']Use within an Agent​from langchain import OpenAIfrom langchain.agents import initialize_agent, AgentTypellm = OpenAI(temperature=0)agent = initialize_agent( tools=toolkit.get_tools(), llm=llm, agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True,)agent.run( "What can I make with these ingredients?" "https://images.openai.com/blob/9ad5a2ab-041f-475f-ad6a-b51899c50182/ingredients.png") > Entering new AgentExecutor chain... Action: ``` { "action": "Azure Cognitive Services Image Analysis", "action_input": "https://images.openai.com/blob/9ad5a2ab-041f-475f-ad6a-b51899c50182/ingredients.png" } ``` | https://python.langchain.com/docs/integrations/toolkits/azure_cognitive_services |
359f73b13b58-3 | } ``` Observation: Caption: a group of eggs and flour in bowls Objects: Egg, Egg, Food Tags: dairy, ingredient, indoor, thickening agent, food, mixing bowl, powder, flour, egg, bowl Thought: I can use the objects and tags to suggest recipes Action: ``` { "action": "Final Answer", "action_input": "You can make pancakes, omelettes, or quiches with these ingredients!" } ``` > Finished chain. 'You can make pancakes, omelettes, or quiches with these ingredients!'audio_file = agent.run("Tell me a joke and read it out for me.") > Entering new AgentExecutor chain... Action: ``` { "action": "Azure Cognitive Services Text2Speech", "action_input": "Why did the chicken cross the playground? To get to the other slide!" } ``` Observation: /tmp/tmpa3uu_j6b.wav Thought: I have the audio file of the joke Action: ``` { "action": "Final Answer", "action_input": "/tmp/tmpa3uu_j6b.wav" } ``` > Finished chain. '/tmp/tmpa3uu_j6b.wav'from IPython import displayaudio = | https://python.langchain.com/docs/integrations/toolkits/azure_cognitive_services |
359f73b13b58-4 | '/tmp/tmpa3uu_j6b.wav'from IPython import displayaudio = display.Audio(audio_file)display.display(audio)PreviousAmadeus ToolkitNextCSV AgentCreate the ToolkitUse within an AgentCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc. | https://python.langchain.com/docs/integrations/toolkits/azure_cognitive_services |
50237cd49062-0 | Amadeus Toolkit | 🦜�🔗 Langchain | https://python.langchain.com/docs/integrations/toolkits/amadeus |
50237cd49062-1 | Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsAmadeus ToolkitAzure Cognitive Services ToolkitCSV AgentDocument ComparisonGitHubGmail ToolkitJiraJSON AgentMultion ToolkitOffice365 ToolkitOpenAPI agentsNatural Language APIsPandas Dataframe AgentPlayWright Browser ToolkitPowerBI Dataset AgentPython AgentSpark Dataframe AgentSpark SQL AgentSQL Database AgentVectorstore AgentXorbits AgentToolsVector storesGrouped by providerIntegrationsAgent toolkitsAmadeus ToolkitOn this pageAmadeus ToolkitThis notebook walks you through connecting LangChain to the Amadeus travel information APITo use this toolkit, you will need to set up your credentials explained in the Amadeus for developers getting started overview. Once you've received a AMADEUS_CLIENT_ID and AMADEUS_CLIENT_SECRET, you can input them as environmental variables below.pip install --upgrade amadeus > /dev/nullAssign Environmental Variables​The toolkit will read the AMADEUS_CLIENT_ID and AMADEUS_CLIENT_SECRET environmental variables to authenticate the user so you need to set them here. You will also need to set your OPENAI_API_KEY to use the agent later.# Set environmental variables hereimport osos.environ["AMADEUS_CLIENT_ID"] = "CLIENT_ID"os.environ["AMADEUS_CLIENT_SECRET"] = "CLIENT_SECRET"os.environ["OPENAI_API_KEY"] = "API_KEY"Create the Amadeus Toolkit and Get Tools​To start, you need to create the toolkit, so you can access its tools later.from langchain.agents.agent_toolkits.amadeus.toolkit import AmadeusToolkittoolkit = AmadeusToolkit()tools = toolkit.get_tools()Use Amadeus Toolkit within an Agent​from | https://python.langchain.com/docs/integrations/toolkits/amadeus |
50237cd49062-2 | = toolkit.get_tools()Use Amadeus Toolkit within an Agent​from langchain import OpenAIfrom langchain.agents import initialize_agent, AgentTypellm = OpenAI(temperature=0)agent = initialize_agent( tools=tools, llm=llm, verbose=False, agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION,)agent.run("What is the name of the airport in Cali, Colombia?") 'The closest airport to Cali, Colombia is Alfonso Bonilla Aragón International Airport (CLO).'agent.run( "What is the departure time of the cheapest flight on August 23, 2023 leaving Dallas, Texas before noon to Lincoln, Nebraska?") 'The cheapest flight on August 23, 2023 leaving Dallas, Texas before noon to Lincoln, Nebraska has a departure time of 16:42 and a total price of 276.08 EURO.'agent.run( "At what time does earliest flight on August 23, 2023 leaving Dallas, Texas to Lincoln, Nebraska land in Nebraska?") 'The earliest flight on August 23, 2023 leaving Dallas, Texas to Lincoln, Nebraska lands in Lincoln, Nebraska at 16:07.'agent.run( "What is the full travel time for the cheapest flight between Portland, Oregon to Dallas, TX on October 3, 2023?") 'The cheapest flight between Portland, Oregon to Dallas, TX on October 3, 2023 is a Spirit Airlines flight with a total price of 84.02 EURO and a total travel time of 8 hours and 43 minutes.'agent.run( "Please draft a concise email from Santiago to Paul, Santiago's travel agent, asking him to book the earliest flight | https://python.langchain.com/docs/integrations/toolkits/amadeus |
50237cd49062-3 | a concise email from Santiago to Paul, Santiago's travel agent, asking him to book the earliest flight from DFW to DCA on Aug 28, 2023. Include all flight details in the email.") 'Dear Paul,\n\nI am writing to request that you book the earliest flight from DFW to DCA on Aug 28, 2023. The flight details are as follows:\n\nFlight 1: DFW to ATL, departing at 7:15 AM, arriving at 10:25 AM, flight number 983, carrier Delta Air Lines\nFlight 2: ATL to DCA, departing at 12:15 PM, arriving at 2:02 PM, flight number 759, carrier Delta Air Lines\n\nThank you for your help.\n\nSincerely,\nSantiago'PreviousAgent toolkitsNextAzure Cognitive Services ToolkitAssign Environmental VariablesCreate the Amadeus Toolkit and Get ToolsUse Amadeus Toolkit within an AgentCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc. | https://python.langchain.com/docs/integrations/toolkits/amadeus |
322323d21da1-0 | SQL Database Agent | 🦜�🔗 Langchain | https://python.langchain.com/docs/integrations/toolkits/sql_database |
322323d21da1-1 | Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKIntegrationsCallbacksChat modelsDocument loadersDocument transformersLLMsMemoryRetrieversText embedding modelsAgent toolkitsAmadeus ToolkitAzure Cognitive Services ToolkitCSV AgentDocument ComparisonGitHubGmail ToolkitJiraJSON AgentMultion ToolkitOffice365 ToolkitOpenAPI agentsNatural Language APIsPandas Dataframe AgentPlayWright Browser ToolkitPowerBI Dataset AgentPython AgentSpark Dataframe AgentSpark SQL AgentSQL Database AgentVectorstore AgentXorbits AgentToolsVector storesGrouped by providerIntegrationsAgent toolkitsSQL Database AgentOn this pageSQL Database AgentThis notebook showcases an agent designed to interact with a sql databases. The agent builds off of SQLDatabaseChain and is designed to answer more general questions about a database, as well as recover from errors.Note that, as this agent is in active development, all answers might not be correct. Additionally, it is not guaranteed that the agent won't perform DML statements on your database given certain questions. Be careful running it on sensitive data!This uses the example Chinook database. To set it up follow the instructions on https://database.guide/2-sample-databases-sqlite/, placing the .db file in a notebooks folder at the root of this repository.Initialization​from langchain.agents import create_sql_agentfrom langchain.agents.agent_toolkits import SQLDatabaseToolkitfrom langchain.sql_database import SQLDatabasefrom langchain.llms.openai import OpenAIfrom langchain.agents import AgentExecutorfrom langchain.agents.agent_types import AgentTypefrom langchain.chat_models import ChatOpenAIdb = SQLDatabase.from_uri("sqlite:///../../../../../notebooks/Chinook.db")toolkit = SQLDatabaseToolkit(db=db, llm=OpenAI(temperature=0))Using ZERO_SHOT_REACT_DESCRIPTION​This | https://python.langchain.com/docs/integrations/toolkits/sql_database |
Subsets and Splits