Unnamed: 0
int64
0
4.66k
page content
stringlengths
23
2k
description
stringlengths
8
925
output
stringlengths
38
2.93k
2,700
AINetwork | 🦜️🔗 Langchain
AI Network is a layer 1 blockchain designed to accommodate
AI Network is a layer 1 blockchain designed to accommodate ->: AINetwork | 🦜️🔗 Langchain
2,701
Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKProvidersAnthropicAWSGoogleMicrosoftOpenAIMoreActiveloop Deep LakeAI21 LabsAimAINetworkAirbyteAirtableAleph AlphaAlibaba Cloud OpensearchAnalyticDBAnnoyAnyscaleApifyArangoDBArgillaArthurArxivAtlasAwaDBAWS DynamoDBAZLyricsBagelDBBananaBasetenBeamBeautiful SoupBiliBiliNIBittensorBlackboardBrave SearchCassandraCerebriumAIChaindeskChromaClarifaiClearMLClickHouseCnosDBCohereCollege ConfidentialCometConfident AIConfluenceC TransformersDashVectorDatabricksDatadog TracingDatadog LogsDataForSEODeepInfraDeepSparseDiffbotDingoDiscordDocArrayDoctranDocugamiDuckDBElasticsearchEpsillaEverNoteFacebook ChatFacebook FaissFigmaFireworksFlyteForefrontAIGitGitBookGoldenGoogle Document AIGoogle SerperGooseAIGPT4AllGradientGraphsignalGrobidGutenbergHacker NewsHazy ResearchHeliconeHologresHTML to textHugging FaceiFixitIMSDbInfinoJavelin AI GatewayJinaKonkoLanceDBLangChain Decorators ✨Llama.cppLog10MarqoMediaWikiDumpMeilisearchMetalMilvusMinimaxMLflow AI GatewayMLflowModalModelScopeModern TreasuryMomentoMongoDB AtlasMotherduckMotörheadMyScaleNeo4jNLPCloudNotion DBNucliaObsidianOpenLLMOpenSearchOpenWeatherMapPetalsPostgres EmbeddingPGVectorPineconePipelineAIPortkeyPredibasePrediction GuardPromptLayerprovidersPsychicPubMedQdrantRay ServeRebuffRedditRedisReplicateRoamRocksetRunhouseRWKV-4ScaNNSearchApiSearxNG Search APISerpAPIShale ProtocolSingleStoreDBscikit-learnSlackspaCySpreedlyStarRocksStochasticAIStripeSupabase (Postgres)NebulaTairTelegramTencentVectorDBTensorFlow DatasetsTigris2MarkdownTrelloTruLensTwitterTypesenseUnstructuredUpstash RedisUSearchVearchVectaraVespaWandB TracingWeights & BiasesWeatherWeaviateWhatsAppWhyLabsWikipediaWolfram AlphaWriterXataXorbits Inference (Xinference)YandexYeager.aiYouTubeZepZillizComponentsLLMsChat modelsDocument loadersDocument transformersText embedding modelsVector storesRetrieversToolsAgents and toolkitsMemoryCallbacksChat
AI Network is a layer 1 blockchain designed to accommodate
AI Network is a layer 1 blockchain designed to accommodate ->: Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKProvidersAnthropicAWSGoogleMicrosoftOpenAIMoreActiveloop Deep LakeAI21 LabsAimAINetworkAirbyteAirtableAleph AlphaAlibaba Cloud OpensearchAnalyticDBAnnoyAnyscaleApifyArangoDBArgillaArthurArxivAtlasAwaDBAWS DynamoDBAZLyricsBagelDBBananaBasetenBeamBeautiful SoupBiliBiliNIBittensorBlackboardBrave SearchCassandraCerebriumAIChaindeskChromaClarifaiClearMLClickHouseCnosDBCohereCollege ConfidentialCometConfident AIConfluenceC TransformersDashVectorDatabricksDatadog TracingDatadog LogsDataForSEODeepInfraDeepSparseDiffbotDingoDiscordDocArrayDoctranDocugamiDuckDBElasticsearchEpsillaEverNoteFacebook ChatFacebook FaissFigmaFireworksFlyteForefrontAIGitGitBookGoldenGoogle Document AIGoogle SerperGooseAIGPT4AllGradientGraphsignalGrobidGutenbergHacker NewsHazy ResearchHeliconeHologresHTML to textHugging FaceiFixitIMSDbInfinoJavelin AI GatewayJinaKonkoLanceDBLangChain Decorators ✨Llama.cppLog10MarqoMediaWikiDumpMeilisearchMetalMilvusMinimaxMLflow AI GatewayMLflowModalModelScopeModern TreasuryMomentoMongoDB AtlasMotherduckMotörheadMyScaleNeo4jNLPCloudNotion DBNucliaObsidianOpenLLMOpenSearchOpenWeatherMapPetalsPostgres EmbeddingPGVectorPineconePipelineAIPortkeyPredibasePrediction GuardPromptLayerprovidersPsychicPubMedQdrantRay ServeRebuffRedditRedisReplicateRoamRocksetRunhouseRWKV-4ScaNNSearchApiSearxNG Search APISerpAPIShale ProtocolSingleStoreDBscikit-learnSlackspaCySpreedlyStarRocksStochasticAIStripeSupabase (Postgres)NebulaTairTelegramTencentVectorDBTensorFlow DatasetsTigris2MarkdownTrelloTruLensTwitterTypesenseUnstructuredUpstash RedisUSearchVearchVectaraVespaWandB TracingWeights & BiasesWeatherWeaviateWhatsAppWhyLabsWikipediaWolfram AlphaWriterXataXorbits Inference (Xinference)YandexYeager.aiYouTubeZepZillizComponentsLLMsChat modelsDocument loadersDocument transformersText embedding modelsVector storesRetrieversToolsAgents and toolkitsMemoryCallbacksChat
2,702
and toolkitsMemoryCallbacksChat loadersProvidersMoreAINetworkOn this pageAINetworkAI Network is a layer 1 blockchain designed to accommodate
AI Network is a layer 1 blockchain designed to accommodate
AI Network is a layer 1 blockchain designed to accommodate ->: and toolkitsMemoryCallbacksChat loadersProvidersMoreAINetworkOn this pageAINetworkAI Network is a layer 1 blockchain designed to accommodate
2,703
large-scale AI models, utilizing a decentralized GPU network powered by the $AIN token, enriching AI-driven NFTs (AINFTs).Installation and Setup​You need to install ain-py python package.pip install ain-pyYou need to set the AIN_BLOCKCHAIN_ACCOUNT_PRIVATE_KEY environmental variable to your AIN Blockchain Account Private Key.Toolkit​See a usage example.from langchain.agents.agent_toolkits.ainetwork.toolkit import AINetworkToolkitPreviousAimNextAirbyteInstallation and SetupToolkitCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
AI Network is a layer 1 blockchain designed to accommodate
AI Network is a layer 1 blockchain designed to accommodate ->: large-scale AI models, utilizing a decentralized GPU network powered by the $AIN token, enriching AI-driven NFTs (AINFTs).Installation and Setup​You need to install ain-py python package.pip install ain-pyYou need to set the AIN_BLOCKCHAIN_ACCOUNT_PRIVATE_KEY environmental variable to your AIN Blockchain Account Private Key.Toolkit​See a usage example.from langchain.agents.agent_toolkits.ainetwork.toolkit import AINetworkToolkitPreviousAimNextAirbyteInstallation and SetupToolkitCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
2,704
AINetwork | 🦜️🔗 Langchain
AI Network is a layer 1 blockchain designed to accommodate large-scale AI models, utilizing a decentralized GPU network powered by the $AIN token, enriching AI-driven NFTs (AINFTs).
AI Network is a layer 1 blockchain designed to accommodate large-scale AI models, utilizing a decentralized GPU network powered by the $AIN token, enriching AI-driven NFTs (AINFTs). ->: AINetwork | 🦜️🔗 Langchain
2,705
Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKProvidersAnthropicAWSGoogleMicrosoftOpenAIMoreComponentsLLMsChat modelsDocument loadersDocument transformersText embedding modelsVector storesRetrieversToolsAgents and toolkitsAINetworkAirbyte Question AnsweringAmadeusAzure Cognitive ServicesClickUp Langchain ToolkitCSVDocument ComparisonGithubGitlabGmailGoogle Drive toolJiraJSONMultiOnOffice365OpenAPINatural Language APIsPandas DataframePlayWright BrowserPowerBI DatasetPythonSpark DataframeSpark SQLSQL DatabaseVectorstoreXorbitsMemoryCallbacksChat loadersComponentsAgents and toolkitsAINetworkOn this pageAINetworkAI Network is a layer 1 blockchain designed to accommodate large-scale AI models, utilizing a decentralized GPU network powered by the $AIN token, enriching AI-driven NFTs (AINFTs).The AINetwork Toolkit is a set of tools for interacting with the AINetwork Blockchain. These tools allow you to transfer AIN, read and write values, create apps, and set permissions for specific paths within the blockchain database.Installing dependencies​Before using the AINetwork Toolkit, you need to install the ain-py package. You can install it with pip:pip install ain-pySet environmental variables​You need to set the AIN_BLOCKCHAIN_ACCOUNT_PRIVATE_KEY environmental variable to your AIN Blockchain Account Private Key.import osos.environ["AIN_BLOCKCHAIN_ACCOUNT_PRIVATE_KEY"] = ""Get AIN Blockchain private key​import osfrom ain.account import Accountif os.environ.get("AIN_BLOCKCHAIN_ACCOUNT_PRIVATE_KEY", None): account = Account(os.environ["AIN_BLOCKCHAIN_ACCOUNT_PRIVATE_KEY"])else: account = Account.create() os.environ["AIN_BLOCKCHAIN_ACCOUNT_PRIVATE_KEY"] = account.private_key print( f"""address: {account.address}private_key: {account.private_key}""" )# IMPORTANT: If you plan to use this account in the future, make sure to save the# private key in a secure place. Losing access
AI Network is a layer 1 blockchain designed to accommodate large-scale AI models, utilizing a decentralized GPU network powered by the $AIN token, enriching AI-driven NFTs (AINFTs).
AI Network is a layer 1 blockchain designed to accommodate large-scale AI models, utilizing a decentralized GPU network powered by the $AIN token, enriching AI-driven NFTs (AINFTs). ->: Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKProvidersAnthropicAWSGoogleMicrosoftOpenAIMoreComponentsLLMsChat modelsDocument loadersDocument transformersText embedding modelsVector storesRetrieversToolsAgents and toolkitsAINetworkAirbyte Question AnsweringAmadeusAzure Cognitive ServicesClickUp Langchain ToolkitCSVDocument ComparisonGithubGitlabGmailGoogle Drive toolJiraJSONMultiOnOffice365OpenAPINatural Language APIsPandas DataframePlayWright BrowserPowerBI DatasetPythonSpark DataframeSpark SQLSQL DatabaseVectorstoreXorbitsMemoryCallbacksChat loadersComponentsAgents and toolkitsAINetworkOn this pageAINetworkAI Network is a layer 1 blockchain designed to accommodate large-scale AI models, utilizing a decentralized GPU network powered by the $AIN token, enriching AI-driven NFTs (AINFTs).The AINetwork Toolkit is a set of tools for interacting with the AINetwork Blockchain. These tools allow you to transfer AIN, read and write values, create apps, and set permissions for specific paths within the blockchain database.Installing dependencies​Before using the AINetwork Toolkit, you need to install the ain-py package. You can install it with pip:pip install ain-pySet environmental variables​You need to set the AIN_BLOCKCHAIN_ACCOUNT_PRIVATE_KEY environmental variable to your AIN Blockchain Account Private Key.import osos.environ["AIN_BLOCKCHAIN_ACCOUNT_PRIVATE_KEY"] = ""Get AIN Blockchain private key​import osfrom ain.account import Accountif os.environ.get("AIN_BLOCKCHAIN_ACCOUNT_PRIVATE_KEY", None): account = Account(os.environ["AIN_BLOCKCHAIN_ACCOUNT_PRIVATE_KEY"])else: account = Account.create() os.environ["AIN_BLOCKCHAIN_ACCOUNT_PRIVATE_KEY"] = account.private_key print( f"""address: {account.address}private_key: {account.private_key}""" )# IMPORTANT: If you plan to use this account in the future, make sure to save the# private key in a secure place. Losing access
2,706
private key in a secure place. Losing access to your private key means losing# access to your account. address: 0x5BEB4Defa2ccc274498416Fd7Cb34235DbC122Ac private_key: f5e2f359bb6b7836a2ac70815473d1a290c517f847d096f5effe818de8c2cf14 Initialize the AINetwork Toolkit‚ÄãYou can initialize the AINetwork Toolkit like this:from langchain.agents.agent_toolkits.ainetwork.toolkit import AINetworkToolkittoolkit = AINetworkToolkit()tools = toolkit.get_tools()address = tools[0].interface.wallet.defaultAccount.addressInitialize the Agent with the AINetwork Toolkit‚ÄãYou can initialize the agent with the AINetwork Toolkit like this:from langchain.chat_models import ChatOpenAIfrom langchain.agents import initialize_agent, AgentTypellm = ChatOpenAI(temperature=0)agent = initialize_agent( tools=tools, llm=llm, verbose=True, agent=AgentType.OPENAI_FUNCTIONS,)Example Usage‚ÄãHere are some examples of how you can use the agent with the AINetwork Toolkit:Define App name to test‚ÄãappName = f"langchain_demo_{address.lower()}"Create an app in the AINetwork Blockchain database‚Äãprint( agent.run( f"Create an app in the AINetwork Blockchain database with the name {appName}" )) > Entering new AgentExecutor chain... Invoking: `AINappOps` with `{'type': 'SET_ADMIN', 'appName': 'langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac'}` {"tx_hash": "0x018846d6a9fc111edb1a2246ae2484ef05573bd2c584f3d0da155fa4b4936a9e", "result": {"gas_amount_total": {"bandwidth": {"service": 4002, "app": {"langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac": 2}}, "state": {"service": 1640}}, "gas_cost_total": 0, "func_results": {"_createApp": {"op_results": {"0": {"path": "/apps/langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac", "result": {"code": 0, "bandwidth_gas_amount": 1}}, "1": {"path": "/apps/langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac", "result": {"code": 0, "bandwidth_gas_amount": 1}}, "2": {"path":
AI Network is a layer 1 blockchain designed to accommodate large-scale AI models, utilizing a decentralized GPU network powered by the $AIN token, enriching AI-driven NFTs (AINFTs).
AI Network is a layer 1 blockchain designed to accommodate large-scale AI models, utilizing a decentralized GPU network powered by the $AIN token, enriching AI-driven NFTs (AINFTs). ->: private key in a secure place. Losing access to your private key means losing# access to your account. address: 0x5BEB4Defa2ccc274498416Fd7Cb34235DbC122Ac private_key: f5e2f359bb6b7836a2ac70815473d1a290c517f847d096f5effe818de8c2cf14 Initialize the AINetwork Toolkit‚ÄãYou can initialize the AINetwork Toolkit like this:from langchain.agents.agent_toolkits.ainetwork.toolkit import AINetworkToolkittoolkit = AINetworkToolkit()tools = toolkit.get_tools()address = tools[0].interface.wallet.defaultAccount.addressInitialize the Agent with the AINetwork Toolkit‚ÄãYou can initialize the agent with the AINetwork Toolkit like this:from langchain.chat_models import ChatOpenAIfrom langchain.agents import initialize_agent, AgentTypellm = ChatOpenAI(temperature=0)agent = initialize_agent( tools=tools, llm=llm, verbose=True, agent=AgentType.OPENAI_FUNCTIONS,)Example Usage‚ÄãHere are some examples of how you can use the agent with the AINetwork Toolkit:Define App name to test‚ÄãappName = f"langchain_demo_{address.lower()}"Create an app in the AINetwork Blockchain database‚Äãprint( agent.run( f"Create an app in the AINetwork Blockchain database with the name {appName}" )) > Entering new AgentExecutor chain... Invoking: `AINappOps` with `{'type': 'SET_ADMIN', 'appName': 'langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac'}` {"tx_hash": "0x018846d6a9fc111edb1a2246ae2484ef05573bd2c584f3d0da155fa4b4936a9e", "result": {"gas_amount_total": {"bandwidth": {"service": 4002, "app": {"langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac": 2}}, "state": {"service": 1640}}, "gas_cost_total": 0, "func_results": {"_createApp": {"op_results": {"0": {"path": "/apps/langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac", "result": {"code": 0, "bandwidth_gas_amount": 1}}, "1": {"path": "/apps/langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac", "result": {"code": 0, "bandwidth_gas_amount": 1}}, "2": {"path":
2,707
0, "bandwidth_gas_amount": 1}}, "2": {"path": "/manage_app/langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac/config/admin", "result": {"code": 0, "bandwidth_gas_amount": 1}}}, "code": 0, "bandwidth_gas_amount": 2000}}, "code": 0, "bandwidth_gas_amount": 2001, "gas_amount_charged": 5642}}The app with the name "langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac" has been created in the AINetwork Blockchain database. > Finished chain. The app with the name "langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac" has been created in the AINetwork Blockchain database.Set a value at a given path in the AINetwork Blockchain database‚Äãprint( agent.run(f"Set the value {{1: 2, '34': 56}} at the path /apps/{appName}/object .")) > Entering new AgentExecutor chain... Invoking: `AINvalueOps` with `{'type': 'SET', 'path': '/apps/langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac/object', 'value': {'1': 2, '34': 56}}` {"tx_hash": "0x3d1a16d9808830088cdf4d37f90f4b1fa1242e2d5f6f983829064f45107b5279", "result": {"gas_amount_total": {"bandwidth": {"service": 0, "app": {"langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac": 1}}, "state": {"service": 0, "app": {"langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac": 674}}}, "gas_cost_total": 0, "code": 0, "bandwidth_gas_amount": 1, "gas_amount_charged": 0}}The value {1: 2, '34': 56} has been set at the path /apps/langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac/object. > Finished chain. The value {1: 2, '34': 56} has been set at the path /apps/langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac/object.Set permissions for a path in the AINetwork Blockchain database‚Äãprint( agent.run( f"Set the write permissions for the path /apps/{appName}/user/$from with the" " eval string auth.addr===$from ." )) > Entering new AgentExecutor chain... Invoking: `AINruleOps` with `{'type': 'SET', 'path':
AI Network is a layer 1 blockchain designed to accommodate large-scale AI models, utilizing a decentralized GPU network powered by the $AIN token, enriching AI-driven NFTs (AINFTs).
AI Network is a layer 1 blockchain designed to accommodate large-scale AI models, utilizing a decentralized GPU network powered by the $AIN token, enriching AI-driven NFTs (AINFTs). ->: 0, "bandwidth_gas_amount": 1}}, "2": {"path": "/manage_app/langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac/config/admin", "result": {"code": 0, "bandwidth_gas_amount": 1}}}, "code": 0, "bandwidth_gas_amount": 2000}}, "code": 0, "bandwidth_gas_amount": 2001, "gas_amount_charged": 5642}}The app with the name "langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac" has been created in the AINetwork Blockchain database. > Finished chain. The app with the name "langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac" has been created in the AINetwork Blockchain database.Set a value at a given path in the AINetwork Blockchain database‚Äãprint( agent.run(f"Set the value {{1: 2, '34': 56}} at the path /apps/{appName}/object .")) > Entering new AgentExecutor chain... Invoking: `AINvalueOps` with `{'type': 'SET', 'path': '/apps/langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac/object', 'value': {'1': 2, '34': 56}}` {"tx_hash": "0x3d1a16d9808830088cdf4d37f90f4b1fa1242e2d5f6f983829064f45107b5279", "result": {"gas_amount_total": {"bandwidth": {"service": 0, "app": {"langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac": 1}}, "state": {"service": 0, "app": {"langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac": 674}}}, "gas_cost_total": 0, "code": 0, "bandwidth_gas_amount": 1, "gas_amount_charged": 0}}The value {1: 2, '34': 56} has been set at the path /apps/langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac/object. > Finished chain. The value {1: 2, '34': 56} has been set at the path /apps/langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac/object.Set permissions for a path in the AINetwork Blockchain database‚Äãprint( agent.run( f"Set the write permissions for the path /apps/{appName}/user/$from with the" " eval string auth.addr===$from ." )) > Entering new AgentExecutor chain... Invoking: `AINruleOps` with `{'type': 'SET', 'path':
2,708
`AINruleOps` with `{'type': 'SET', 'path': '/apps/langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac/user/$from', 'eval': 'auth.addr===$from'}` {"tx_hash": "0x37d5264e580f6a217a347059a735bfa9eb5aad85ff28a95531c6dc09252664d2", "result": {"gas_amount_total": {"bandwidth": {"service": 0, "app": {"langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac": 1}}, "state": {"service": 0, "app": {"langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac": 712}}}, "gas_cost_total": 0, "code": 0, "bandwidth_gas_amount": 1, "gas_amount_charged": 0}}The write permissions for the path `/apps/langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac/user/$from` have been set with the eval string `auth.addr===$from`. > Finished chain. The write permissions for the path `/apps/langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac/user/$from` have been set with the eval string `auth.addr===$from`.Retrieve the permissions for a path in the AINetwork Blockchain database‚Äãprint(agent.run(f"Retrieve the permissions for the path /apps/{appName}.")) > Entering new AgentExecutor chain... Invoking: `AINownerOps` with `{'type': 'GET', 'path': '/apps/langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac'}` {".owner": {"owners": {"0x5BEB4Defa2ccc274498416Fd7Cb34235DbC122Ac": {"branch_owner": true, "write_function": true, "write_owner": true, "write_rule": true}}}}The permissions for the path /apps/langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac are as follows: - Address: 0x5BEB4Defa2ccc274498416Fd7Cb34235DbC122Ac - branch_owner: true - write_function: true - write_owner: true - write_rule: true > Finished chain. The permissions for the path /apps/langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac are as follows: - Address: 0x5BEB4Defa2ccc274498416Fd7Cb34235DbC122Ac - branch_owner: true - write_function: true - write_owner: true - write_rule:
AI Network is a layer 1 blockchain designed to accommodate large-scale AI models, utilizing a decentralized GPU network powered by the $AIN token, enriching AI-driven NFTs (AINFTs).
AI Network is a layer 1 blockchain designed to accommodate large-scale AI models, utilizing a decentralized GPU network powered by the $AIN token, enriching AI-driven NFTs (AINFTs). ->: `AINruleOps` with `{'type': 'SET', 'path': '/apps/langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac/user/$from', 'eval': 'auth.addr===$from'}` {"tx_hash": "0x37d5264e580f6a217a347059a735bfa9eb5aad85ff28a95531c6dc09252664d2", "result": {"gas_amount_total": {"bandwidth": {"service": 0, "app": {"langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac": 1}}, "state": {"service": 0, "app": {"langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac": 712}}}, "gas_cost_total": 0, "code": 0, "bandwidth_gas_amount": 1, "gas_amount_charged": 0}}The write permissions for the path `/apps/langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac/user/$from` have been set with the eval string `auth.addr===$from`. > Finished chain. The write permissions for the path `/apps/langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac/user/$from` have been set with the eval string `auth.addr===$from`.Retrieve the permissions for a path in the AINetwork Blockchain database‚Äãprint(agent.run(f"Retrieve the permissions for the path /apps/{appName}.")) > Entering new AgentExecutor chain... Invoking: `AINownerOps` with `{'type': 'GET', 'path': '/apps/langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac'}` {".owner": {"owners": {"0x5BEB4Defa2ccc274498416Fd7Cb34235DbC122Ac": {"branch_owner": true, "write_function": true, "write_owner": true, "write_rule": true}}}}The permissions for the path /apps/langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac are as follows: - Address: 0x5BEB4Defa2ccc274498416Fd7Cb34235DbC122Ac - branch_owner: true - write_function: true - write_owner: true - write_rule: true > Finished chain. The permissions for the path /apps/langchain_demo_0x5beb4defa2ccc274498416fd7cb34235dbc122ac are as follows: - Address: 0x5BEB4Defa2ccc274498416Fd7Cb34235DbC122Ac - branch_owner: true - write_function: true - write_owner: true - write_rule:
2,709
true - write_owner: true - write_rule: trueGet AIN from faucet‚Äãcurl http://faucet.ainetwork.ai/api/test/{address}/ {"result":"0x0eb07b67b7d0a702cb60e865d3deafff3070d8508077ef793d69d6819fd92ea3","time":1692348112376}Get AIN Balance‚Äãprint(agent.run(f"Check AIN balance of {address}")) > Entering new AgentExecutor chain... Invoking: `AINvalueOps` with `{'type': 'GET', 'path': '/accounts/0x5BEB4Defa2ccc274498416Fd7Cb34235DbC122Ac/balance'}` 100The AIN balance of address 0x5BEB4Defa2ccc274498416Fd7Cb34235DbC122Ac is 100 AIN. > Finished chain. The AIN balance of address 0x5BEB4Defa2ccc274498416Fd7Cb34235DbC122Ac is 100 AIN.Transfer AIN‚Äãprint( agent.run( "Transfer 100 AIN to the address 0x19937b227b1b13f29e7ab18676a89ea3bdea9c5b" )) > Entering new AgentExecutor chain... Invoking: `AINtransfer` with `{'address': '0x19937b227b1b13f29e7ab18676a89ea3bdea9c5b', 'amount': 100}` {"tx_hash": "0xa59d15d23373bcc00e413ac8ba18cb016bb3bdd54058d62606aec688c6ad3d2e", "result": {"gas_amount_total": {"bandwidth": {"service": 3}, "state": {"service": 866}}, "gas_cost_total": 0, "func_results": {"_transfer": {"op_results": {"0": {"path": "/accounts/0x5BEB4Defa2ccc274498416Fd7Cb34235DbC122Ac/balance", "result": {"code": 0, "bandwidth_gas_amount": 1}}, "1": {"path": "/accounts/0x19937B227b1b13f29e7AB18676a89EA3BDEA9C5b/balance", "result": {"code": 0, "bandwidth_gas_amount": 1}}}, "code": 0, "bandwidth_gas_amount": 0}}, "code": 0, "bandwidth_gas_amount": 1, "gas_amount_charged": 869}}The transfer of 100 AIN to the address 0x19937b227b1b13f29e7ab18676a89ea3bdea9c5b was successful. The transaction hash is 0xa59d15d23373bcc00e413ac8ba18cb016bb3bdd54058d62606aec688c6ad3d2e. > Finished chain. The transfer of 100 AIN to the address 0x19937b227b1b13f29e7ab18676a89ea3bdea9c5b was successful. The transaction hash is
AI Network is a layer 1 blockchain designed to accommodate large-scale AI models, utilizing a decentralized GPU network powered by the $AIN token, enriching AI-driven NFTs (AINFTs).
AI Network is a layer 1 blockchain designed to accommodate large-scale AI models, utilizing a decentralized GPU network powered by the $AIN token, enriching AI-driven NFTs (AINFTs). ->: true - write_owner: true - write_rule: trueGet AIN from faucet‚Äãcurl http://faucet.ainetwork.ai/api/test/{address}/ {"result":"0x0eb07b67b7d0a702cb60e865d3deafff3070d8508077ef793d69d6819fd92ea3","time":1692348112376}Get AIN Balance‚Äãprint(agent.run(f"Check AIN balance of {address}")) > Entering new AgentExecutor chain... Invoking: `AINvalueOps` with `{'type': 'GET', 'path': '/accounts/0x5BEB4Defa2ccc274498416Fd7Cb34235DbC122Ac/balance'}` 100The AIN balance of address 0x5BEB4Defa2ccc274498416Fd7Cb34235DbC122Ac is 100 AIN. > Finished chain. The AIN balance of address 0x5BEB4Defa2ccc274498416Fd7Cb34235DbC122Ac is 100 AIN.Transfer AIN‚Äãprint( agent.run( "Transfer 100 AIN to the address 0x19937b227b1b13f29e7ab18676a89ea3bdea9c5b" )) > Entering new AgentExecutor chain... Invoking: `AINtransfer` with `{'address': '0x19937b227b1b13f29e7ab18676a89ea3bdea9c5b', 'amount': 100}` {"tx_hash": "0xa59d15d23373bcc00e413ac8ba18cb016bb3bdd54058d62606aec688c6ad3d2e", "result": {"gas_amount_total": {"bandwidth": {"service": 3}, "state": {"service": 866}}, "gas_cost_total": 0, "func_results": {"_transfer": {"op_results": {"0": {"path": "/accounts/0x5BEB4Defa2ccc274498416Fd7Cb34235DbC122Ac/balance", "result": {"code": 0, "bandwidth_gas_amount": 1}}, "1": {"path": "/accounts/0x19937B227b1b13f29e7AB18676a89EA3BDEA9C5b/balance", "result": {"code": 0, "bandwidth_gas_amount": 1}}}, "code": 0, "bandwidth_gas_amount": 0}}, "code": 0, "bandwidth_gas_amount": 1, "gas_amount_charged": 869}}The transfer of 100 AIN to the address 0x19937b227b1b13f29e7ab18676a89ea3bdea9c5b was successful. The transaction hash is 0xa59d15d23373bcc00e413ac8ba18cb016bb3bdd54058d62606aec688c6ad3d2e. > Finished chain. The transfer of 100 AIN to the address 0x19937b227b1b13f29e7ab18676a89ea3bdea9c5b was successful. The transaction hash is
2,710
was successful. The transaction hash is 0xa59d15d23373bcc00e413ac8ba18cb016bb3bdd54058d62606aec688c6ad3d2e.PreviousAgents and toolkitsNextAirbyte Question AnsweringInstalling dependenciesSet environmental variablesGet AIN Blockchain private keyInitialize the AINetwork ToolkitInitialize the Agent with the AINetwork ToolkitExample UsageDefine App name to testCreate an app in the AINetwork Blockchain databaseSet a value at a given path in the AINetwork Blockchain databaseSet permissions for a path in the AINetwork Blockchain databaseRetrieve the permissions for a path in the AINetwork Blockchain databaseGet AIN from faucetGet AIN BalanceTransfer AINCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
AI Network is a layer 1 blockchain designed to accommodate large-scale AI models, utilizing a decentralized GPU network powered by the $AIN token, enriching AI-driven NFTs (AINFTs).
AI Network is a layer 1 blockchain designed to accommodate large-scale AI models, utilizing a decentralized GPU network powered by the $AIN token, enriching AI-driven NFTs (AINFTs). ->: was successful. The transaction hash is 0xa59d15d23373bcc00e413ac8ba18cb016bb3bdd54058d62606aec688c6ad3d2e.PreviousAgents and toolkitsNextAirbyte Question AnsweringInstalling dependenciesSet environmental variablesGet AIN Blockchain private keyInitialize the AINetwork ToolkitInitialize the Agent with the AINetwork ToolkitExample UsageDefine App name to testCreate an app in the AINetwork Blockchain databaseSet a value at a given path in the AINetwork Blockchain databaseSet permissions for a path in the AINetwork Blockchain databaseRetrieve the permissions for a path in the AINetwork Blockchain databaseGet AIN from faucetGet AIN BalanceTransfer AINCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
2,711
Gmail | 🦜️🔗 Langchain
This notebook walks through connecting a LangChain email to the Gmail API.
This notebook walks through connecting a LangChain email to the Gmail API. ->: Gmail | 🦜️🔗 Langchain
2,712
Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKProvidersAnthropicAWSGoogleMicrosoftOpenAIMoreComponentsLLMsChat modelsDocument loadersDocument transformersText embedding modelsVector storesRetrieversToolsAgents and toolkitsAINetworkAirbyte Question AnsweringAmadeusAzure Cognitive ServicesClickUp Langchain ToolkitCSVDocument ComparisonGithubGitlabGmailGoogle Drive toolJiraJSONMultiOnOffice365OpenAPINatural Language APIsPandas DataframePlayWright BrowserPowerBI DatasetPythonSpark DataframeSpark SQLSQL DatabaseVectorstoreXorbitsMemoryCallbacksChat loadersComponentsAgents and toolkitsGmailOn this pageGmailThis 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.
This notebook walks through connecting a LangChain email to the Gmail API.
This notebook walks through connecting a LangChain email to the Gmail API. ->: Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKProvidersAnthropicAWSGoogleMicrosoftOpenAIMoreComponentsLLMsChat modelsDocument loadersDocument transformersText embedding modelsVector storesRetrieversToolsAgents and toolkitsAINetworkAirbyte Question AnsweringAmadeusAzure Cognitive ServicesClickUp Langchain ToolkitCSVDocument ComparisonGithubGitlabGmailGoogle Drive toolJiraJSONMultiOnOffice365OpenAPINatural Language APIsPandas DataframePlayWright BrowserPowerBI DatasetPythonSpark DataframeSpark SQLSQL DatabaseVectorstoreXorbitsMemoryCallbacksChat loadersComponentsAgents and toolkitsGmailOn this pageGmailThis 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.
2,713
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>), 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,
This notebook walks through connecting a LangChain email to the Gmail API.
This notebook walks through connecting a LangChain email to the Gmail API. ->: 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>), 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,
2,714
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.llms 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 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,
This notebook walks through connecting a LangChain email to the Gmail API.
This notebook walks through connecting a LangChain email to the Gmail API. ->: 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.llms 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 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,
2,715
I look forward to hearing from you. Sincerely, [Parrot]'"PreviousGitlabNextGoogle Drive toolCreate the ToolkitCustomizing AuthenticationUse within an AgentCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
This notebook walks through connecting a LangChain email to the Gmail API.
This notebook walks through connecting a LangChain email to the Gmail API. ->: I look forward to hearing from you. Sincerely, [Parrot]'"PreviousGitlabNextGoogle Drive toolCreate the ToolkitCustomizing AuthenticationUse within an AgentCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
2,716
Xorbits | 🦜️🔗 Langchain
This notebook shows how to use agents to interact with Xorbits Pandas dataframe and Xorbits Numpy ndarray. It is mostly optimized for question answering.
This notebook shows how to use agents to interact with Xorbits Pandas dataframe and Xorbits Numpy ndarray. It is mostly optimized for question answering. ->: Xorbits | 🦜️🔗 Langchain
2,717
Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKProvidersAnthropicAWSGoogleMicrosoftOpenAIMoreComponentsLLMsChat modelsDocument loadersDocument transformersText embedding modelsVector storesRetrieversToolsAgents and toolkitsAINetworkAirbyte Question AnsweringAmadeusAzure Cognitive ServicesClickUp Langchain ToolkitCSVDocument ComparisonGithubGitlabGmailGoogle Drive toolJiraJSONMultiOnOffice365OpenAPINatural Language APIsPandas DataframePlayWright BrowserPowerBI DatasetPythonSpark DataframeSpark SQLSQL DatabaseVectorstoreXorbitsMemoryCallbacksChat loadersComponentsAgents and toolkitsXorbitsOn this pageXorbitsThis notebook shows how to use agents to interact with Xorbits Pandas dataframe and Xorbits Numpy ndarray. 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.Pandas examples​import xorbits.pandas as pdfrom langchain.agents import create_xorbits_agentfrom langchain.llms import OpenAIdata = pd.read_csv("titanic.csv")agent = create_xorbits_agent(OpenAI(temperature=0), data, verbose=True) 0%| | 0.00/100 [00:00<?, ?it/s]agent.run("How many rows and columns are there?") > Entering new chain... Thought: I need to count the number of rows and columns Action: python_repl_ast Action Input: data.shape Observation: (891, 12) Thought: I now know the final answer Final Answer: There are 891 rows and 12 columns. > Finished chain. 'There are 891 rows and 12 columns.'agent.run("How many people are in pclass 1?") > Entering new chain... 0%| | 0.00/100 [00:00<?, ?it/s] Thought: I need to count the number of people in pclass 1 Action: python_repl_ast Action Input: data[data['Pclass'] == 1].shape[0] Observation: 216 Thought: I now know the final
This notebook shows how to use agents to interact with Xorbits Pandas dataframe and Xorbits Numpy ndarray. It is mostly optimized for question answering.
This notebook shows how to use agents to interact with Xorbits Pandas dataframe and Xorbits Numpy ndarray. It is mostly optimized for question answering. ->: Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKProvidersAnthropicAWSGoogleMicrosoftOpenAIMoreComponentsLLMsChat modelsDocument loadersDocument transformersText embedding modelsVector storesRetrieversToolsAgents and toolkitsAINetworkAirbyte Question AnsweringAmadeusAzure Cognitive ServicesClickUp Langchain ToolkitCSVDocument ComparisonGithubGitlabGmailGoogle Drive toolJiraJSONMultiOnOffice365OpenAPINatural Language APIsPandas DataframePlayWright BrowserPowerBI DatasetPythonSpark DataframeSpark SQLSQL DatabaseVectorstoreXorbitsMemoryCallbacksChat loadersComponentsAgents and toolkitsXorbitsOn this pageXorbitsThis notebook shows how to use agents to interact with Xorbits Pandas dataframe and Xorbits Numpy ndarray. 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.Pandas examples​import xorbits.pandas as pdfrom langchain.agents import create_xorbits_agentfrom langchain.llms import OpenAIdata = pd.read_csv("titanic.csv")agent = create_xorbits_agent(OpenAI(temperature=0), data, verbose=True) 0%| | 0.00/100 [00:00<?, ?it/s]agent.run("How many rows and columns are there?") > Entering new chain... Thought: I need to count the number of rows and columns Action: python_repl_ast Action Input: data.shape Observation: (891, 12) Thought: I now know the final answer Final Answer: There are 891 rows and 12 columns. > Finished chain. 'There are 891 rows and 12 columns.'agent.run("How many people are in pclass 1?") > Entering new chain... 0%| | 0.00/100 [00:00<?, ?it/s] Thought: I need to count the number of people in pclass 1 Action: python_repl_ast Action Input: data[data['Pclass'] == 1].shape[0] Observation: 216 Thought: I now know the final
2,718
Observation: 216 Thought: I now know the final answer Final Answer: There are 216 people in pclass 1. > Finished chain. 'There are 216 people in pclass 1.'agent.run("whats the mean age?") > Entering new chain... Thought: I need to calculate the mean age Action: python_repl_ast Action Input: data['Age'].mean() 0%| | 0.00/100 [00:00<?, ?it/s] Observation: 29.69911764705882 Thought: I now know the final answer Final Answer: The mean age is 29.69911764705882. > Finished chain. 'The mean age is 29.69911764705882.'agent.run("Group the data by sex and find the average age for each group") > Entering new chain... Thought: I need to group the data by sex and then find the average age for each group Action: python_repl_ast Action Input: data.groupby('Sex')['Age'].mean() 0%| | 0.00/100 [00:00<?, ?it/s] Observation: Sex female 27.915709 male 30.726645 Name: Age, dtype: float64 Thought: I now know the average age for each group Final Answer: The average age for female passengers is 27.92 and the average age for male passengers is 30.73. > Finished chain. 'The average age for female passengers is 27.92 and the average age for male passengers is 30.73.'agent.run( "Show the number of people whose age is greater than 30 and fare is between 30 and 50 , and pclass is either 1 or 2") > Entering new chain... 0%| | 0.00/100 [00:00<?, ?it/s] Thought: I need to filter the dataframe to get the desired result Action: python_repl_ast Action Input: data[(data['Age'] > 30) & (data['Fare'] > 30) & (data['Fare'] < 50) & ((data['Pclass'] == 1) | (data['Pclass'] == 2))].shape[0] Observation: 20 Thought: I now know the final answer Final Answer: 20 > Finished chain. '20'Numpy examples‚Äãimport xorbits.numpy as npfrom langchain.agents import create_xorbits_agentfrom langchain.llms import
This notebook shows how to use agents to interact with Xorbits Pandas dataframe and Xorbits Numpy ndarray. It is mostly optimized for question answering.
This notebook shows how to use agents to interact with Xorbits Pandas dataframe and Xorbits Numpy ndarray. It is mostly optimized for question answering. ->: Observation: 216 Thought: I now know the final answer Final Answer: There are 216 people in pclass 1. > Finished chain. 'There are 216 people in pclass 1.'agent.run("whats the mean age?") > Entering new chain... Thought: I need to calculate the mean age Action: python_repl_ast Action Input: data['Age'].mean() 0%| | 0.00/100 [00:00<?, ?it/s] Observation: 29.69911764705882 Thought: I now know the final answer Final Answer: The mean age is 29.69911764705882. > Finished chain. 'The mean age is 29.69911764705882.'agent.run("Group the data by sex and find the average age for each group") > Entering new chain... Thought: I need to group the data by sex and then find the average age for each group Action: python_repl_ast Action Input: data.groupby('Sex')['Age'].mean() 0%| | 0.00/100 [00:00<?, ?it/s] Observation: Sex female 27.915709 male 30.726645 Name: Age, dtype: float64 Thought: I now know the average age for each group Final Answer: The average age for female passengers is 27.92 and the average age for male passengers is 30.73. > Finished chain. 'The average age for female passengers is 27.92 and the average age for male passengers is 30.73.'agent.run( "Show the number of people whose age is greater than 30 and fare is between 30 and 50 , and pclass is either 1 or 2") > Entering new chain... 0%| | 0.00/100 [00:00<?, ?it/s] Thought: I need to filter the dataframe to get the desired result Action: python_repl_ast Action Input: data[(data['Age'] > 30) & (data['Fare'] > 30) & (data['Fare'] < 50) & ((data['Pclass'] == 1) | (data['Pclass'] == 2))].shape[0] Observation: 20 Thought: I now know the final answer Final Answer: 20 > Finished chain. '20'Numpy examples‚Äãimport xorbits.numpy as npfrom langchain.agents import create_xorbits_agentfrom langchain.llms import
2,719
create_xorbits_agentfrom langchain.llms import OpenAIarr = np.array([1, 2, 3, 4, 5, 6])agent = create_xorbits_agent(OpenAI(temperature=0), arr, verbose=True) 0%| | 0.00/100 [00:00<?, ?it/s]agent.run("Give the shape of the array ") > Entering new chain... Thought: I need to find out the shape of the array Action: python_repl_ast Action Input: data.shape Observation: (6,) Thought: I now know the final answer Final Answer: The shape of the array is (6,). > Finished chain. 'The shape of the array is (6,).'agent.run("Give the 2nd element of the array ") > Entering new chain... Thought: I need to access the 2nd element of the array Action: python_repl_ast Action Input: data[1] 0%| | 0.00/100 [00:00<?, ?it/s] Observation: 2 Thought: I now know the final answer Final Answer: 2 > Finished chain. '2'agent.run( "Reshape the array into a 2-dimensional array with 2 rows and 3 columns, and then transpose it") > Entering new chain... Thought: I need to reshape the array and then transpose it Action: python_repl_ast Action Input: np.reshape(data, (2,3)).T 0%| | 0.00/100 [00:00<?, ?it/s] Observation: [[1 4] [2 5] [3 6]] Thought: I now know the final answer Final Answer: The reshaped and transposed array is [[1 4], [2 5], [3 6]]. > Finished chain. 'The reshaped and transposed array is [[1 4], [2 5], [3 6]].'agent.run( "Reshape the array into a 2-dimensional array with 3 rows and 2 columns and sum the array along the first axis") > Entering new chain... Thought: I need to reshape the array and then sum it Action: python_repl_ast Action Input: np.sum(np.reshape(data, (3,2)), axis=0) 0%| | 0.00/100 [00:00<?, ?it/s] Observation: [ 9 12] Thought: I now know the final answer Final Answer: The sum of the array along the first axis is [9, 12]. >
This notebook shows how to use agents to interact with Xorbits Pandas dataframe and Xorbits Numpy ndarray. It is mostly optimized for question answering.
This notebook shows how to use agents to interact with Xorbits Pandas dataframe and Xorbits Numpy ndarray. It is mostly optimized for question answering. ->: create_xorbits_agentfrom langchain.llms import OpenAIarr = np.array([1, 2, 3, 4, 5, 6])agent = create_xorbits_agent(OpenAI(temperature=0), arr, verbose=True) 0%| | 0.00/100 [00:00<?, ?it/s]agent.run("Give the shape of the array ") > Entering new chain... Thought: I need to find out the shape of the array Action: python_repl_ast Action Input: data.shape Observation: (6,) Thought: I now know the final answer Final Answer: The shape of the array is (6,). > Finished chain. 'The shape of the array is (6,).'agent.run("Give the 2nd element of the array ") > Entering new chain... Thought: I need to access the 2nd element of the array Action: python_repl_ast Action Input: data[1] 0%| | 0.00/100 [00:00<?, ?it/s] Observation: 2 Thought: I now know the final answer Final Answer: 2 > Finished chain. '2'agent.run( "Reshape the array into a 2-dimensional array with 2 rows and 3 columns, and then transpose it") > Entering new chain... Thought: I need to reshape the array and then transpose it Action: python_repl_ast Action Input: np.reshape(data, (2,3)).T 0%| | 0.00/100 [00:00<?, ?it/s] Observation: [[1 4] [2 5] [3 6]] Thought: I now know the final answer Final Answer: The reshaped and transposed array is [[1 4], [2 5], [3 6]]. > Finished chain. 'The reshaped and transposed array is [[1 4], [2 5], [3 6]].'agent.run( "Reshape the array into a 2-dimensional array with 3 rows and 2 columns and sum the array along the first axis") > Entering new chain... Thought: I need to reshape the array and then sum it Action: python_repl_ast Action Input: np.sum(np.reshape(data, (3,2)), axis=0) 0%| | 0.00/100 [00:00<?, ?it/s] Observation: [ 9 12] Thought: I now know the final answer Final Answer: The sum of the array along the first axis is [9, 12]. >
2,720
array along the first axis is [9, 12]. > Finished chain. 'The sum of the array along the first axis is [9, 12].'arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])agent = create_xorbits_agent(OpenAI(temperature=0), arr, verbose=True) 0%| | 0.00/100 [00:00<?, ?it/s]agent.run("calculate the covariance matrix") > Entering new chain... Thought: I need to use the numpy covariance function Action: python_repl_ast Action Input: np.cov(data) 0%| | 0.00/100 [00:00<?, ?it/s] Observation: [[1. 1. 1.] [1. 1. 1.] [1. 1. 1.]] Thought: I now know the final answer Final Answer: The covariance matrix is [[1. 1. 1.], [1. 1. 1.], [1. 1. 1.]]. > Finished chain. 'The covariance matrix is [[1. 1. 1.], [1. 1. 1.], [1. 1. 1.]].'agent.run("compute the U of Singular Value Decomposition of the matrix") > Entering new chain... Thought: I need to use the SVD function Action: python_repl_ast Action Input: U, S, V = np.linalg.svd(data) Observation: Thought: I now have the U matrix Final Answer: U = [[-0.70710678 -0.70710678] [-0.70710678 0.70710678]] > Finished chain. 'U = [[-0.70710678 -0.70710678]\n [-0.70710678 0.70710678]]'PreviousVectorstoreNextMemoryPandas examplesNumpy examplesCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
This notebook shows how to use agents to interact with Xorbits Pandas dataframe and Xorbits Numpy ndarray. It is mostly optimized for question answering.
This notebook shows how to use agents to interact with Xorbits Pandas dataframe and Xorbits Numpy ndarray. It is mostly optimized for question answering. ->: array along the first axis is [9, 12]. > Finished chain. 'The sum of the array along the first axis is [9, 12].'arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])agent = create_xorbits_agent(OpenAI(temperature=0), arr, verbose=True) 0%| | 0.00/100 [00:00<?, ?it/s]agent.run("calculate the covariance matrix") > Entering new chain... Thought: I need to use the numpy covariance function Action: python_repl_ast Action Input: np.cov(data) 0%| | 0.00/100 [00:00<?, ?it/s] Observation: [[1. 1. 1.] [1. 1. 1.] [1. 1. 1.]] Thought: I now know the final answer Final Answer: The covariance matrix is [[1. 1. 1.], [1. 1. 1.], [1. 1. 1.]]. > Finished chain. 'The covariance matrix is [[1. 1. 1.], [1. 1. 1.], [1. 1. 1.]].'agent.run("compute the U of Singular Value Decomposition of the matrix") > Entering new chain... Thought: I need to use the SVD function Action: python_repl_ast Action Input: U, S, V = np.linalg.svd(data) Observation: Thought: I now have the U matrix Final Answer: U = [[-0.70710678 -0.70710678] [-0.70710678 0.70710678]] > Finished chain. 'U = [[-0.70710678 -0.70710678]\n [-0.70710678 0.70710678]]'PreviousVectorstoreNextMemoryPandas examplesNumpy examplesCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
2,721
Spark Dataframe | 🦜️🔗 Langchain
This notebook shows how to use agents to interact with a Spark DataFrame and Spark Connect. It is mostly optimized for question answering.
This notebook shows how to use agents to interact with a Spark DataFrame and Spark Connect. It is mostly optimized for question answering. ->: Spark Dataframe | 🦜️🔗 Langchain
2,722
Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKProvidersAnthropicAWSGoogleMicrosoftOpenAIMoreComponentsLLMsChat modelsDocument loadersDocument transformersText embedding modelsVector storesRetrieversToolsAgents and toolkitsAINetworkAirbyte Question AnsweringAmadeusAzure Cognitive ServicesClickUp Langchain ToolkitCSVDocument ComparisonGithubGitlabGmailGoogle Drive toolJiraJSONMultiOnOffice365OpenAPINatural Language APIsPandas DataframePlayWright BrowserPowerBI DatasetPythonSpark DataframeSpark SQLSQL DatabaseVectorstoreXorbitsMemoryCallbacksChat loadersComponentsAgents and toolkitsSpark DataframeOn this pageSpark DataframeThis 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..."Spark DataFrame example​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 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
This notebook shows how to use agents to interact with a Spark DataFrame and Spark Connect. It is mostly optimized for question answering.
This notebook shows how to use agents to interact with a Spark DataFrame and Spark Connect. It is mostly optimized for question answering. ->: Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKProvidersAnthropicAWSGoogleMicrosoftOpenAIMoreComponentsLLMsChat modelsDocument loadersDocument transformersText embedding modelsVector storesRetrieversToolsAgents and toolkitsAINetworkAirbyte Question AnsweringAmadeusAzure Cognitive ServicesClickUp Langchain ToolkitCSVDocument ComparisonGithubGitlabGmailGoogle Drive toolJiraJSONMultiOnOffice365OpenAPINatural Language APIsPandas DataframePlayWright BrowserPowerBI DatasetPythonSpark DataframeSpark SQLSQL DatabaseVectorstoreXorbitsMemoryCallbacksChat loadersComponentsAgents and toolkitsSpark DataframeOn this pageSpark DataframeThis 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..."Spark DataFrame example​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 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
2,723
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| 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| 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| 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|
This notebook shows how to use agents to interact with a Spark DataFrame and Spark Connect. It is mostly optimized for question answering.
This notebook shows how to use agents to interact with a Spark DataFrame and Spark Connect. It is mostly optimized for question answering. ->: 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| 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| 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| 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|
2,724
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| 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| +-----------+--------+------+--------------------+------+----+-----+-----+----------------+-------+-----+--------+ 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 to get the
This notebook shows how to use agents to interact with a Spark DataFrame and Spark Connect. It is mostly optimized for question answering.
This notebook shows how to use agents to interact with a Spark DataFrame and Spark Connect. It is mostly optimized for question answering. ->: 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| 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| +-----------+--------+------+--------------------+------+----+-----+-----+----------------+-------+-----+--------+ 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 to get the
2,725
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 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()
This notebook shows how to use agents to interact with a Spark DataFrame and Spark Connect. It is mostly optimized for question answering.
This notebook shows how to use agents to interact with a Spark DataFrame and Spark Connect. It is mostly optimized for question answering. ->: 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 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()
2,726
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| | 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| 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| 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|
This notebook shows how to use agents to interact with a Spark DataFrame and Spark Connect. It is mostly optimized for question answering.
This notebook shows how to use agents to interact with a Spark DataFrame and Spark Connect. It is mostly optimized for question answering. ->: 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| | 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| 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| 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|
2,727
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| 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| +-----------+--------+------+--------------------+------+----+-----+-----+----------------+-------+-----+--------+ 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, 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()PreviousPythonNextSpark SQLSpark DataFrame exampleSpark
This notebook shows how to use agents to interact with a Spark DataFrame and Spark Connect. It is mostly optimized for question answering.
This notebook shows how to use agents to interact with a Spark DataFrame and Spark Connect. It is mostly optimized for question answering. ->: 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| 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| +-----------+--------+------+--------------------+------+----+-----+-----+----------------+-------+-----+--------+ 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, 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()PreviousPythonNextSpark SQLSpark DataFrame exampleSpark
2,728
SQLSpark DataFrame exampleSpark Connect exampleCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
This notebook shows how to use agents to interact with a Spark DataFrame and Spark Connect. It is mostly optimized for question answering.
This notebook shows how to use agents to interact with a Spark DataFrame and Spark Connect. It is mostly optimized for question answering. ->: SQLSpark DataFrame exampleSpark Connect exampleCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
2,729
Amadeus | 🦜️🔗 Langchain
This notebook walks you through connecting LangChain to the Amadeus travel information API
This notebook walks you through connecting LangChain to the Amadeus travel information API ->: Amadeus | 🦜️🔗 Langchain
2,730
Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKProvidersAnthropicAWSGoogleMicrosoftOpenAIMoreComponentsLLMsChat modelsDocument loadersDocument transformersText embedding modelsVector storesRetrieversToolsAgents and toolkitsAINetworkAirbyte Question AnsweringAmadeusAzure Cognitive ServicesClickUp Langchain ToolkitCSVDocument ComparisonGithubGitlabGmailGoogle Drive toolJiraJSONMultiOnOffice365OpenAPINatural Language APIsPandas DataframePlayWright BrowserPowerBI DatasetPythonSpark DataframeSpark SQLSQL DatabaseVectorstoreXorbitsMemoryCallbacksChat loadersComponentsAgents and toolkitsAmadeusOn this pageAmadeusThis 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 langchain.llms import OpenAIfrom langchain.agents import initialize_agent, AgentTypellm = OpenAI(temperature=0)agent = initialize_agent( tools=tools, llm=llm, verbose=False,
This notebook walks you through connecting LangChain to the Amadeus travel information API
This notebook walks you through connecting LangChain to the Amadeus travel information API ->: Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKProvidersAnthropicAWSGoogleMicrosoftOpenAIMoreComponentsLLMsChat modelsDocument loadersDocument transformersText embedding modelsVector storesRetrieversToolsAgents and toolkitsAINetworkAirbyte Question AnsweringAmadeusAzure Cognitive ServicesClickUp Langchain ToolkitCSVDocument ComparisonGithubGitlabGmailGoogle Drive toolJiraJSONMultiOnOffice365OpenAPINatural Language APIsPandas DataframePlayWright BrowserPowerBI DatasetPythonSpark DataframeSpark SQLSQL DatabaseVectorstoreXorbitsMemoryCallbacksChat loadersComponentsAgents and toolkitsAmadeusOn this pageAmadeusThis 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 langchain.llms import OpenAIfrom langchain.agents import initialize_agent, AgentTypellm = OpenAI(temperature=0)agent = initialize_agent( tools=tools, llm=llm, verbose=False,
2,731
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 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'PreviousAirbyte Question AnsweringNextAzure Cognitive ServicesAssign Environmental VariablesCreate the Amadeus Toolkit and Get ToolsUse Amadeus Toolkit within an
This notebook walks you through connecting LangChain to the Amadeus travel information API
This notebook walks you through connecting LangChain to the Amadeus travel information API ->: 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 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'PreviousAirbyte Question AnsweringNextAzure Cognitive ServicesAssign Environmental VariablesCreate the Amadeus Toolkit and Get ToolsUse Amadeus Toolkit within an
2,732
and Get ToolsUse Amadeus Toolkit within an AgentCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
This notebook walks you through connecting LangChain to the Amadeus travel information API
This notebook walks you through connecting LangChain to the Amadeus travel information API ->: and Get ToolsUse Amadeus Toolkit within an AgentCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
2,733
Jira | 🦜️🔗 Langchain
This notebook goes over how to use the Jira toolkit.
This notebook goes over how to use the Jira toolkit. ->: Jira | 🦜️🔗 Langchain
2,734
Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKProvidersAnthropicAWSGoogleMicrosoftOpenAIMoreComponentsLLMsChat modelsDocument loadersDocument transformersText embedding modelsVector storesRetrieversToolsAgents and toolkitsAINetworkAirbyte Question AnsweringAmadeusAzure Cognitive ServicesClickUp Langchain ToolkitCSVDocument ComparisonGithubGitlabGmailGoogle Drive toolJiraJSONMultiOnOffice365OpenAPINatural Language APIsPandas DataframePlayWright BrowserPowerBI DatasetPythonSpark DataframeSpark SQLSQL DatabaseVectorstoreXorbitsMemoryCallbacksChat loadersComponentsAgents and toolkitsJiraJiraThis notebook goes over how to use the Jira toolkit.The Jira toolkit 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
This notebook goes over how to use the Jira toolkit.
This notebook goes over how to use the Jira toolkit. ->: Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKProvidersAnthropicAWSGoogleMicrosoftOpenAIMoreComponentsLLMsChat modelsDocument loadersDocument transformersText embedding modelsVector storesRetrieversToolsAgents and toolkitsAINetworkAirbyte Question AnsweringAmadeusAzure Cognitive ServicesClickUp Langchain ToolkitCSVDocument ComparisonGithubGitlabGmailGoogle Drive toolJiraJSONMultiOnOffice365OpenAPINatural Language APIsPandas DataframePlayWright BrowserPowerBI DatasetPythonSpark DataframeSpark SQLSQL DatabaseVectorstoreXorbitsMemoryCallbacksChat loadersComponentsAgents and toolkitsJiraJiraThis notebook goes over how to use the Jira toolkit.The Jira toolkit 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
2,735
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".'PreviousGoogle Drive toolNextJSONCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
This notebook goes over how to use the Jira toolkit.
This notebook goes over how to use the Jira toolkit. ->: 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".'PreviousGoogle Drive toolNextJSONCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
2,736
CSV | 🦜️🔗 Langchain
This notebook shows how to use agents to interact with data in CSV format. It is mostly optimized for question answering.
This notebook shows how to use agents to interact with data in CSV format. It is mostly optimized for question answering. ->: CSV | 🦜️🔗 Langchain
2,737
Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKProvidersAnthropicAWSGoogleMicrosoftOpenAIMoreComponentsLLMsChat modelsDocument loadersDocument transformersText embedding modelsVector storesRetrieversToolsAgents and toolkitsAINetworkAirbyte Question AnsweringAmadeusAzure Cognitive ServicesClickUp Langchain ToolkitCSVDocument ComparisonGithubGitlabGmailGoogle Drive toolJiraJSONMultiOnOffice365OpenAPINatural Language APIsPandas DataframePlayWright BrowserPowerBI DatasetPythonSpark DataframeSpark SQLSQL DatabaseVectorstoreXorbitsMemoryCallbacksChat loadersComponentsAgents and toolkitsCSVOn this pageCSVThis notebook shows how to use agents to interact with data in CSV format. It is mostly optimized for question answering.NOTE: this agent calls the Pandas DataFrame agent under the hood, which in turn calls the Python agent, which executes LLM generated Python code - this can be bad if the LLM generated Python code is harmful. Use cautiously.from langchain.llms import OpenAIfrom langchain.chat_models import ChatOpenAIfrom langchain.agents.agent_types import AgentTypefrom langchain.agents import create_csv_agentUsing ZERO_SHOT_REACT_DESCRIPTION​This shows how to initialize the agent using the ZERO_SHOT_REACT_DESCRIPTION agent type. Note that this is an alternative to the above.agent = create_csv_agent( OpenAI(temperature=0), "titanic.csv", 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 = create_csv_agent( ChatOpenAI(temperature=0, model="gpt-3.5-turbo-0613"), "titanic.csv", verbose=True, agent_type=AgentType.OPENAI_FUNCTIONS,)agent.run("how many rows are there?") Error in on_chain_start callback: 'name' Invoking: `python_repl_ast` with `df.shape[0]` 891There are 891 rows in the
This notebook shows how to use agents to interact with data in CSV format. It is mostly optimized for question answering.
This notebook shows how to use agents to interact with data in CSV format. It is mostly optimized for question answering. ->: Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKProvidersAnthropicAWSGoogleMicrosoftOpenAIMoreComponentsLLMsChat modelsDocument loadersDocument transformersText embedding modelsVector storesRetrieversToolsAgents and toolkitsAINetworkAirbyte Question AnsweringAmadeusAzure Cognitive ServicesClickUp Langchain ToolkitCSVDocument ComparisonGithubGitlabGmailGoogle Drive toolJiraJSONMultiOnOffice365OpenAPINatural Language APIsPandas DataframePlayWright BrowserPowerBI DatasetPythonSpark DataframeSpark SQLSQL DatabaseVectorstoreXorbitsMemoryCallbacksChat loadersComponentsAgents and toolkitsCSVOn this pageCSVThis notebook shows how to use agents to interact with data in CSV format. It is mostly optimized for question answering.NOTE: this agent calls the Pandas DataFrame agent under the hood, which in turn calls the Python agent, which executes LLM generated Python code - this can be bad if the LLM generated Python code is harmful. Use cautiously.from langchain.llms import OpenAIfrom langchain.chat_models import ChatOpenAIfrom langchain.agents.agent_types import AgentTypefrom langchain.agents import create_csv_agentUsing ZERO_SHOT_REACT_DESCRIPTION​This shows how to initialize the agent using the ZERO_SHOT_REACT_DESCRIPTION agent type. Note that this is an alternative to the above.agent = create_csv_agent( OpenAI(temperature=0), "titanic.csv", 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 = create_csv_agent( ChatOpenAI(temperature=0, model="gpt-3.5-turbo-0613"), "titanic.csv", verbose=True, agent_type=AgentType.OPENAI_FUNCTIONS,)agent.run("how many rows are there?") Error in on_chain_start callback: 'name' Invoking: `python_repl_ast` with `df.shape[0]` 891There are 891 rows in the
2,738
891There are 891 rows in the dataframe. > Finished chain. 'There are 891 rows in the dataframe.'agent.run("how many people have more than 3 siblings") Error in on_chain_start callback: 'name' Invoking: `python_repl_ast` with `df[df['SibSp'] > 3]['PassengerId'].count()` 30There are 30 people in the dataframe who have more than 3 siblings. > Finished chain. 'There are 30 people in the dataframe who have more than 3 siblings.'agent.run("whats the square root of the average age?") Error in on_chain_start callback: 'name' Invoking: `python_repl_ast` with `import pandas as pd import math # Create a dataframe data = {'Age': [22, 38, 26, 35, 35]} df = pd.DataFrame(data) # Calculate the average age average_age = df['Age'].mean() # Calculate the square root of the average age square_root = math.sqrt(average_age) square_root` 5.585696017507576The square root of the average age is approximately 5.59. > Finished chain. 'The square root of the average age is approximately 5.59.'Multi CSV Example‚ÄãThis next part shows how the agent can interact with multiple csv files passed in as a list.agent = create_csv_agent( ChatOpenAI(temperature=0, model="gpt-3.5-turbo-0613"), ["titanic.csv", "titanic_age_fillna.csv"], verbose=True, agent_type=AgentType.OPENAI_FUNCTIONS,)agent.run("how many rows in the age column are different between the two dfs?") Error in on_chain_start callback: 'name' Invoking: `python_repl_ast` with `df1['Age'].nunique() - df2['Age'].nunique()` -1There is 1 row in the age column that is different between the two dataframes. > Finished chain. 'There is 1 row in the age column that is different between the two dataframes.'PreviousClickUp Langchain ToolkitNextDocument ComparisonUsing ZERO_SHOT_REACT_DESCRIPTIONUsing OpenAI FunctionsMulti CSV
This notebook shows how to use agents to interact with data in CSV format. It is mostly optimized for question answering.
This notebook shows how to use agents to interact with data in CSV format. It is mostly optimized for question answering. ->: 891There are 891 rows in the dataframe. > Finished chain. 'There are 891 rows in the dataframe.'agent.run("how many people have more than 3 siblings") Error in on_chain_start callback: 'name' Invoking: `python_repl_ast` with `df[df['SibSp'] > 3]['PassengerId'].count()` 30There are 30 people in the dataframe who have more than 3 siblings. > Finished chain. 'There are 30 people in the dataframe who have more than 3 siblings.'agent.run("whats the square root of the average age?") Error in on_chain_start callback: 'name' Invoking: `python_repl_ast` with `import pandas as pd import math # Create a dataframe data = {'Age': [22, 38, 26, 35, 35]} df = pd.DataFrame(data) # Calculate the average age average_age = df['Age'].mean() # Calculate the square root of the average age square_root = math.sqrt(average_age) square_root` 5.585696017507576The square root of the average age is approximately 5.59. > Finished chain. 'The square root of the average age is approximately 5.59.'Multi CSV Example‚ÄãThis next part shows how the agent can interact with multiple csv files passed in as a list.agent = create_csv_agent( ChatOpenAI(temperature=0, model="gpt-3.5-turbo-0613"), ["titanic.csv", "titanic_age_fillna.csv"], verbose=True, agent_type=AgentType.OPENAI_FUNCTIONS,)agent.run("how many rows in the age column are different between the two dfs?") Error in on_chain_start callback: 'name' Invoking: `python_repl_ast` with `df1['Age'].nunique() - df2['Age'].nunique()` -1There is 1 row in the age column that is different between the two dataframes. > Finished chain. 'There is 1 row in the age column that is different between the two dataframes.'PreviousClickUp Langchain ToolkitNextDocument ComparisonUsing ZERO_SHOT_REACT_DESCRIPTIONUsing OpenAI FunctionsMulti CSV
2,739
OpenAI FunctionsMulti CSV ExampleCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
This notebook shows how to use agents to interact with data in CSV format. It is mostly optimized for question answering.
This notebook shows how to use agents to interact with data in CSV format. It is mostly optimized for question answering. ->: OpenAI FunctionsMulti CSV ExampleCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
2,740
Azure Cognitive Services | 🦜️🔗 Langchain
This toolkit is used to interact with the Azure Cognitive Services API to achieve some multimodal capabilities.
This toolkit is used to interact with the Azure Cognitive Services API to achieve some multimodal capabilities. ->: Azure Cognitive Services | 🦜️🔗 Langchain
2,741
Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKProvidersAnthropicAWSGoogleMicrosoftOpenAIMoreComponentsLLMsChat modelsDocument loadersDocument transformersText embedding modelsVector storesRetrieversToolsAgents and toolkitsAINetworkAirbyte Question AnsweringAmadeusAzure Cognitive ServicesClickUp Langchain ToolkitCSVDocument ComparisonGithubGitlabGmailGoogle Drive toolJiraJSONMultiOnOffice365OpenAPINatural Language APIsPandas DataframePlayWright BrowserPowerBI DatasetPythonSpark DataframeSpark SQLSQL DatabaseVectorstoreXorbitsMemoryCallbacksChat loadersComponentsAgents and toolkitsAzure Cognitive ServicesOn this pageAzure Cognitive ServicesThis 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 > /dev/nullimport osos.environ["OPENAI_API_KEY"] = "sk-"os.environ["AZURE_COGS_KEY"] = ""os.environ["AZURE_COGS_ENDPOINT"] =
This toolkit is used to interact with the Azure Cognitive Services API to achieve some multimodal capabilities.
This toolkit is used to interact with the Azure Cognitive Services API to achieve some multimodal capabilities. ->: Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKProvidersAnthropicAWSGoogleMicrosoftOpenAIMoreComponentsLLMsChat modelsDocument loadersDocument transformersText embedding modelsVector storesRetrieversToolsAgents and toolkitsAINetworkAirbyte Question AnsweringAmadeusAzure Cognitive ServicesClickUp Langchain ToolkitCSVDocument ComparisonGithubGitlabGmailGoogle Drive toolJiraJSONMultiOnOffice365OpenAPINatural Language APIsPandas DataframePlayWright BrowserPowerBI DatasetPythonSpark DataframeSpark SQLSQL DatabaseVectorstoreXorbitsMemoryCallbacksChat loadersComponentsAgents and toolkitsAzure Cognitive ServicesOn this pageAzure Cognitive ServicesThis 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 > /dev/nullimport osos.environ["OPENAI_API_KEY"] = "sk-"os.environ["AZURE_COGS_KEY"] = ""os.environ["AZURE_COGS_ENDPOINT"] =
2,742
= ""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.llms 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" } ``` 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
This toolkit is used to interact with the Azure Cognitive Services API to achieve some multimodal capabilities.
This toolkit is used to interact with the Azure Cognitive Services API to achieve some multimodal capabilities. ->: = ""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.llms 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" } ``` 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
2,743
/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 = display.Audio(audio_file)display.display(audio)PreviousAmadeusNextClickUp Langchain ToolkitCreate the ToolkitUse within an AgentCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
This toolkit is used to interact with the Azure Cognitive Services API to achieve some multimodal capabilities.
This toolkit is used to interact with the Azure Cognitive Services API to achieve some multimodal capabilities. ->: /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 = display.Audio(audio_file)display.display(audio)PreviousAmadeusNextClickUp Langchain ToolkitCreate the ToolkitUse within an AgentCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
2,744
ClickUp Langchain Toolkit | 🦜️🔗 Langchain
Get Authenticated
Get Authenticated ->: ClickUp Langchain Toolkit | 🦜️🔗 Langchain
2,745
Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKProvidersAnthropicAWSGoogleMicrosoftOpenAIMoreComponentsLLMsChat modelsDocument loadersDocument transformersText embedding modelsVector storesRetrieversToolsAgents and toolkitsAINetworkAirbyte Question AnsweringAmadeusAzure Cognitive ServicesClickUp Langchain ToolkitCSVDocument ComparisonGithubGitlabGmailGoogle Drive toolJiraJSONMultiOnOffice365OpenAPINatural Language APIsPandas DataframePlayWright BrowserPowerBI DatasetPythonSpark DataframeSpark SQLSQL DatabaseVectorstoreXorbitsMemoryCallbacksChat loadersComponentsAgents and toolkitsClickUp Langchain ToolkitOn this pageClickUp Langchain Toolkitfrom datetime import datetimefrom langchain.agents.agent_toolkits.clickup.toolkit import ClickupToolkitfrom langchain.agents import AgentType, initialize_agentfrom langchain.llms import OpenAIfrom langchain.utilities.clickup import ClickupAPIWrapperInitGet Authenticated​Create a ClickUp AppFollow these steps to get your client_id and client_secret.Suggestion: use https://google.com as the redirect_uri. This is what we assume in the defaults for this toolkit.Copy/paste them and run the next cell to get your code# Copilot Sandboxoauth_client_id = "ABC..."oauth_client_secret = "123..."redirect_uri = "https://google.com"print('Click this link, select your workspace, click `Connect Workspace`')print(ClickupAPIWrapper.get_access_code_url(oauth_client_id, redirect_uri)) Click this link, select your workspace, click `Connect Workspace` https://app.clickup.com/api?client_id=ABC...&redirect_uri=https://google.comThe url should change to something like this https://www.google.com/?code=THISISMYCODERIGHTHERE.Next, copy/paste the CODE (THISISMYCODERIGHTHERE) generated in the URL in the cell below.code = "THISISMYCODERIGHTHERE"Get Access Token​Then, use the code below to get your access_token.Important: Each code is a one time code that will expire after use.
Get Authenticated
Get Authenticated ->: Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKProvidersAnthropicAWSGoogleMicrosoftOpenAIMoreComponentsLLMsChat modelsDocument loadersDocument transformersText embedding modelsVector storesRetrieversToolsAgents and toolkitsAINetworkAirbyte Question AnsweringAmadeusAzure Cognitive ServicesClickUp Langchain ToolkitCSVDocument ComparisonGithubGitlabGmailGoogle Drive toolJiraJSONMultiOnOffice365OpenAPINatural Language APIsPandas DataframePlayWright BrowserPowerBI DatasetPythonSpark DataframeSpark SQLSQL DatabaseVectorstoreXorbitsMemoryCallbacksChat loadersComponentsAgents and toolkitsClickUp Langchain ToolkitOn this pageClickUp Langchain Toolkitfrom datetime import datetimefrom langchain.agents.agent_toolkits.clickup.toolkit import ClickupToolkitfrom langchain.agents import AgentType, initialize_agentfrom langchain.llms import OpenAIfrom langchain.utilities.clickup import ClickupAPIWrapperInitGet Authenticated​Create a ClickUp AppFollow these steps to get your client_id and client_secret.Suggestion: use https://google.com as the redirect_uri. This is what we assume in the defaults for this toolkit.Copy/paste them and run the next cell to get your code# Copilot Sandboxoauth_client_id = "ABC..."oauth_client_secret = "123..."redirect_uri = "https://google.com"print('Click this link, select your workspace, click `Connect Workspace`')print(ClickupAPIWrapper.get_access_code_url(oauth_client_id, redirect_uri)) Click this link, select your workspace, click `Connect Workspace` https://app.clickup.com/api?client_id=ABC...&redirect_uri=https://google.comThe url should change to something like this https://www.google.com/?code=THISISMYCODERIGHTHERE.Next, copy/paste the CODE (THISISMYCODERIGHTHERE) generated in the URL in the cell below.code = "THISISMYCODERIGHTHERE"Get Access Token​Then, use the code below to get your access_token.Important: Each code is a one time code that will expire after use.
2,746
is a one time code that will expire after use. The access_token can be used for a period of time. Make sure to copy paste the access_token once you get it!access_token = ClickupAPIWrapper.get_access_token(oauth_client_id, oauth_client_secret, code)if access_token is not None: print('Copy/paste this code, into the next cell so you can reuse it!') print(access_token) Error: {'err': 'Code already used', 'ECODE': 'OAUTH_014'} You already used this code once. Go back a step and generate a new code. Our best guess for the url to get a new code is: https://app.clickup.com/api?client_id=B5D61F8EVO04PR0JX0U73984LLS9GI6P&redirect_uri=https://google.comCreate Toolkit‚Äã# Set your access token hereaccess_token = '12345678_myaccesstokengoeshere123'access_token = '81928627_c009bf122ccf36ec3ba3e0ef748b07042c5e4217260042004a5934540cb61527'# Init toolkitclickup_api_wrapper = ClickupAPIWrapper(access_token=access_token)toolkit = ClickupToolkit.from_clickup_api_wrapper(clickup_api_wrapper)print(f'Found team_id: {clickup_api_wrapper.team_id}.\nMost request require the team id, so we store it for you in the toolkit, we assume the first team in your list is the one you want. \nNote: If you know this is the wrong ID, you can pass it at initialization.') Found team_id: 9011010153. Most request require the team id, so we store it for you in the toolkit, we assume the first team in your list is the one you want. Note: If you know this is the wrong ID, you can pass it at initialization.Create Agent‚Äãllm = OpenAI(temperature=0, openai_api_key="")agent = initialize_agent( toolkit.get_tools(), llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)Run# helper function for demodef print_and_run(command): print('\033[94m$ COMMAND\033[0m') print(command) print('\n\033[94m$ AGENT\033[0m') response = agent.run(command) print(''.join(['-']*80)) return responseNavigation‚ÄãYou can get the teams, folder and spaces your user has access
Get Authenticated
Get Authenticated ->: is a one time code that will expire after use. The access_token can be used for a period of time. Make sure to copy paste the access_token once you get it!access_token = ClickupAPIWrapper.get_access_token(oauth_client_id, oauth_client_secret, code)if access_token is not None: print('Copy/paste this code, into the next cell so you can reuse it!') print(access_token) Error: {'err': 'Code already used', 'ECODE': 'OAUTH_014'} You already used this code once. Go back a step and generate a new code. Our best guess for the url to get a new code is: https://app.clickup.com/api?client_id=B5D61F8EVO04PR0JX0U73984LLS9GI6P&redirect_uri=https://google.comCreate Toolkit‚Äã# Set your access token hereaccess_token = '12345678_myaccesstokengoeshere123'access_token = '81928627_c009bf122ccf36ec3ba3e0ef748b07042c5e4217260042004a5934540cb61527'# Init toolkitclickup_api_wrapper = ClickupAPIWrapper(access_token=access_token)toolkit = ClickupToolkit.from_clickup_api_wrapper(clickup_api_wrapper)print(f'Found team_id: {clickup_api_wrapper.team_id}.\nMost request require the team id, so we store it for you in the toolkit, we assume the first team in your list is the one you want. \nNote: If you know this is the wrong ID, you can pass it at initialization.') Found team_id: 9011010153. Most request require the team id, so we store it for you in the toolkit, we assume the first team in your list is the one you want. Note: If you know this is the wrong ID, you can pass it at initialization.Create Agent‚Äãllm = OpenAI(temperature=0, openai_api_key="")agent = initialize_agent( toolkit.get_tools(), llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)Run# helper function for demodef print_and_run(command): print('\033[94m$ COMMAND\033[0m') print(command) print('\n\033[94m$ AGENT\033[0m') response = agent.run(command) print(''.join(['-']*80)) return responseNavigation‚ÄãYou can get the teams, folder and spaces your user has access
2,747
the teams, folder and spaces your user has access toprint_and_run("Get all the teams that the user is authorized to access")print_and_run("Get all the spaces available to the team")print_and_run("Get all the folders for the team") $ COMMAND Get all the teams that the user is authorized to access $ AGENT > Entering new AgentExecutor chain... I need to use the Get Teams tool Action: Get Teams Action Input: No necessary request parameters Observation: {'teams': [{'id': '9011010153', 'name': 'Task Copilot Sandbox Workspace 1', 'members': [{'id': 61681706, 'username': 'Aiswarya ', 'email': '[email protected]', 'initials': 'A'}, {'id': 81928627, 'username': 'Rodrigo Ceballos Lentini', 'email': '[email protected]', 'initials': 'RL'}]}]} Thought: I now know the teams the user is authorized to access Final Answer: The user is authorized to access the team 'Task Copilot Sandbox Workspace 1'. > Finished chain. -------------------------------------------------------------------------------- $ COMMAND Get all the spaces available to the team $ AGENT > Entering new AgentExecutor chain... I need to use the API to get the spaces Action: Get Teams Action Input: No necessary request parameters Observation: {'teams': [{'id': '9011010153', 'name': 'Task Copilot Sandbox Workspace 1', 'members': [{'id': 61681706, 'username': 'Aiswarya ', 'email': '[email protected]', 'initials': 'A'}, {'id': 81928627, 'username': 'Rodrigo Ceballos Lentini', 'email': '[email protected]', 'initials': 'RL'}]}]} Thought: I now have the list of teams Final Answer: The list of teams available to the team is [{'id': '9011010153', 'name': 'Task Copilot Sandbox Workspace 1', 'members': [{'id': 61681706, 'username': 'Aiswarya ', 'email': '[email protected]', 'initials': 'A'}, {'id': 81928627, 'username': 'Rodrigo Ceballos Lentini', 'email': '[email protected]', 'initials': 'RL'}]}] > Finished
Get Authenticated
Get Authenticated ->: the teams, folder and spaces your user has access toprint_and_run("Get all the teams that the user is authorized to access")print_and_run("Get all the spaces available to the team")print_and_run("Get all the folders for the team") $ COMMAND Get all the teams that the user is authorized to access $ AGENT > Entering new AgentExecutor chain... I need to use the Get Teams tool Action: Get Teams Action Input: No necessary request parameters Observation: {'teams': [{'id': '9011010153', 'name': 'Task Copilot Sandbox Workspace 1', 'members': [{'id': 61681706, 'username': 'Aiswarya ', 'email': '[email protected]', 'initials': 'A'}, {'id': 81928627, 'username': 'Rodrigo Ceballos Lentini', 'email': '[email protected]', 'initials': 'RL'}]}]} Thought: I now know the teams the user is authorized to access Final Answer: The user is authorized to access the team 'Task Copilot Sandbox Workspace 1'. > Finished chain. -------------------------------------------------------------------------------- $ COMMAND Get all the spaces available to the team $ AGENT > Entering new AgentExecutor chain... I need to use the API to get the spaces Action: Get Teams Action Input: No necessary request parameters Observation: {'teams': [{'id': '9011010153', 'name': 'Task Copilot Sandbox Workspace 1', 'members': [{'id': 61681706, 'username': 'Aiswarya ', 'email': '[email protected]', 'initials': 'A'}, {'id': 81928627, 'username': 'Rodrigo Ceballos Lentini', 'email': '[email protected]', 'initials': 'RL'}]}]} Thought: I now have the list of teams Final Answer: The list of teams available to the team is [{'id': '9011010153', 'name': 'Task Copilot Sandbox Workspace 1', 'members': [{'id': 61681706, 'username': 'Aiswarya ', 'email': '[email protected]', 'initials': 'A'}, {'id': 81928627, 'username': 'Rodrigo Ceballos Lentini', 'email': '[email protected]', 'initials': 'RL'}]}] > Finished
2,748
'initials': 'RL'}]}] > Finished chain. -------------------------------------------------------------------------------- $ COMMAND Get all the folders for the team $ AGENT > Entering new AgentExecutor chain... I need to get all the folders for the team Action: Get all folders in the workspace Action Input: {"folder_id": "90130119692"} Observation: {'spaces': [{'id': '90110075934', 'name': 'Test Space', 'color': None, 'private': False, 'avatar': None, 'admin_can_manage': False, 'statuses': [{'id': 'p90110075934_lBKIEh3r', 'status': 'Open', 'type': 'open', 'orderindex': 0, 'color': '#d3d3d3'}, {'id': 'p90110075934_AvVAnVqy', 'status': 'in progress', 'type': 'custom', 'orderindex': 1, 'color': '#a875ff'}, {'id': 'p90110075934_SftYWzGt', 'status': 'Closed', 'type': 'closed', 'orderindex': 2, 'color': '#6bc950'}], 'multiple_assignees': True, 'features': {'due_dates': {'enabled': True, 'start_date': True, 'remap_due_dates': False, 'remap_closed_due_date': False}, 'sprints': {'enabled': False}, 'time_tracking': {'enabled': True, 'harvest': False, 'rollup': False}, 'points': {'enabled': False}, 'custom_items': {'enabled': False}, 'priorities': {'enabled': True, 'priorities': [{'color': '#f50000', 'id': '1', 'orderindex': '1', 'priority': 'urgent'}, {'color': '#ffcc00', 'id': '2', 'orderindex': '2', 'priority': 'high'}, {'color': '#6fddff', 'id': '3', 'orderindex': '3', 'priority': 'normal'}, {'color': '#d8d8d8', 'id': '4', 'orderindex': '4', 'priority': 'low'}]}, 'tags': {'enabled': True}, 'check_unresolved': {'enabled': True, 'subtasks': None, 'checklists': None, 'comments': None}, 'zoom': {'enabled': False}, 'milestones': {'enabled': False}, 'custom_fields': {'enabled': True}, 'dependency_warning': {'enabled': True}, 'status_pies': {'enabled': False}, 'multiple_assignees': {'enabled': True}}, 'archived': False}]} Thought: I now know the folders in the team Final Answer: The folders in the team are listed in the
Get Authenticated
Get Authenticated ->: 'initials': 'RL'}]}] > Finished chain. -------------------------------------------------------------------------------- $ COMMAND Get all the folders for the team $ AGENT > Entering new AgentExecutor chain... I need to get all the folders for the team Action: Get all folders in the workspace Action Input: {"folder_id": "90130119692"} Observation: {'spaces': [{'id': '90110075934', 'name': 'Test Space', 'color': None, 'private': False, 'avatar': None, 'admin_can_manage': False, 'statuses': [{'id': 'p90110075934_lBKIEh3r', 'status': 'Open', 'type': 'open', 'orderindex': 0, 'color': '#d3d3d3'}, {'id': 'p90110075934_AvVAnVqy', 'status': 'in progress', 'type': 'custom', 'orderindex': 1, 'color': '#a875ff'}, {'id': 'p90110075934_SftYWzGt', 'status': 'Closed', 'type': 'closed', 'orderindex': 2, 'color': '#6bc950'}], 'multiple_assignees': True, 'features': {'due_dates': {'enabled': True, 'start_date': True, 'remap_due_dates': False, 'remap_closed_due_date': False}, 'sprints': {'enabled': False}, 'time_tracking': {'enabled': True, 'harvest': False, 'rollup': False}, 'points': {'enabled': False}, 'custom_items': {'enabled': False}, 'priorities': {'enabled': True, 'priorities': [{'color': '#f50000', 'id': '1', 'orderindex': '1', 'priority': 'urgent'}, {'color': '#ffcc00', 'id': '2', 'orderindex': '2', 'priority': 'high'}, {'color': '#6fddff', 'id': '3', 'orderindex': '3', 'priority': 'normal'}, {'color': '#d8d8d8', 'id': '4', 'orderindex': '4', 'priority': 'low'}]}, 'tags': {'enabled': True}, 'check_unresolved': {'enabled': True, 'subtasks': None, 'checklists': None, 'comments': None}, 'zoom': {'enabled': False}, 'milestones': {'enabled': False}, 'custom_fields': {'enabled': True}, 'dependency_warning': {'enabled': True}, 'status_pies': {'enabled': False}, 'multiple_assignees': {'enabled': True}}, 'archived': False}]} Thought: I now know the folders in the team Final Answer: The folders in the team are listed in the
2,749
Answer: The folders in the team are listed in the observation. > Finished chain. -------------------------------------------------------------------------------- 'The folders in the team are listed in the observation.'Task Operations‚ÄãYou can get, ask question about tasks and update themtask_id = '8685mb5fn'Basic attirbute getting and updating‚Äã# We can get a task to inspect it's contentsprint_and_run(f"Get task with id {task_id}")# We can get a specific attribute from a taskprevious_description = print_and_run(f"What is the description of task with id {task_id}")# We can even update it!print_and_run(f"For task with id {task_id}, change the description to 'A cool task descriptiont changed by AI!'")print_and_run(f"What is the description of task with id {task_id}")# Undo what we didprint_and_run(f"For task with id {task_id}, change the description to '{previous_description}'") $ COMMAND Get task with id 8685mb5fn $ AGENT > Entering new AgentExecutor chain... I need to use the Get task tool Action: Get task Action Input: {"task_id": "8685mb5fn"} Observation: {'id': '8685mb5fn', 'name': 'dummy task 1', 'text_content': 'An old, boring task description', 'description': 'An old, boring task description', 'status': 'to do', 'creator_id': 81928627, 'creator_username': 'Rodrigo Ceballos Lentini', 'creator_email': '[email protected]', 'assignees': [], 'watcher_username': 'Rodrigo Ceballos Lentini', 'watcher_email': '[email protected]', 'priority': 'high', 'due_date': '1694764800000', 'start_date': None, 'points': None, 'team_id': '9011010153', 'project_id': '90110331875'} Thought: I now know the task details Final Answer: The task with id 8685mb5fn has the following details: {'id': '8685mb5fn', 'name': 'dummy task 1', 'text_content': 'An old, boring task description', 'description': 'An old, boring task description', 'status': 'to do', 'creator_id': 81928627, 'creator_username': 'Rodrigo Ceballos Lentini',
Get Authenticated
Get Authenticated ->: Answer: The folders in the team are listed in the observation. > Finished chain. -------------------------------------------------------------------------------- 'The folders in the team are listed in the observation.'Task Operations‚ÄãYou can get, ask question about tasks and update themtask_id = '8685mb5fn'Basic attirbute getting and updating‚Äã# We can get a task to inspect it's contentsprint_and_run(f"Get task with id {task_id}")# We can get a specific attribute from a taskprevious_description = print_and_run(f"What is the description of task with id {task_id}")# We can even update it!print_and_run(f"For task with id {task_id}, change the description to 'A cool task descriptiont changed by AI!'")print_and_run(f"What is the description of task with id {task_id}")# Undo what we didprint_and_run(f"For task with id {task_id}, change the description to '{previous_description}'") $ COMMAND Get task with id 8685mb5fn $ AGENT > Entering new AgentExecutor chain... I need to use the Get task tool Action: Get task Action Input: {"task_id": "8685mb5fn"} Observation: {'id': '8685mb5fn', 'name': 'dummy task 1', 'text_content': 'An old, boring task description', 'description': 'An old, boring task description', 'status': 'to do', 'creator_id': 81928627, 'creator_username': 'Rodrigo Ceballos Lentini', 'creator_email': '[email protected]', 'assignees': [], 'watcher_username': 'Rodrigo Ceballos Lentini', 'watcher_email': '[email protected]', 'priority': 'high', 'due_date': '1694764800000', 'start_date': None, 'points': None, 'team_id': '9011010153', 'project_id': '90110331875'} Thought: I now know the task details Final Answer: The task with id 8685mb5fn has the following details: {'id': '8685mb5fn', 'name': 'dummy task 1', 'text_content': 'An old, boring task description', 'description': 'An old, boring task description', 'status': 'to do', 'creator_id': 81928627, 'creator_username': 'Rodrigo Ceballos Lentini',
2,750
'creator_username': 'Rodrigo Ceballos Lentini', 'creator_email': '[email protected]', 'assignees': [], 'watcher_username': 'Rodrigo Ceballos Lentini', 'watcher_email': '[email protected]', 'priority': 'high', 'due_date': '1694764800000', 'start_date': None, 'points': None, 'team_id': '9011010153', 'project_id': '90110331875'} > Finished chain. -------------------------------------------------------------------------------- $ COMMAND What is the description of task with id 8685mb5fn $ AGENT > Entering new AgentExecutor chain... I need to get the description of the task Action: Get task attribute Action Input: {"task_id": "8685mb5fn", "attribute_name": "description"} Observation: An old, boring task description Thought: I now know the description of the task Final Answer: An old, boring task description > Finished chain. -------------------------------------------------------------------------------- $ COMMAND For task with id 8685mb5fn, change the description to 'A cool task descriptiont changed by AI!' $ AGENT > Entering new AgentExecutor chain... I need to update the description of a task Action: Update task Action Input: {"task_id": "8685mb5fn", "attribute_name": "description", "value": "A cool task description changed by AI!"} Observation: <Response [200]> Thought: I have successfully updated the task description Final Answer: The description of task 8685mb5fn has been successfully changed to 'A cool task description changed by AI!' > Finished chain. -------------------------------------------------------------------------------- $ COMMAND What is the description of task with id 8685mb5fn $ AGENT > Entering new AgentExecutor chain... I need to get the description of the task Action: Get task attribute Action Input: {"task_id": "8685mb5fn", "attribute_name": "description"} Observation: A cool task
Get Authenticated
Get Authenticated ->: 'creator_username': 'Rodrigo Ceballos Lentini', 'creator_email': '[email protected]', 'assignees': [], 'watcher_username': 'Rodrigo Ceballos Lentini', 'watcher_email': '[email protected]', 'priority': 'high', 'due_date': '1694764800000', 'start_date': None, 'points': None, 'team_id': '9011010153', 'project_id': '90110331875'} > Finished chain. -------------------------------------------------------------------------------- $ COMMAND What is the description of task with id 8685mb5fn $ AGENT > Entering new AgentExecutor chain... I need to get the description of the task Action: Get task attribute Action Input: {"task_id": "8685mb5fn", "attribute_name": "description"} Observation: An old, boring task description Thought: I now know the description of the task Final Answer: An old, boring task description > Finished chain. -------------------------------------------------------------------------------- $ COMMAND For task with id 8685mb5fn, change the description to 'A cool task descriptiont changed by AI!' $ AGENT > Entering new AgentExecutor chain... I need to update the description of a task Action: Update task Action Input: {"task_id": "8685mb5fn", "attribute_name": "description", "value": "A cool task description changed by AI!"} Observation: <Response [200]> Thought: I have successfully updated the task description Final Answer: The description of task 8685mb5fn has been successfully changed to 'A cool task description changed by AI!' > Finished chain. -------------------------------------------------------------------------------- $ COMMAND What is the description of task with id 8685mb5fn $ AGENT > Entering new AgentExecutor chain... I need to get the description of the task Action: Get task attribute Action Input: {"task_id": "8685mb5fn", "attribute_name": "description"} Observation: A cool task
2,751
"description"} Observation: A cool task description changed by AI! Thought: I now know the description of the task Final Answer: A cool task description changed by AI! > Finished chain. -------------------------------------------------------------------------------- $ COMMAND For task with id 8685mb5fn, change the description to 'An old, boring task description' $ AGENT > Entering new AgentExecutor chain... I need to update the description of a task Action: Update task Action Input: {"task_id": "8685mb5fn", "attribute_name": "description", "value": "An old, boring task description"} Observation: <Response [200]> Thought: I now know the task description has been updated Final Answer: The description of task 8685mb5fn has been updated to 'An old, boring task description'. > Finished chain. -------------------------------------------------------------------------------- "The description of task 8685mb5fn has been updated to 'An old, boring task description'."print_and_run("Change the descrition task 8685mj6cd to 'Look ma no hands'") $ COMMAND Change the descrition task 8685mj6cd to 'Look ma no hands' $ AGENT > Entering new AgentExecutor chain... I need to update the description of a task Action: Update task Action Input: {"task_id": "8685mj6cd", "attribute_name": "description", "value": "Look ma no hands"} Observation: <Response [200]> Thought: The task description has been successfully updated Final Answer: The description of task 8685mj6cd has been changed to 'Look ma no hands'. > Finished chain. -------------------------------------------------------------------------------- "The description of task 8685mj6cd has been changed to 'Look ma no hands'."Advanced Attributes (Assignees)‚ÄãYou can query and update almost every thing about a task!user_id = 81928627print_and_run(f"What are the assignees of task id
Get Authenticated
Get Authenticated ->: "description"} Observation: A cool task description changed by AI! Thought: I now know the description of the task Final Answer: A cool task description changed by AI! > Finished chain. -------------------------------------------------------------------------------- $ COMMAND For task with id 8685mb5fn, change the description to 'An old, boring task description' $ AGENT > Entering new AgentExecutor chain... I need to update the description of a task Action: Update task Action Input: {"task_id": "8685mb5fn", "attribute_name": "description", "value": "An old, boring task description"} Observation: <Response [200]> Thought: I now know the task description has been updated Final Answer: The description of task 8685mb5fn has been updated to 'An old, boring task description'. > Finished chain. -------------------------------------------------------------------------------- "The description of task 8685mb5fn has been updated to 'An old, boring task description'."print_and_run("Change the descrition task 8685mj6cd to 'Look ma no hands'") $ COMMAND Change the descrition task 8685mj6cd to 'Look ma no hands' $ AGENT > Entering new AgentExecutor chain... I need to update the description of a task Action: Update task Action Input: {"task_id": "8685mj6cd", "attribute_name": "description", "value": "Look ma no hands"} Observation: <Response [200]> Thought: The task description has been successfully updated Final Answer: The description of task 8685mj6cd has been changed to 'Look ma no hands'. > Finished chain. -------------------------------------------------------------------------------- "The description of task 8685mj6cd has been changed to 'Look ma no hands'."Advanced Attributes (Assignees)‚ÄãYou can query and update almost every thing about a task!user_id = 81928627print_and_run(f"What are the assignees of task id
2,752
are the assignees of task id {task_id}?")print_and_run(f"Remove user {user_id} from the assignees of task id {task_id}")print_and_run(f"What are the assignees of task id {task_id}?")print_and_run(f"Add user {user_id} from the assignees of task id {task_id}") $ COMMAND What are the assignees of task id 8685mb5fn? $ AGENT > Entering new AgentExecutor chain... I need to get the assignees of a task Action: Get task attribute Action Input: {"task_id": "8685mb5fn", "attribute_name": "assignee"} Observation: Error: attribute_name = assignee was not found in task keys dict_keys(['id', 'name', 'text_content', 'description', 'status', 'creator_id', 'creator_username', 'creator_email', 'assignees', 'watcher_username', 'watcher_email', 'priority', 'due_date', 'start_date', 'points', 'team_id', 'project_id']). Please call again with one of the key names. Thought: I need to get the assignees of a task Action: Get task attribute Action Input: {"task_id": "8685mb5fn", "attribute_name": "assignees"} Observation: [] Thought: I now know the final answer Final Answer: There are no assignees for task id 8685mb5fn. > Finished chain. -------------------------------------------------------------------------------- $ COMMAND Remove user 81928627 from the assignees of task id 8685mb5fn $ AGENT > Entering new AgentExecutor chain... I need to update the assignees of a task Action: Update task assignees Action Input: {"task_id": "8685mb5fn", "operation": "rem", "users": [81928627]} Observation: <Response [200]> Thought: The user has been removed from the assignees of the task Final Answer: User 81928627 has been removed from the assignees of task id 8685mb5fn. > Finished chain. -------------------------------------------------------------------------------- $ COMMAND What are the assignees of task id 8685mb5fn? $ AGENT > Entering new AgentExecutor
Get Authenticated
Get Authenticated ->: are the assignees of task id {task_id}?")print_and_run(f"Remove user {user_id} from the assignees of task id {task_id}")print_and_run(f"What are the assignees of task id {task_id}?")print_and_run(f"Add user {user_id} from the assignees of task id {task_id}") $ COMMAND What are the assignees of task id 8685mb5fn? $ AGENT > Entering new AgentExecutor chain... I need to get the assignees of a task Action: Get task attribute Action Input: {"task_id": "8685mb5fn", "attribute_name": "assignee"} Observation: Error: attribute_name = assignee was not found in task keys dict_keys(['id', 'name', 'text_content', 'description', 'status', 'creator_id', 'creator_username', 'creator_email', 'assignees', 'watcher_username', 'watcher_email', 'priority', 'due_date', 'start_date', 'points', 'team_id', 'project_id']). Please call again with one of the key names. Thought: I need to get the assignees of a task Action: Get task attribute Action Input: {"task_id": "8685mb5fn", "attribute_name": "assignees"} Observation: [] Thought: I now know the final answer Final Answer: There are no assignees for task id 8685mb5fn. > Finished chain. -------------------------------------------------------------------------------- $ COMMAND Remove user 81928627 from the assignees of task id 8685mb5fn $ AGENT > Entering new AgentExecutor chain... I need to update the assignees of a task Action: Update task assignees Action Input: {"task_id": "8685mb5fn", "operation": "rem", "users": [81928627]} Observation: <Response [200]> Thought: The user has been removed from the assignees of the task Final Answer: User 81928627 has been removed from the assignees of task id 8685mb5fn. > Finished chain. -------------------------------------------------------------------------------- $ COMMAND What are the assignees of task id 8685mb5fn? $ AGENT > Entering new AgentExecutor
2,753
$ AGENT > Entering new AgentExecutor chain... I need to get the assignees of a task Action: Get task attribute Action Input: {"task_id": "8685mb5fn", "attribute_name": "assignee"} Observation: Error: attribute_name = assignee was not found in task keys dict_keys(['id', 'name', 'text_content', 'description', 'status', 'creator_id', 'creator_username', 'creator_email', 'assignees', 'watcher_username', 'watcher_email', 'priority', 'due_date', 'start_date', 'points', 'team_id', 'project_id']). Please call again with one of the key names. Thought: I need to get the assignees of a task Action: Get task attribute Action Input: {"task_id": "8685mb5fn", "attribute_name": "assignees"} Observation: [] Thought: I now know the final answer Final Answer: There are no assignees for task id 8685mb5fn. > Finished chain. -------------------------------------------------------------------------------- $ COMMAND Add user 81928627 from the assignees of task id 8685mb5fn $ AGENT > Entering new AgentExecutor chain... I need to update the assignees of a task Action: Update task assignees Action Input: {"task_id": "8685mb5fn", "operation": "rem", "users": [81928627]} Observation: <Response [200]> Thought: The user has been removed from the assignees of the task Final Answer: User 81928627 has been removed from the assignees of task id 8685mb5fn. > Finished chain. -------------------------------------------------------------------------------- 'User 81928627 has been removed from the assignees of task id 8685mb5fn.'Creation‚ÄãYou can create tasks, lists and folderstime_str = datetime.now().strftime("%d/%m/%Y-%H:%M:%S")print_and_run(f"Create a task called 'Test Task - {time_str}' with description 'This is a Test'") $ COMMAND Create a task called 'Test Task - 18/09/2023-10:31:22' with description 'This is a Test' $ AGENT > Entering new AgentExecutor chain...
Get Authenticated
Get Authenticated ->: $ AGENT > Entering new AgentExecutor chain... I need to get the assignees of a task Action: Get task attribute Action Input: {"task_id": "8685mb5fn", "attribute_name": "assignee"} Observation: Error: attribute_name = assignee was not found in task keys dict_keys(['id', 'name', 'text_content', 'description', 'status', 'creator_id', 'creator_username', 'creator_email', 'assignees', 'watcher_username', 'watcher_email', 'priority', 'due_date', 'start_date', 'points', 'team_id', 'project_id']). Please call again with one of the key names. Thought: I need to get the assignees of a task Action: Get task attribute Action Input: {"task_id": "8685mb5fn", "attribute_name": "assignees"} Observation: [] Thought: I now know the final answer Final Answer: There are no assignees for task id 8685mb5fn. > Finished chain. -------------------------------------------------------------------------------- $ COMMAND Add user 81928627 from the assignees of task id 8685mb5fn $ AGENT > Entering new AgentExecutor chain... I need to update the assignees of a task Action: Update task assignees Action Input: {"task_id": "8685mb5fn", "operation": "rem", "users": [81928627]} Observation: <Response [200]> Thought: The user has been removed from the assignees of the task Final Answer: User 81928627 has been removed from the assignees of task id 8685mb5fn. > Finished chain. -------------------------------------------------------------------------------- 'User 81928627 has been removed from the assignees of task id 8685mb5fn.'Creation‚ÄãYou can create tasks, lists and folderstime_str = datetime.now().strftime("%d/%m/%Y-%H:%M:%S")print_and_run(f"Create a task called 'Test Task - {time_str}' with description 'This is a Test'") $ COMMAND Create a task called 'Test Task - 18/09/2023-10:31:22' with description 'This is a Test' $ AGENT > Entering new AgentExecutor chain...
2,754
> Entering new AgentExecutor chain... I need to use the Create Task tool Action: Create Task Action Input: {"name": "Test Task - 18/09/2023-10:31:22", "description": "This is a Test"} Observation: {'id': '8685mw4wq', 'custom_id': None, 'name': 'Test Task - 18/09/2023-10:31:22', 'text_content': 'This is a Test', 'description': 'This is a Test', 'status': {'id': 'p90110061901_VlN8IJtk', 'status': 'to do', 'color': '#87909e', 'orderindex': 0, 'type': 'open'}, 'orderindex': '23.00000000000000000000000000000000', 'date_created': '1695047486396', 'date_updated': '1695047486396', 'date_closed': None, 'date_done': None, 'archived': False, 'creator': {'id': 81928627, 'username': 'Rodrigo Ceballos Lentini', 'color': '#c51162', 'email': '[email protected]', 'profilePicture': None}, 'assignees': [], 'watchers': [{'id': 81928627, 'username': 'Rodrigo Ceballos Lentini', 'color': '#c51162', 'initials': 'RL', 'email': '[email protected]', 'profilePicture': None}], 'checklists': [], 'tags': [], 'parent': None, 'priority': None, 'due_date': None, 'start_date': None, 'points': None, 'time_estimate': None, 'time_spent': 0, 'custom_fields': [], 'dependencies': [], 'linked_tasks': [], 'team_id': '9011010153', 'url': 'https://app.clickup.com/t/8685mw4wq', 'sharing': {'public': False, 'public_share_expires_on': None, 'public_fields': ['assignees', 'priority', 'due_date', 'content', 'comments', 'attachments', 'customFields', 'subtasks', 'tags', 'checklists', 'coverimage'], 'token': None, 'seo_optimized': False}, 'permission_level': 'create', 'list': {'id': '901100754275', 'name': 'Test List', 'access': True}, 'project': {'id': '90110336890', 'name': 'Test Folder', 'hidden': False, 'access': True}, 'folder': {'id': '90110336890', 'name': 'Test Folder', 'hidden': False, 'access': True}, 'space': {'id': '90110061901'}} Thought: I now know the final answer Final Answer: A task called 'Test Task - 18/09/2023-10:31:22' with description 'This is a Test' was
Get Authenticated
Get Authenticated ->: > Entering new AgentExecutor chain... I need to use the Create Task tool Action: Create Task Action Input: {"name": "Test Task - 18/09/2023-10:31:22", "description": "This is a Test"} Observation: {'id': '8685mw4wq', 'custom_id': None, 'name': 'Test Task - 18/09/2023-10:31:22', 'text_content': 'This is a Test', 'description': 'This is a Test', 'status': {'id': 'p90110061901_VlN8IJtk', 'status': 'to do', 'color': '#87909e', 'orderindex': 0, 'type': 'open'}, 'orderindex': '23.00000000000000000000000000000000', 'date_created': '1695047486396', 'date_updated': '1695047486396', 'date_closed': None, 'date_done': None, 'archived': False, 'creator': {'id': 81928627, 'username': 'Rodrigo Ceballos Lentini', 'color': '#c51162', 'email': '[email protected]', 'profilePicture': None}, 'assignees': [], 'watchers': [{'id': 81928627, 'username': 'Rodrigo Ceballos Lentini', 'color': '#c51162', 'initials': 'RL', 'email': '[email protected]', 'profilePicture': None}], 'checklists': [], 'tags': [], 'parent': None, 'priority': None, 'due_date': None, 'start_date': None, 'points': None, 'time_estimate': None, 'time_spent': 0, 'custom_fields': [], 'dependencies': [], 'linked_tasks': [], 'team_id': '9011010153', 'url': 'https://app.clickup.com/t/8685mw4wq', 'sharing': {'public': False, 'public_share_expires_on': None, 'public_fields': ['assignees', 'priority', 'due_date', 'content', 'comments', 'attachments', 'customFields', 'subtasks', 'tags', 'checklists', 'coverimage'], 'token': None, 'seo_optimized': False}, 'permission_level': 'create', 'list': {'id': '901100754275', 'name': 'Test List', 'access': True}, 'project': {'id': '90110336890', 'name': 'Test Folder', 'hidden': False, 'access': True}, 'folder': {'id': '90110336890', 'name': 'Test Folder', 'hidden': False, 'access': True}, 'space': {'id': '90110061901'}} Thought: I now know the final answer Final Answer: A task called 'Test Task - 18/09/2023-10:31:22' with description 'This is a Test' was
2,755
with description 'This is a Test' was successfully created. > Finished chain. -------------------------------------------------------------------------------- "A task called 'Test Task - 18/09/2023-10:31:22' with description 'This is a Test' was successfully created."time_str = datetime.now().strftime("%d/%m/%Y-%H:%M:%S")print_and_run(f"Create a list called Test List - {time_str}") $ COMMAND Create a list called Test List - 18/09/2023-10:32:12 $ AGENT > Entering new AgentExecutor chain... I need to create a list Action: Create List Action Input: {"name": "Test List - 18/09/2023-10:32:12"} Observation: {'id': '901100774700', 'name': 'Test List - 18/09/2023-10:32:12', 'deleted': False, 'orderindex': 13, 'content': '', 'priority': None, 'assignee': None, 'due_date': None, 'start_date': None, 'folder': {'id': '90110336890', 'name': 'Test Folder', 'hidden': False, 'access': True}, 'space': {'id': '90110061901', 'name': 'Space', 'access': True}, 'inbound_address': 'a.t.901100774700.u-81928627.20b87d50-eece-4721-b487-9ca500338587@tasks.clickup.com', 'archived': False, 'override_statuses': False, 'statuses': [{'id': 'p90110061901_VlN8IJtk', 'status': 'to do', 'orderindex': 0, 'color': '#87909e', 'type': 'open'}, {'id': 'p90110061901_14GpYKnM', 'status': 'complete', 'orderindex': 1, 'color': '#6bc950', 'type': 'closed'}], 'permission_level': 'create'} Thought: I now know the final answer Final Answer: The list "Test List - 18/09/2023-10:32:12" has been created with id 901100774700. > Finished chain. -------------------------------------------------------------------------------- 'The list "Test List - 18/09/2023-10:32:12" has been created with id 901100774700.'time_str = datetime.now().strftime("%d/%m/%Y-%H:%M:%S")print_and_run(f"Create a folder called 'Test Folder - {time_str}'") $ COMMAND Create a folder called 'Test Folder - 18/09/2023-10:32:51' $ AGENT > Entering new
Get Authenticated
Get Authenticated ->: with description 'This is a Test' was successfully created. > Finished chain. -------------------------------------------------------------------------------- "A task called 'Test Task - 18/09/2023-10:31:22' with description 'This is a Test' was successfully created."time_str = datetime.now().strftime("%d/%m/%Y-%H:%M:%S")print_and_run(f"Create a list called Test List - {time_str}") $ COMMAND Create a list called Test List - 18/09/2023-10:32:12 $ AGENT > Entering new AgentExecutor chain... I need to create a list Action: Create List Action Input: {"name": "Test List - 18/09/2023-10:32:12"} Observation: {'id': '901100774700', 'name': 'Test List - 18/09/2023-10:32:12', 'deleted': False, 'orderindex': 13, 'content': '', 'priority': None, 'assignee': None, 'due_date': None, 'start_date': None, 'folder': {'id': '90110336890', 'name': 'Test Folder', 'hidden': False, 'access': True}, 'space': {'id': '90110061901', 'name': 'Space', 'access': True}, 'inbound_address': 'a.t.901100774700.u-81928627.20b87d50-eece-4721-b487-9ca500338587@tasks.clickup.com', 'archived': False, 'override_statuses': False, 'statuses': [{'id': 'p90110061901_VlN8IJtk', 'status': 'to do', 'orderindex': 0, 'color': '#87909e', 'type': 'open'}, {'id': 'p90110061901_14GpYKnM', 'status': 'complete', 'orderindex': 1, 'color': '#6bc950', 'type': 'closed'}], 'permission_level': 'create'} Thought: I now know the final answer Final Answer: The list "Test List - 18/09/2023-10:32:12" has been created with id 901100774700. > Finished chain. -------------------------------------------------------------------------------- 'The list "Test List - 18/09/2023-10:32:12" has been created with id 901100774700.'time_str = datetime.now().strftime("%d/%m/%Y-%H:%M:%S")print_and_run(f"Create a folder called 'Test Folder - {time_str}'") $ COMMAND Create a folder called 'Test Folder - 18/09/2023-10:32:51' $ AGENT > Entering new
2,756
$ AGENT > Entering new AgentExecutor chain... I need to use the Create Folder tool Action: Create Folder Action Input: {"name": "Test Folder - 18/09/2023-10:32:51"} Observation: {'id': '90110348711', 'name': 'Test Folder - 18/09/2023-10:32:51', 'orderindex': 12, 'override_statuses': False, 'hidden': False, 'space': {'id': '90110061901', 'name': 'Space', 'access': True}, 'task_count': '0', 'archived': False, 'statuses': [], 'lists': [], 'permission_level': 'create'} Thought: I have successfully created the folder Final Answer: The folder 'Test Folder - 18/09/2023-10:32:51' has been successfully created. > Finished chain. -------------------------------------------------------------------------------- "The folder 'Test Folder - 18/09/2023-10:32:51' has been successfully created."time_str = datetime.now().strftime("%d/%m/%Y-%H:%M:%S")print_and_run(f"Create a list called 'Test List - {time_str}' with content My test list with high priority and status red") $ COMMAND Create a list called 'Test List - 18/09/2023-10:34:01' with content My test list with high priority and status red $ AGENT > Entering new AgentExecutor chain... I need to create a list with the given name, content, priority and status Action: Create List Action Input: {"name": "Test List - 18/09/2023-10:34:01", "content": "My test list", "priority": 2, "status": "red"} Observation: {'id': '901100774746', 'name': 'Test List - 18/09/2023-10:34:01', 'deleted': False, 'orderindex': 15, 'content': '', 'status': {'status': 'red', 'color': '#e50000', 'hide_label': True}, 'priority': {'priority': 'high', 'color': '#ffcc00'}, 'assignee': None, 'due_date': None, 'start_date': None, 'folder': {'id': '90110336890', 'name': 'Test Folder', 'hidden': False, 'access': True}, 'space': {'id': '90110061901', 'name': 'Space', 'access': True}, 'inbound_address':
Get Authenticated
Get Authenticated ->: $ AGENT > Entering new AgentExecutor chain... I need to use the Create Folder tool Action: Create Folder Action Input: {"name": "Test Folder - 18/09/2023-10:32:51"} Observation: {'id': '90110348711', 'name': 'Test Folder - 18/09/2023-10:32:51', 'orderindex': 12, 'override_statuses': False, 'hidden': False, 'space': {'id': '90110061901', 'name': 'Space', 'access': True}, 'task_count': '0', 'archived': False, 'statuses': [], 'lists': [], 'permission_level': 'create'} Thought: I have successfully created the folder Final Answer: The folder 'Test Folder - 18/09/2023-10:32:51' has been successfully created. > Finished chain. -------------------------------------------------------------------------------- "The folder 'Test Folder - 18/09/2023-10:32:51' has been successfully created."time_str = datetime.now().strftime("%d/%m/%Y-%H:%M:%S")print_and_run(f"Create a list called 'Test List - {time_str}' with content My test list with high priority and status red") $ COMMAND Create a list called 'Test List - 18/09/2023-10:34:01' with content My test list with high priority and status red $ AGENT > Entering new AgentExecutor chain... I need to create a list with the given name, content, priority and status Action: Create List Action Input: {"name": "Test List - 18/09/2023-10:34:01", "content": "My test list", "priority": 2, "status": "red"} Observation: {'id': '901100774746', 'name': 'Test List - 18/09/2023-10:34:01', 'deleted': False, 'orderindex': 15, 'content': '', 'status': {'status': 'red', 'color': '#e50000', 'hide_label': True}, 'priority': {'priority': 'high', 'color': '#ffcc00'}, 'assignee': None, 'due_date': None, 'start_date': None, 'folder': {'id': '90110336890', 'name': 'Test Folder', 'hidden': False, 'access': True}, 'space': {'id': '90110061901', 'name': 'Space', 'access': True}, 'inbound_address':
2,757
'Space', 'access': True}, 'inbound_address': 'a.t.901100774746.u-81928627.2ab87133-728e-4166-b2ae-423cc320df37@tasks.clickup.com', 'archived': False, 'override_statuses': False, 'statuses': [{'id': 'p90110061901_VlN8IJtk', 'status': 'to do', 'orderindex': 0, 'color': '#87909e', 'type': 'open'}, {'id': 'p90110061901_14GpYKnM', 'status': 'complete', 'orderindex': 1, 'color': '#6bc950', 'type': 'closed'}], 'permission_level': 'create'} Thought: I have successfully created the list Final Answer: The list 'Test List - 18/09/2023-10:34:01' with content 'My test list' with high priority and status red has been successfully created. > Finished chain. -------------------------------------------------------------------------------- "The list 'Test List - 18/09/2023-10:34:01' with content 'My test list' with high priority and status red has been successfully created."Multi-Step Tasksprint_and_run("Figure out what user ID Rodrigo is, create a task called 'Rod's task', assign it to Rodrigo") $ COMMAND Figure out what user ID Rodrigo is, create a task called 'Rod's task', assign it to Rodrigo $ AGENT > Entering new AgentExecutor chain... I need to get the user ID of Rodrigo, create a task, and assign it to Rodrigo Action: Get Teams Action Input: No input necessary Observation: {'teams': [{'id': '9011010153', 'name': 'Task Copilot Sandbox Workspace 1', 'members': [{'id': 81928627, 'username': 'Rodrigo Ceballos Lentini', 'email': '[email protected]', 'initials': 'RL'}]}]} Thought: I now have the user ID of Rodrigo Action: Create Task Action Input: {"name": "Rod's task", "assignees": [81928627]} /Users/rodrigolentini/repos/langchain-clickup/libs/langchain/langchain/utilities/clickup.py:145: UserWarning: Error encountered while trying to parse <class 'langchain.utilities.clickup.Task'>: 'NoneType' object is not subscriptable Falling back to returning input data. warnings.warn(f'Error encountered while
Get Authenticated
Get Authenticated ->: 'Space', 'access': True}, 'inbound_address': 'a.t.901100774746.u-81928627.2ab87133-728e-4166-b2ae-423cc320df37@tasks.clickup.com', 'archived': False, 'override_statuses': False, 'statuses': [{'id': 'p90110061901_VlN8IJtk', 'status': 'to do', 'orderindex': 0, 'color': '#87909e', 'type': 'open'}, {'id': 'p90110061901_14GpYKnM', 'status': 'complete', 'orderindex': 1, 'color': '#6bc950', 'type': 'closed'}], 'permission_level': 'create'} Thought: I have successfully created the list Final Answer: The list 'Test List - 18/09/2023-10:34:01' with content 'My test list' with high priority and status red has been successfully created. > Finished chain. -------------------------------------------------------------------------------- "The list 'Test List - 18/09/2023-10:34:01' with content 'My test list' with high priority and status red has been successfully created."Multi-Step Tasksprint_and_run("Figure out what user ID Rodrigo is, create a task called 'Rod's task', assign it to Rodrigo") $ COMMAND Figure out what user ID Rodrigo is, create a task called 'Rod's task', assign it to Rodrigo $ AGENT > Entering new AgentExecutor chain... I need to get the user ID of Rodrigo, create a task, and assign it to Rodrigo Action: Get Teams Action Input: No input necessary Observation: {'teams': [{'id': '9011010153', 'name': 'Task Copilot Sandbox Workspace 1', 'members': [{'id': 81928627, 'username': 'Rodrigo Ceballos Lentini', 'email': '[email protected]', 'initials': 'RL'}]}]} Thought: I now have the user ID of Rodrigo Action: Create Task Action Input: {"name": "Rod's task", "assignees": [81928627]} /Users/rodrigolentini/repos/langchain-clickup/libs/langchain/langchain/utilities/clickup.py:145: UserWarning: Error encountered while trying to parse <class 'langchain.utilities.clickup.Task'>: 'NoneType' object is not subscriptable Falling back to returning input data. warnings.warn(f'Error encountered while
2,758
warnings.warn(f'Error encountered while trying to parse {dataclass}: {e}\n Falling back to returning input data.') Observation: {'id': '8685mw6dz', 'custom_id': None, 'name': "Rod's task", 'text_content': '', 'description': '', 'status': {'id': 'p90110061901_VlN8IJtk', 'status': 'to do', 'color': '#87909e', 'orderindex': 0, 'type': 'open'}, 'orderindex': '24.00000000000000000000000000000000', 'date_created': '1695047740939', 'date_updated': '1695047740939', 'date_closed': None, 'date_done': None, 'archived': False, 'creator': {'id': 81928627, 'username': 'Rodrigo Ceballos Lentini', 'color': '#c51162', 'email': '[email protected]', 'profilePicture': None}, 'assignees': [{'id': 81928627, 'username': 'Rodrigo Ceballos Lentini', 'color': '#c51162', 'initials': 'RL', 'email': '[email protected]', 'profilePicture': None}], 'watchers': [{'id': 81928627, 'username': 'Rodrigo Ceballos Lentini', 'color': '#c51162', 'initials': 'RL', 'email': '[email protected]', 'profilePicture': None}], 'checklists': [], 'tags': [], 'parent': None, 'priority': None, 'due_date': None, 'start_date': None, 'points': None, 'time_estimate': None, 'time_spent': 0, 'custom_fields': [], 'dependencies': [], 'linked_tasks': [], 'team_id': '9011010153', 'url': 'https://app.clickup.com/t/8685mw6dz', 'sharing': {'public': False, 'public_share_expires_on': None, 'public_fields': ['assignees', 'priority', 'due_date', 'content', 'comments', 'attachments', 'customFields', 'subtasks', 'tags', 'checklists', 'coverimage'], 'token': None, 'seo_optimized': False}, 'permission_level': 'create', 'list': {'id': '901100754275', 'name': 'Test List', 'access': True}, 'project': {'id': '90110336890', 'name': 'Test Folder', 'hidden': False, 'access': True}, 'folder': {'id': '90110336890', 'name': 'Test Folder', 'hidden': False, 'access': True}, 'space': {'id': '90110061901'}} Thought: I now have the task created and assigned to Rodrigo Final Answer: Rodrigo's user ID is 81928627 and a task
Get Authenticated
Get Authenticated ->: warnings.warn(f'Error encountered while trying to parse {dataclass}: {e}\n Falling back to returning input data.') Observation: {'id': '8685mw6dz', 'custom_id': None, 'name': "Rod's task", 'text_content': '', 'description': '', 'status': {'id': 'p90110061901_VlN8IJtk', 'status': 'to do', 'color': '#87909e', 'orderindex': 0, 'type': 'open'}, 'orderindex': '24.00000000000000000000000000000000', 'date_created': '1695047740939', 'date_updated': '1695047740939', 'date_closed': None, 'date_done': None, 'archived': False, 'creator': {'id': 81928627, 'username': 'Rodrigo Ceballos Lentini', 'color': '#c51162', 'email': '[email protected]', 'profilePicture': None}, 'assignees': [{'id': 81928627, 'username': 'Rodrigo Ceballos Lentini', 'color': '#c51162', 'initials': 'RL', 'email': '[email protected]', 'profilePicture': None}], 'watchers': [{'id': 81928627, 'username': 'Rodrigo Ceballos Lentini', 'color': '#c51162', 'initials': 'RL', 'email': '[email protected]', 'profilePicture': None}], 'checklists': [], 'tags': [], 'parent': None, 'priority': None, 'due_date': None, 'start_date': None, 'points': None, 'time_estimate': None, 'time_spent': 0, 'custom_fields': [], 'dependencies': [], 'linked_tasks': [], 'team_id': '9011010153', 'url': 'https://app.clickup.com/t/8685mw6dz', 'sharing': {'public': False, 'public_share_expires_on': None, 'public_fields': ['assignees', 'priority', 'due_date', 'content', 'comments', 'attachments', 'customFields', 'subtasks', 'tags', 'checklists', 'coverimage'], 'token': None, 'seo_optimized': False}, 'permission_level': 'create', 'list': {'id': '901100754275', 'name': 'Test List', 'access': True}, 'project': {'id': '90110336890', 'name': 'Test Folder', 'hidden': False, 'access': True}, 'folder': {'id': '90110336890', 'name': 'Test Folder', 'hidden': False, 'access': True}, 'space': {'id': '90110061901'}} Thought: I now have the task created and assigned to Rodrigo Final Answer: Rodrigo's user ID is 81928627 and a task
2,759
Answer: Rodrigo's user ID is 81928627 and a task called 'Rod's task' has been created and assigned to him. > Finished chain. -------------------------------------------------------------------------------- "Rodrigo's user ID is 81928627 and a task called 'Rod's task' has been created and assigned to him."PreviousAzure Cognitive ServicesNextCSVGet AuthenticatedGet Access TokenCreate ToolkitCreate AgentNavigationTask OperationsCreationCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
Get Authenticated
Get Authenticated ->: Answer: Rodrigo's user ID is 81928627 and a task called 'Rod's task' has been created and assigned to him. > Finished chain. -------------------------------------------------------------------------------- "Rodrigo's user ID is 81928627 and a task called 'Rod's task' has been created and assigned to him."PreviousAzure Cognitive ServicesNextCSVGet AuthenticatedGet Access TokenCreate ToolkitCreate AgentNavigationTask OperationsCreationCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
2,760
OpenAPI | 🦜️🔗 Langchain
We can construct agents to consume arbitrary APIs, here APIs conformant to the OpenAPI/Swagger specification.
We can construct agents to consume arbitrary APIs, here APIs conformant to the OpenAPI/Swagger specification. ->: OpenAPI | 🦜️🔗 Langchain
2,761
Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKProvidersAnthropicAWSGoogleMicrosoftOpenAIMoreComponentsLLMsChat modelsDocument loadersDocument transformersText embedding modelsVector storesRetrieversToolsAgents and toolkitsAINetworkAirbyte Question AnsweringAmadeusAzure Cognitive ServicesClickUp Langchain ToolkitCSVDocument ComparisonGithubGitlabGmailGoogle Drive toolJiraJSONMultiOnOffice365OpenAPINatural Language APIsPandas DataframePlayWright BrowserPowerBI DatasetPythonSpark DataframeSpark SQLSQL DatabaseVectorstoreXorbitsMemoryCallbacksChat loadersComponentsAgents and toolkitsOpenAPIOn this pageOpenAPIWe can construct agents to consume arbitrary APIs, here APIs conformant to the OpenAPI/Swagger specification.1st example: hierarchical planning agent​In this example, we'll consider an approach called hierarchical planning, common in robotics and appearing in recent works for LLMs X robotics. We'll see it's a viable approach to start working with a massive API spec AND to assist with user queries that require multiple steps against the API.The idea is simple: to get coherent agent behavior over long sequences behavior & to save on tokens, we'll separate concerns: a "planner" will be responsible for what endpoints to call and a "controller" will be responsible for how to call them.In the initial implementation, the planner is an LLM chain that has the name and a short description for each endpoint in context. The controller is an LLM agent that is instantiated with documentation for only the endpoints for a particular plan. There's a lot left to get this working very robustly :)To start, let's collect some OpenAPI specs.​import os, yamlwget https://raw.githubusercontent.com/openai/openai-openapi/master/openapi.yamlmv openapi.yaml openai_openapi.yamlwget https://www.klarna.com/us/shopping/public/openai/v0/api-docsmv api-docs klarna_openapi.yamlwget
We can construct agents to consume arbitrary APIs, here APIs conformant to the OpenAPI/Swagger specification.
We can construct agents to consume arbitrary APIs, here APIs conformant to the OpenAPI/Swagger specification. ->: Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKProvidersAnthropicAWSGoogleMicrosoftOpenAIMoreComponentsLLMsChat modelsDocument loadersDocument transformersText embedding modelsVector storesRetrieversToolsAgents and toolkitsAINetworkAirbyte Question AnsweringAmadeusAzure Cognitive ServicesClickUp Langchain ToolkitCSVDocument ComparisonGithubGitlabGmailGoogle Drive toolJiraJSONMultiOnOffice365OpenAPINatural Language APIsPandas DataframePlayWright BrowserPowerBI DatasetPythonSpark DataframeSpark SQLSQL DatabaseVectorstoreXorbitsMemoryCallbacksChat loadersComponentsAgents and toolkitsOpenAPIOn this pageOpenAPIWe can construct agents to consume arbitrary APIs, here APIs conformant to the OpenAPI/Swagger specification.1st example: hierarchical planning agent​In this example, we'll consider an approach called hierarchical planning, common in robotics and appearing in recent works for LLMs X robotics. We'll see it's a viable approach to start working with a massive API spec AND to assist with user queries that require multiple steps against the API.The idea is simple: to get coherent agent behavior over long sequences behavior & to save on tokens, we'll separate concerns: a "planner" will be responsible for what endpoints to call and a "controller" will be responsible for how to call them.In the initial implementation, the planner is an LLM chain that has the name and a short description for each endpoint in context. The controller is an LLM agent that is instantiated with documentation for only the endpoints for a particular plan. There's a lot left to get this working very robustly :)To start, let's collect some OpenAPI specs.​import os, yamlwget https://raw.githubusercontent.com/openai/openai-openapi/master/openapi.yamlmv openapi.yaml openai_openapi.yamlwget https://www.klarna.com/us/shopping/public/openai/v0/api-docsmv api-docs klarna_openapi.yamlwget
2,762
api-docs klarna_openapi.yamlwget https://raw.githubusercontent.com/APIs-guru/openapi-directory/main/APIs/spotify.com/1.0.0/openapi.yamlmv openapi.yaml spotify_openapi.yaml --2023-03-31 15:45:56-- https://raw.githubusercontent.com/openai/openai-openapi/master/openapi.yaml Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.110.133, 185.199.109.133, 185.199.111.133, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.110.133|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 122995 (120K) [text/plain] Saving to: ‘openapi.yaml’ openapi.yaml 100%[===================>] 120.11K --.-KB/s in 0.01s 2023-03-31 15:45:56 (10.4 MB/s) - ‘openapi.yaml’ saved [122995/122995] --2023-03-31 15:45:57-- https://www.klarna.com/us/shopping/public/openai/v0/api-docs Resolving www.klarna.com (www.klarna.com)... 52.84.150.34, 52.84.150.46, 52.84.150.61, ... Connecting to www.klarna.com (www.klarna.com)|52.84.150.34|:443... connected. HTTP request sent, awaiting response... 200 OK Length: unspecified [application/json] Saving to: ‘api-docs’ api-docs [ <=> ] 1.87K --.-KB/s in 0s 2023-03-31 15:45:57 (261 MB/s) - ‘api-docs’ saved [1916] --2023-03-31 15:45:57-- https://raw.githubusercontent.com/APIs-guru/openapi-directory/main/APIs/spotify.com/1.0.0/openapi.yaml Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.110.133, 185.199.109.133, 185.199.111.133, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.110.133|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 286747 (280K) [text/plain] Saving to: ‘openapi.yaml’ openapi.yaml 100%[===================>] 280.03K --.-KB/s in 0.02s 2023-03-31 15:45:58 (13.3 MB/s) - ‘openapi.yaml’ saved [286747/286747]
We can construct agents to consume arbitrary APIs, here APIs conformant to the OpenAPI/Swagger specification.
We can construct agents to consume arbitrary APIs, here APIs conformant to the OpenAPI/Swagger specification. ->: api-docs klarna_openapi.yamlwget https://raw.githubusercontent.com/APIs-guru/openapi-directory/main/APIs/spotify.com/1.0.0/openapi.yamlmv openapi.yaml spotify_openapi.yaml --2023-03-31 15:45:56-- https://raw.githubusercontent.com/openai/openai-openapi/master/openapi.yaml Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.110.133, 185.199.109.133, 185.199.111.133, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.110.133|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 122995 (120K) [text/plain] Saving to: ‘openapi.yaml’ openapi.yaml 100%[===================>] 120.11K --.-KB/s in 0.01s 2023-03-31 15:45:56 (10.4 MB/s) - ‘openapi.yaml’ saved [122995/122995] --2023-03-31 15:45:57-- https://www.klarna.com/us/shopping/public/openai/v0/api-docs Resolving www.klarna.com (www.klarna.com)... 52.84.150.34, 52.84.150.46, 52.84.150.61, ... Connecting to www.klarna.com (www.klarna.com)|52.84.150.34|:443... connected. HTTP request sent, awaiting response... 200 OK Length: unspecified [application/json] Saving to: ‘api-docs’ api-docs [ <=> ] 1.87K --.-KB/s in 0s 2023-03-31 15:45:57 (261 MB/s) - ‘api-docs’ saved [1916] --2023-03-31 15:45:57-- https://raw.githubusercontent.com/APIs-guru/openapi-directory/main/APIs/spotify.com/1.0.0/openapi.yaml Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.110.133, 185.199.109.133, 185.199.111.133, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.110.133|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 286747 (280K) [text/plain] Saving to: ‘openapi.yaml’ openapi.yaml 100%[===================>] 280.03K --.-KB/s in 0.02s 2023-03-31 15:45:58 (13.3 MB/s) - ‘openapi.yaml’ saved [286747/286747]
2,763
- ‘openapi.yaml’ saved [286747/286747] from langchain.agents.agent_toolkits.openapi.spec import reduce_openapi_specwith open("openai_openapi.yaml") as f: raw_openai_api_spec = yaml.load(f, Loader=yaml.Loader)openai_api_spec = reduce_openapi_spec(raw_openai_api_spec)with open("klarna_openapi.yaml") as f: raw_klarna_api_spec = yaml.load(f, Loader=yaml.Loader)klarna_api_spec = reduce_openapi_spec(raw_klarna_api_spec)with open("spotify_openapi.yaml") as f: raw_spotify_api_spec = yaml.load(f, Loader=yaml.Loader)spotify_api_spec = reduce_openapi_spec(raw_spotify_api_spec)We'll work with the Spotify API as one of the examples of a somewhat complex API. There's a bit of auth-related setup to do if you want to replicate this.You'll have to set up an application in the Spotify developer console, documented here, to get credentials: CLIENT_ID, CLIENT_SECRET, and REDIRECT_URI.To get an access tokens (and keep them fresh), you can implement the oauth flows, or you can use spotipy. If you've set your Spotify creedentials as environment variables SPOTIPY_CLIENT_ID, SPOTIPY_CLIENT_SECRET, and SPOTIPY_REDIRECT_URI, you can use the helper functions below:import spotipy.util as utilfrom langchain.requests import RequestsWrapperdef construct_spotify_auth_headers(raw_spec: dict): scopes = list( raw_spec["components"]["securitySchemes"]["oauth_2_0"]["flows"][ "authorizationCode" ]["scopes"].keys() ) access_token = util.prompt_for_user_token(scope=",".join(scopes)) return {"Authorization": f"Bearer {access_token}"}# Get API credentials.headers = construct_spotify_auth_headers(raw_spotify_api_spec)requests_wrapper = RequestsWrapper(headers=headers)How big is this spec?​endpoints = [ (route, operation) for route, operations in raw_spotify_api_spec["paths"].items() for operation in operations if operation in ["get", "post"]]len(endpoints) 63import tiktokenenc = tiktoken.encoding_for_model("text-davinci-003")def
We can construct agents to consume arbitrary APIs, here APIs conformant to the OpenAPI/Swagger specification.
We can construct agents to consume arbitrary APIs, here APIs conformant to the OpenAPI/Swagger specification. ->: - ‘openapi.yaml’ saved [286747/286747] from langchain.agents.agent_toolkits.openapi.spec import reduce_openapi_specwith open("openai_openapi.yaml") as f: raw_openai_api_spec = yaml.load(f, Loader=yaml.Loader)openai_api_spec = reduce_openapi_spec(raw_openai_api_spec)with open("klarna_openapi.yaml") as f: raw_klarna_api_spec = yaml.load(f, Loader=yaml.Loader)klarna_api_spec = reduce_openapi_spec(raw_klarna_api_spec)with open("spotify_openapi.yaml") as f: raw_spotify_api_spec = yaml.load(f, Loader=yaml.Loader)spotify_api_spec = reduce_openapi_spec(raw_spotify_api_spec)We'll work with the Spotify API as one of the examples of a somewhat complex API. There's a bit of auth-related setup to do if you want to replicate this.You'll have to set up an application in the Spotify developer console, documented here, to get credentials: CLIENT_ID, CLIENT_SECRET, and REDIRECT_URI.To get an access tokens (and keep them fresh), you can implement the oauth flows, or you can use spotipy. If you've set your Spotify creedentials as environment variables SPOTIPY_CLIENT_ID, SPOTIPY_CLIENT_SECRET, and SPOTIPY_REDIRECT_URI, you can use the helper functions below:import spotipy.util as utilfrom langchain.requests import RequestsWrapperdef construct_spotify_auth_headers(raw_spec: dict): scopes = list( raw_spec["components"]["securitySchemes"]["oauth_2_0"]["flows"][ "authorizationCode" ]["scopes"].keys() ) access_token = util.prompt_for_user_token(scope=",".join(scopes)) return {"Authorization": f"Bearer {access_token}"}# Get API credentials.headers = construct_spotify_auth_headers(raw_spotify_api_spec)requests_wrapper = RequestsWrapper(headers=headers)How big is this spec?​endpoints = [ (route, operation) for route, operations in raw_spotify_api_spec["paths"].items() for operation in operations if operation in ["get", "post"]]len(endpoints) 63import tiktokenenc = tiktoken.encoding_for_model("text-davinci-003")def
2,764
count_tokens(s): return len(enc.encode(s))count_tokens(yaml.dump(raw_spotify_api_spec)) 80326Let's see some examples!‚ÄãStarting with GPT-4. (Some robustness iterations under way for GPT-3 family.)from langchain.llms.openai import OpenAIfrom langchain.agents.agent_toolkits.openapi import plannerllm = OpenAI(model_name="gpt-4", temperature=0.0) /Users/jeremywelborn/src/langchain/langchain/llms/openai.py:169: UserWarning: You are trying to use a chat model. This way of initializing it is no longer supported. Instead, please use: `from langchain.chat_models import ChatOpenAI` warnings.warn( /Users/jeremywelborn/src/langchain/langchain/llms/openai.py:608: UserWarning: You are trying to use a chat model. This way of initializing it is no longer supported. Instead, please use: `from langchain.chat_models import ChatOpenAI` warnings.warn(spotify_agent = planner.create_openapi_agent(spotify_api_spec, requests_wrapper, llm)user_query = ( "make me a playlist with the first song from kind of blue. call it machine blues.")spotify_agent.run(user_query) > Entering new AgentExecutor chain... Action: api_planner Action Input: I need to find the right API calls to create a playlist with the first song from Kind of Blue and name it Machine Blues Observation: 1. GET /search to search for the album "Kind of Blue" 2. GET /albums/{id}/tracks to get the tracks from the "Kind of Blue" album 3. GET /me to get the current user's information 4. POST /users/{user_id}/playlists to create a new playlist named "Machine Blues" for the current user 5. POST /playlists/{playlist_id}/tracks to add the first song from "Kind of Blue" to the "Machine Blues" playlist Thought:I have the plan, now I need to execute the API calls. Action: api_controller Action Input: 1. GET /search to search for the album "Kind of Blue" 2. GET /albums/{id}/tracks to get the tracks from the "Kind of Blue" album 3. GET /me to get the current user's
We can construct agents to consume arbitrary APIs, here APIs conformant to the OpenAPI/Swagger specification.
We can construct agents to consume arbitrary APIs, here APIs conformant to the OpenAPI/Swagger specification. ->: count_tokens(s): return len(enc.encode(s))count_tokens(yaml.dump(raw_spotify_api_spec)) 80326Let's see some examples!‚ÄãStarting with GPT-4. (Some robustness iterations under way for GPT-3 family.)from langchain.llms.openai import OpenAIfrom langchain.agents.agent_toolkits.openapi import plannerllm = OpenAI(model_name="gpt-4", temperature=0.0) /Users/jeremywelborn/src/langchain/langchain/llms/openai.py:169: UserWarning: You are trying to use a chat model. This way of initializing it is no longer supported. Instead, please use: `from langchain.chat_models import ChatOpenAI` warnings.warn( /Users/jeremywelborn/src/langchain/langchain/llms/openai.py:608: UserWarning: You are trying to use a chat model. This way of initializing it is no longer supported. Instead, please use: `from langchain.chat_models import ChatOpenAI` warnings.warn(spotify_agent = planner.create_openapi_agent(spotify_api_spec, requests_wrapper, llm)user_query = ( "make me a playlist with the first song from kind of blue. call it machine blues.")spotify_agent.run(user_query) > Entering new AgentExecutor chain... Action: api_planner Action Input: I need to find the right API calls to create a playlist with the first song from Kind of Blue and name it Machine Blues Observation: 1. GET /search to search for the album "Kind of Blue" 2. GET /albums/{id}/tracks to get the tracks from the "Kind of Blue" album 3. GET /me to get the current user's information 4. POST /users/{user_id}/playlists to create a new playlist named "Machine Blues" for the current user 5. POST /playlists/{playlist_id}/tracks to add the first song from "Kind of Blue" to the "Machine Blues" playlist Thought:I have the plan, now I need to execute the API calls. Action: api_controller Action Input: 1. GET /search to search for the album "Kind of Blue" 2. GET /albums/{id}/tracks to get the tracks from the "Kind of Blue" album 3. GET /me to get the current user's
2,765
album 3. GET /me to get the current user's information 4. POST /users/{user_id}/playlists to create a new playlist named "Machine Blues" for the current user 5. POST /playlists/{playlist_id}/tracks to add the first song from "Kind of Blue" to the "Machine Blues" playlist > Entering new AgentExecutor chain... Action: requests_get Action Input: {"url": "https://api.spotify.com/v1/search?q=Kind%20of%20Blue&type=album", "output_instructions": "Extract the id of the first album in the search results"} Observation: 1weenld61qoidwYuZ1GESA Thought:Action: requests_get Action Input: {"url": "https://api.spotify.com/v1/albums/1weenld61qoidwYuZ1GESA/tracks", "output_instructions": "Extract the id of the first track in the album"} Observation: 7q3kkfAVpmcZ8g6JUThi3o Thought:Action: requests_get Action Input: {"url": "https://api.spotify.com/v1/me", "output_instructions": "Extract the id of the current user"} Observation: 22rhrz4m4kvpxlsb5hezokzwi Thought:Action: requests_post Action Input: {"url": "https://api.spotify.com/v1/users/22rhrz4m4kvpxlsb5hezokzwi/playlists", "data": {"name": "Machine Blues"}, "output_instructions": "Extract the id of the created playlist"} Observation: 7lzoEi44WOISnFYlrAIqyX Thought:Action: requests_post Action Input: {"url": "https://api.spotify.com/v1/playlists/7lzoEi44WOISnFYlrAIqyX/tracks", "data": {"uris": ["spotify:track:7q3kkfAVpmcZ8g6JUThi3o"]}, "output_instructions": "Confirm that the track was added to the playlist"} Observation: The track was added to the playlist, confirmed by the snapshot_id: MiwxODMxNTMxZTFlNzg3ZWFlZmMxYTlmYWQyMDFiYzUwNDEwMTAwZmE1. Thought:I am finished executing the plan. Final Answer: The first song from the "Kind of Blue" album has been added to the "Machine Blues" playlist. > Finished chain. Observation: The first song from the "Kind of Blue" album has been added to the "Machine Blues" playlist. Thought:I am finished executing
We can construct agents to consume arbitrary APIs, here APIs conformant to the OpenAPI/Swagger specification.
We can construct agents to consume arbitrary APIs, here APIs conformant to the OpenAPI/Swagger specification. ->: album 3. GET /me to get the current user's information 4. POST /users/{user_id}/playlists to create a new playlist named "Machine Blues" for the current user 5. POST /playlists/{playlist_id}/tracks to add the first song from "Kind of Blue" to the "Machine Blues" playlist > Entering new AgentExecutor chain... Action: requests_get Action Input: {"url": "https://api.spotify.com/v1/search?q=Kind%20of%20Blue&type=album", "output_instructions": "Extract the id of the first album in the search results"} Observation: 1weenld61qoidwYuZ1GESA Thought:Action: requests_get Action Input: {"url": "https://api.spotify.com/v1/albums/1weenld61qoidwYuZ1GESA/tracks", "output_instructions": "Extract the id of the first track in the album"} Observation: 7q3kkfAVpmcZ8g6JUThi3o Thought:Action: requests_get Action Input: {"url": "https://api.spotify.com/v1/me", "output_instructions": "Extract the id of the current user"} Observation: 22rhrz4m4kvpxlsb5hezokzwi Thought:Action: requests_post Action Input: {"url": "https://api.spotify.com/v1/users/22rhrz4m4kvpxlsb5hezokzwi/playlists", "data": {"name": "Machine Blues"}, "output_instructions": "Extract the id of the created playlist"} Observation: 7lzoEi44WOISnFYlrAIqyX Thought:Action: requests_post Action Input: {"url": "https://api.spotify.com/v1/playlists/7lzoEi44WOISnFYlrAIqyX/tracks", "data": {"uris": ["spotify:track:7q3kkfAVpmcZ8g6JUThi3o"]}, "output_instructions": "Confirm that the track was added to the playlist"} Observation: The track was added to the playlist, confirmed by the snapshot_id: MiwxODMxNTMxZTFlNzg3ZWFlZmMxYTlmYWQyMDFiYzUwNDEwMTAwZmE1. Thought:I am finished executing the plan. Final Answer: The first song from the "Kind of Blue" album has been added to the "Machine Blues" playlist. > Finished chain. Observation: The first song from the "Kind of Blue" album has been added to the "Machine Blues" playlist. Thought:I am finished executing
2,766
playlist. Thought:I am finished executing the plan and have created the playlist with the first song from Kind of Blue. Final Answer: I have created a playlist called "Machine Blues" with the first song from the "Kind of Blue" album. > Finished chain. 'I have created a playlist called "Machine Blues" with the first song from the "Kind of Blue" album.'user_query = "give me a song I'd like, make it blues-ey"spotify_agent.run(user_query) > Entering new AgentExecutor chain... Action: api_planner Action Input: I need to find the right API calls to get a blues song recommendation for the user Observation: 1. GET /me to get the current user's information 2. GET /recommendations/available-genre-seeds to retrieve a list of available genres 3. GET /recommendations with the seed_genre parameter set to "blues" to get a blues song recommendation for the user Thought:I have the plan, now I need to execute the API calls. Action: api_controller Action Input: 1. GET /me to get the current user's information 2. GET /recommendations/available-genre-seeds to retrieve a list of available genres 3. GET /recommendations with the seed_genre parameter set to "blues" to get a blues song recommendation for the user > Entering new AgentExecutor chain... Action: requests_get Action Input: {"url": "https://api.spotify.com/v1/me", "output_instructions": "Extract the user's id and username"} Observation: ID: 22rhrz4m4kvpxlsb5hezokzwi, Username: Jeremy Welborn Thought:Action: requests_get Action Input: {"url": "https://api.spotify.com/v1/recommendations/available-genre-seeds", "output_instructions": "Extract the list of available genres"} Observation: acoustic, afrobeat, alt-rock, alternative, ambient, anime, black-metal, bluegrass, blues, bossanova, brazil, breakbeat, british, cantopop, chicago-house, children, chill, classical, club, comedy, country, dance, dancehall, death-metal, deep-house, detroit-techno, disco,
We can construct agents to consume arbitrary APIs, here APIs conformant to the OpenAPI/Swagger specification.
We can construct agents to consume arbitrary APIs, here APIs conformant to the OpenAPI/Swagger specification. ->: playlist. Thought:I am finished executing the plan and have created the playlist with the first song from Kind of Blue. Final Answer: I have created a playlist called "Machine Blues" with the first song from the "Kind of Blue" album. > Finished chain. 'I have created a playlist called "Machine Blues" with the first song from the "Kind of Blue" album.'user_query = "give me a song I'd like, make it blues-ey"spotify_agent.run(user_query) > Entering new AgentExecutor chain... Action: api_planner Action Input: I need to find the right API calls to get a blues song recommendation for the user Observation: 1. GET /me to get the current user's information 2. GET /recommendations/available-genre-seeds to retrieve a list of available genres 3. GET /recommendations with the seed_genre parameter set to "blues" to get a blues song recommendation for the user Thought:I have the plan, now I need to execute the API calls. Action: api_controller Action Input: 1. GET /me to get the current user's information 2. GET /recommendations/available-genre-seeds to retrieve a list of available genres 3. GET /recommendations with the seed_genre parameter set to "blues" to get a blues song recommendation for the user > Entering new AgentExecutor chain... Action: requests_get Action Input: {"url": "https://api.spotify.com/v1/me", "output_instructions": "Extract the user's id and username"} Observation: ID: 22rhrz4m4kvpxlsb5hezokzwi, Username: Jeremy Welborn Thought:Action: requests_get Action Input: {"url": "https://api.spotify.com/v1/recommendations/available-genre-seeds", "output_instructions": "Extract the list of available genres"} Observation: acoustic, afrobeat, alt-rock, alternative, ambient, anime, black-metal, bluegrass, blues, bossanova, brazil, breakbeat, british, cantopop, chicago-house, children, chill, classical, club, comedy, country, dance, dancehall, death-metal, deep-house, detroit-techno, disco,
2,767
death-metal, deep-house, detroit-techno, disco, disney, drum-and-bass, dub, dubstep, edm, electro, electronic, emo, folk, forro, french, funk, garage, german, gospel, goth, grindcore, groove, grunge, guitar, happy, hard-rock, hardcore, hardstyle, heavy-metal, hip-hop, holidays, honky-tonk, house, idm, indian, indie, indie-pop, industrial, iranian, j-dance, j-idol, j-pop, j-rock, jazz, k-pop, kids, latin, latino, malay, mandopop, metal, metal-misc, metalcore, minimal-techno, movies, mpb, new-age, new-release, opera, pagode, party, philippines- Thought: Retrying langchain.llms.openai.completion_with_retry.<locals>._completion_with_retry in 4.0 seconds as it raised RateLimitError: That model is currently overloaded with other requests. You can retry your request, or contact us through our help center at help.openai.com if the error persists. (Please include the request ID 2167437a0072228238f3c0c5b3882764 in your message.). Action: requests_get Action Input: {"url": "https://api.spotify.com/v1/recommendations?seed_genres=blues", "output_instructions": "Extract the list of recommended tracks with their ids and names"} Observation: [ { id: '03lXHmokj9qsXspNsPoirR', name: 'Get Away Jordan' } ] Thought:I am finished executing the plan. Final Answer: The recommended blues song for user Jeremy Welborn (ID: 22rhrz4m4kvpxlsb5hezokzwi) is "Get Away Jordan" with the track ID: 03lXHmokj9qsXspNsPoirR. > Finished chain. Observation: The recommended blues song for user Jeremy Welborn (ID: 22rhrz4m4kvpxlsb5hezokzwi) is "Get Away Jordan" with the track ID: 03lXHmokj9qsXspNsPoirR. Thought:I am finished executing the plan and have the information the user asked for. Final Answer: The recommended blues song for you is "Get Away Jordan" with the track ID: 03lXHmokj9qsXspNsPoirR. > Finished chain. 'The recommended blues song for you is "Get Away Jordan" with the track ID: 03lXHmokj9qsXspNsPoirR.'Try another
We can construct agents to consume arbitrary APIs, here APIs conformant to the OpenAPI/Swagger specification.
We can construct agents to consume arbitrary APIs, here APIs conformant to the OpenAPI/Swagger specification. ->: death-metal, deep-house, detroit-techno, disco, disney, drum-and-bass, dub, dubstep, edm, electro, electronic, emo, folk, forro, french, funk, garage, german, gospel, goth, grindcore, groove, grunge, guitar, happy, hard-rock, hardcore, hardstyle, heavy-metal, hip-hop, holidays, honky-tonk, house, idm, indian, indie, indie-pop, industrial, iranian, j-dance, j-idol, j-pop, j-rock, jazz, k-pop, kids, latin, latino, malay, mandopop, metal, metal-misc, metalcore, minimal-techno, movies, mpb, new-age, new-release, opera, pagode, party, philippines- Thought: Retrying langchain.llms.openai.completion_with_retry.<locals>._completion_with_retry in 4.0 seconds as it raised RateLimitError: That model is currently overloaded with other requests. You can retry your request, or contact us through our help center at help.openai.com if the error persists. (Please include the request ID 2167437a0072228238f3c0c5b3882764 in your message.). Action: requests_get Action Input: {"url": "https://api.spotify.com/v1/recommendations?seed_genres=blues", "output_instructions": "Extract the list of recommended tracks with their ids and names"} Observation: [ { id: '03lXHmokj9qsXspNsPoirR', name: 'Get Away Jordan' } ] Thought:I am finished executing the plan. Final Answer: The recommended blues song for user Jeremy Welborn (ID: 22rhrz4m4kvpxlsb5hezokzwi) is "Get Away Jordan" with the track ID: 03lXHmokj9qsXspNsPoirR. > Finished chain. Observation: The recommended blues song for user Jeremy Welborn (ID: 22rhrz4m4kvpxlsb5hezokzwi) is "Get Away Jordan" with the track ID: 03lXHmokj9qsXspNsPoirR. Thought:I am finished executing the plan and have the information the user asked for. Final Answer: The recommended blues song for you is "Get Away Jordan" with the track ID: 03lXHmokj9qsXspNsPoirR. > Finished chain. 'The recommended blues song for you is "Get Away Jordan" with the track ID: 03lXHmokj9qsXspNsPoirR.'Try another
2,768
the track ID: 03lXHmokj9qsXspNsPoirR.'Try another API.‚Äãheaders = {"Authorization": f"Bearer {os.getenv('OPENAI_API_KEY')}"}openai_requests_wrapper = RequestsWrapper(headers=headers)# Meta!llm = OpenAI(model_name="gpt-4", temperature=0.25)openai_agent = planner.create_openapi_agent( openai_api_spec, openai_requests_wrapper, llm)user_query = "generate a short piece of advice"openai_agent.run(user_query) > Entering new AgentExecutor chain... Action: api_planner Action Input: I need to find the right API calls to generate a short piece of advice Observation: 1. GET /engines to retrieve the list of available engines 2. POST /completions with the selected engine and a prompt for generating a short piece of advice Thought:I have the plan, now I need to execute the API calls. Action: api_controller Action Input: 1. GET /engines to retrieve the list of available engines 2. POST /completions with the selected engine and a prompt for generating a short piece of advice > Entering new AgentExecutor chain... Action: requests_get Action Input: {"url": "https://api.openai.com/v1/engines", "output_instructions": "Extract the ids of the engines"} Observation: babbage, davinci, text-davinci-edit-001, babbage-code-search-code, text-similarity-babbage-001, code-davinci-edit-001, text-davinci-001, ada, babbage-code-search-text, babbage-similarity, whisper-1, code-search-babbage-text-001, text-curie-001, code-search-babbage-code-001, text-ada-001, text-embedding-ada-002, text-similarity-ada-001, curie-instruct-beta, ada-code-search-code, ada-similarity, text-davinci-003, code-search-ada-text-001, text-search-ada-query-001, davinci-search-document, ada-code-search-text, text-search-ada-doc-001, davinci-instruct-beta, text-similarity-curie-001, code-search-ada-code-001 Thought:I will use the "davinci" engine to generate a short piece of advice. Action: requests_post Action Input: {"url":
We can construct agents to consume arbitrary APIs, here APIs conformant to the OpenAPI/Swagger specification.
We can construct agents to consume arbitrary APIs, here APIs conformant to the OpenAPI/Swagger specification. ->: the track ID: 03lXHmokj9qsXspNsPoirR.'Try another API.‚Äãheaders = {"Authorization": f"Bearer {os.getenv('OPENAI_API_KEY')}"}openai_requests_wrapper = RequestsWrapper(headers=headers)# Meta!llm = OpenAI(model_name="gpt-4", temperature=0.25)openai_agent = planner.create_openapi_agent( openai_api_spec, openai_requests_wrapper, llm)user_query = "generate a short piece of advice"openai_agent.run(user_query) > Entering new AgentExecutor chain... Action: api_planner Action Input: I need to find the right API calls to generate a short piece of advice Observation: 1. GET /engines to retrieve the list of available engines 2. POST /completions with the selected engine and a prompt for generating a short piece of advice Thought:I have the plan, now I need to execute the API calls. Action: api_controller Action Input: 1. GET /engines to retrieve the list of available engines 2. POST /completions with the selected engine and a prompt for generating a short piece of advice > Entering new AgentExecutor chain... Action: requests_get Action Input: {"url": "https://api.openai.com/v1/engines", "output_instructions": "Extract the ids of the engines"} Observation: babbage, davinci, text-davinci-edit-001, babbage-code-search-code, text-similarity-babbage-001, code-davinci-edit-001, text-davinci-001, ada, babbage-code-search-text, babbage-similarity, whisper-1, code-search-babbage-text-001, text-curie-001, code-search-babbage-code-001, text-ada-001, text-embedding-ada-002, text-similarity-ada-001, curie-instruct-beta, ada-code-search-code, ada-similarity, text-davinci-003, code-search-ada-text-001, text-search-ada-query-001, davinci-search-document, ada-code-search-text, text-search-ada-doc-001, davinci-instruct-beta, text-similarity-curie-001, code-search-ada-code-001 Thought:I will use the "davinci" engine to generate a short piece of advice. Action: requests_post Action Input: {"url":
2,769
Action: requests_post Action Input: {"url": "https://api.openai.com/v1/completions", "data": {"engine": "davinci", "prompt": "Give me a short piece of advice on how to be more productive."}, "output_instructions": "Extract the text from the first choice"} Observation: "you must provide a model parameter" Thought:!! Could not _extract_tool_and_input from "I cannot finish executing the plan without knowing how to provide the model parameter correctly." in _get_next_action I cannot finish executing the plan without knowing how to provide the model parameter correctly. > Finished chain. Observation: I need more information on how to provide the model parameter correctly in the POST request to generate a short piece of advice. Thought:I need to adjust my plan to include the model parameter in the POST request. Action: api_planner Action Input: I need to find the right API calls to generate a short piece of advice, including the model parameter in the POST request Observation: 1. GET /models to retrieve the list of available models 2. Choose a suitable model from the list 3. POST /completions with the chosen model as a parameter to generate a short piece of advice Thought:I have an updated plan, now I need to execute the API calls. Action: api_controller Action Input: 1. GET /models to retrieve the list of available models 2. Choose a suitable model from the list 3. POST /completions with the chosen model as a parameter to generate a short piece of advice > Entering new AgentExecutor chain... Action: requests_get Action Input: {"url": "https://api.openai.com/v1/models", "output_instructions": "Extract the ids of the available models"} Observation: babbage, davinci, text-davinci-edit-001, babbage-code-search-code, text-similarity-babbage-001, code-davinci-edit-001, text-davinci-edit-001, ada Thought:Action: requests_post Action Input: {"url": "https://api.openai.com/v1/completions",
We can construct agents to consume arbitrary APIs, here APIs conformant to the OpenAPI/Swagger specification.
We can construct agents to consume arbitrary APIs, here APIs conformant to the OpenAPI/Swagger specification. ->: Action: requests_post Action Input: {"url": "https://api.openai.com/v1/completions", "data": {"engine": "davinci", "prompt": "Give me a short piece of advice on how to be more productive."}, "output_instructions": "Extract the text from the first choice"} Observation: "you must provide a model parameter" Thought:!! Could not _extract_tool_and_input from "I cannot finish executing the plan without knowing how to provide the model parameter correctly." in _get_next_action I cannot finish executing the plan without knowing how to provide the model parameter correctly. > Finished chain. Observation: I need more information on how to provide the model parameter correctly in the POST request to generate a short piece of advice. Thought:I need to adjust my plan to include the model parameter in the POST request. Action: api_planner Action Input: I need to find the right API calls to generate a short piece of advice, including the model parameter in the POST request Observation: 1. GET /models to retrieve the list of available models 2. Choose a suitable model from the list 3. POST /completions with the chosen model as a parameter to generate a short piece of advice Thought:I have an updated plan, now I need to execute the API calls. Action: api_controller Action Input: 1. GET /models to retrieve the list of available models 2. Choose a suitable model from the list 3. POST /completions with the chosen model as a parameter to generate a short piece of advice > Entering new AgentExecutor chain... Action: requests_get Action Input: {"url": "https://api.openai.com/v1/models", "output_instructions": "Extract the ids of the available models"} Observation: babbage, davinci, text-davinci-edit-001, babbage-code-search-code, text-similarity-babbage-001, code-davinci-edit-001, text-davinci-edit-001, ada Thought:Action: requests_post Action Input: {"url": "https://api.openai.com/v1/completions",
2,770
{"url": "https://api.openai.com/v1/completions", "data": {"model": "davinci", "prompt": "Give me a short piece of advice on how to improve communication skills."}, "output_instructions": "Extract the text from the first choice"} Observation: "I'd like to broaden my horizon.\n\nI was trying to" Thought:I cannot finish executing the plan without knowing some other information. Final Answer: The generated text is not a piece of advice on improving communication skills. I would need to retry the API call with a different prompt or model to get a more relevant response. > Finished chain. Observation: The generated text is not a piece of advice on improving communication skills. I would need to retry the API call with a different prompt or model to get a more relevant response. Thought:I need to adjust my plan to include a more specific prompt for generating a short piece of advice on improving communication skills. Action: api_planner Action Input: I need to find the right API calls to generate a short piece of advice on improving communication skills, including the model parameter in the POST request Observation: 1. GET /models to retrieve the list of available models 2. Choose a suitable model for generating text (e.g., text-davinci-002) 3. POST /completions with the chosen model and a prompt related to improving communication skills to generate a short piece of advice Thought:I have an updated plan, now I need to execute the API calls. Action: api_controller Action Input: 1. GET /models to retrieve the list of available models 2. Choose a suitable model for generating text (e.g., text-davinci-002) 3. POST /completions with the chosen model and a prompt related to improving communication skills to generate a short piece of advice > Entering new AgentExecutor chain... Action: requests_get Action Input: {"url": "https://api.openai.com/v1/models", "output_instructions": "Extract the names of the
We can construct agents to consume arbitrary APIs, here APIs conformant to the OpenAPI/Swagger specification.
We can construct agents to consume arbitrary APIs, here APIs conformant to the OpenAPI/Swagger specification. ->: {"url": "https://api.openai.com/v1/completions", "data": {"model": "davinci", "prompt": "Give me a short piece of advice on how to improve communication skills."}, "output_instructions": "Extract the text from the first choice"} Observation: "I'd like to broaden my horizon.\n\nI was trying to" Thought:I cannot finish executing the plan without knowing some other information. Final Answer: The generated text is not a piece of advice on improving communication skills. I would need to retry the API call with a different prompt or model to get a more relevant response. > Finished chain. Observation: The generated text is not a piece of advice on improving communication skills. I would need to retry the API call with a different prompt or model to get a more relevant response. Thought:I need to adjust my plan to include a more specific prompt for generating a short piece of advice on improving communication skills. Action: api_planner Action Input: I need to find the right API calls to generate a short piece of advice on improving communication skills, including the model parameter in the POST request Observation: 1. GET /models to retrieve the list of available models 2. Choose a suitable model for generating text (e.g., text-davinci-002) 3. POST /completions with the chosen model and a prompt related to improving communication skills to generate a short piece of advice Thought:I have an updated plan, now I need to execute the API calls. Action: api_controller Action Input: 1. GET /models to retrieve the list of available models 2. Choose a suitable model for generating text (e.g., text-davinci-002) 3. POST /completions with the chosen model and a prompt related to improving communication skills to generate a short piece of advice > Entering new AgentExecutor chain... Action: requests_get Action Input: {"url": "https://api.openai.com/v1/models", "output_instructions": "Extract the names of the
2,771
"output_instructions": "Extract the names of the models"} Observation: babbage, davinci, text-davinci-edit-001, babbage-code-search-code, text-similarity-babbage-001, code-davinci-edit-001, text-davinci-edit-001, ada Thought:Action: requests_post Action Input: {"url": "https://api.openai.com/v1/completions", "data": {"model": "text-davinci-002", "prompt": "Give a short piece of advice on how to improve communication skills"}, "output_instructions": "Extract the text from the first choice"} Observation: "Some basic advice for improving communication skills would be to make sure to listen" Thought:I am finished executing the plan. Final Answer: Some basic advice for improving communication skills would be to make sure to listen. > Finished chain. Observation: Some basic advice for improving communication skills would be to make sure to listen. Thought:I am finished executing the plan and have the information the user asked for. Final Answer: A short piece of advice for improving communication skills is to make sure to listen. > Finished chain. 'A short piece of advice for improving communication skills is to make sure to listen.'Takes awhile to get there!2nd example: "json explorer" agent‚ÄãHere's an agent that's not particularly practical, but neat! The agent has access to 2 toolkits. One comprises tools to interact with json: one tool to list the keys of a json object and another tool to get the value for a given key. The other toolkit comprises requests wrappers to send GET and POST requests. This agent consumes a lot calls to the language model, but does a surprisingly decent job.from langchain.agents import create_openapi_agentfrom langchain.agents.agent_toolkits import OpenAPIToolkitfrom langchain.llms.openai import OpenAIfrom langchain.requests import TextRequestsWrapperfrom langchain.tools.json.tool import JsonSpecwith open("openai_openapi.yaml") as f: data = yaml.load(f, Loader=yaml.FullLoader)json_spec
We can construct agents to consume arbitrary APIs, here APIs conformant to the OpenAPI/Swagger specification.
We can construct agents to consume arbitrary APIs, here APIs conformant to the OpenAPI/Swagger specification. ->: "output_instructions": "Extract the names of the models"} Observation: babbage, davinci, text-davinci-edit-001, babbage-code-search-code, text-similarity-babbage-001, code-davinci-edit-001, text-davinci-edit-001, ada Thought:Action: requests_post Action Input: {"url": "https://api.openai.com/v1/completions", "data": {"model": "text-davinci-002", "prompt": "Give a short piece of advice on how to improve communication skills"}, "output_instructions": "Extract the text from the first choice"} Observation: "Some basic advice for improving communication skills would be to make sure to listen" Thought:I am finished executing the plan. Final Answer: Some basic advice for improving communication skills would be to make sure to listen. > Finished chain. Observation: Some basic advice for improving communication skills would be to make sure to listen. Thought:I am finished executing the plan and have the information the user asked for. Final Answer: A short piece of advice for improving communication skills is to make sure to listen. > Finished chain. 'A short piece of advice for improving communication skills is to make sure to listen.'Takes awhile to get there!2nd example: "json explorer" agent‚ÄãHere's an agent that's not particularly practical, but neat! The agent has access to 2 toolkits. One comprises tools to interact with json: one tool to list the keys of a json object and another tool to get the value for a given key. The other toolkit comprises requests wrappers to send GET and POST requests. This agent consumes a lot calls to the language model, but does a surprisingly decent job.from langchain.agents import create_openapi_agentfrom langchain.agents.agent_toolkits import OpenAPIToolkitfrom langchain.llms.openai import OpenAIfrom langchain.requests import TextRequestsWrapperfrom langchain.tools.json.tool import JsonSpecwith open("openai_openapi.yaml") as f: data = yaml.load(f, Loader=yaml.FullLoader)json_spec
2,772
= yaml.load(f, Loader=yaml.FullLoader)json_spec = JsonSpec(dict_=data, max_value_length=4000)openapi_toolkit = OpenAPIToolkit.from_llm( OpenAI(temperature=0), json_spec, openai_requests_wrapper, verbose=True)openapi_agent_executor = create_openapi_agent( llm=OpenAI(temperature=0), toolkit=openapi_toolkit, verbose=True)openapi_agent_executor.run( "Make a post request to openai /completions. The prompt should be 'tell me a joke.'") > Entering new AgentExecutor chain... Action: json_explorer Action Input: What is the base url for the API? > Entering new AgentExecutor chain... Action: json_spec_list_keys Action Input: data Observation: ['openapi', 'info', 'servers', 'tags', 'paths', 'components', 'x-oaiMeta'] Thought: I should look at the servers key to see what the base url is Action: json_spec_list_keys Action Input: data["servers"][0] Observation: ValueError('Value at path `data["servers"][0]` is not a dict, get the value directly.') Thought: I should get the value of the servers key Action: json_spec_get_value Action Input: data["servers"][0] Observation: {'url': 'https://api.openai.com/v1'} Thought: I now know the base url for the API Final Answer: The base url for the API is https://api.openai.com/v1 > Finished chain. Observation: The base url for the API is https://api.openai.com/v1 Thought: I should find the path for the /completions endpoint. Action: json_explorer Action Input: What is the path for the /completions endpoint? > Entering new AgentExecutor chain... Action: json_spec_list_keys Action Input: data Observation: ['openapi', 'info', 'servers', 'tags', 'paths', 'components', 'x-oaiMeta'] Thought: I should look at the paths key to see what endpoints exist Action: json_spec_list_keys Action Input: data["paths"] Observation: ['/engines', '/engines/{engine_id}', '/completions', '/chat/completions', '/edits', '/images/generations',
We can construct agents to consume arbitrary APIs, here APIs conformant to the OpenAPI/Swagger specification.
We can construct agents to consume arbitrary APIs, here APIs conformant to the OpenAPI/Swagger specification. ->: = yaml.load(f, Loader=yaml.FullLoader)json_spec = JsonSpec(dict_=data, max_value_length=4000)openapi_toolkit = OpenAPIToolkit.from_llm( OpenAI(temperature=0), json_spec, openai_requests_wrapper, verbose=True)openapi_agent_executor = create_openapi_agent( llm=OpenAI(temperature=0), toolkit=openapi_toolkit, verbose=True)openapi_agent_executor.run( "Make a post request to openai /completions. The prompt should be 'tell me a joke.'") > Entering new AgentExecutor chain... Action: json_explorer Action Input: What is the base url for the API? > Entering new AgentExecutor chain... Action: json_spec_list_keys Action Input: data Observation: ['openapi', 'info', 'servers', 'tags', 'paths', 'components', 'x-oaiMeta'] Thought: I should look at the servers key to see what the base url is Action: json_spec_list_keys Action Input: data["servers"][0] Observation: ValueError('Value at path `data["servers"][0]` is not a dict, get the value directly.') Thought: I should get the value of the servers key Action: json_spec_get_value Action Input: data["servers"][0] Observation: {'url': 'https://api.openai.com/v1'} Thought: I now know the base url for the API Final Answer: The base url for the API is https://api.openai.com/v1 > Finished chain. Observation: The base url for the API is https://api.openai.com/v1 Thought: I should find the path for the /completions endpoint. Action: json_explorer Action Input: What is the path for the /completions endpoint? > Entering new AgentExecutor chain... Action: json_spec_list_keys Action Input: data Observation: ['openapi', 'info', 'servers', 'tags', 'paths', 'components', 'x-oaiMeta'] Thought: I should look at the paths key to see what endpoints exist Action: json_spec_list_keys Action Input: data["paths"] Observation: ['/engines', '/engines/{engine_id}', '/completions', '/chat/completions', '/edits', '/images/generations',
2,773
'/edits', '/images/generations', '/images/edits', '/images/variations', '/embeddings', '/audio/transcriptions', '/audio/translations', '/engines/{engine_id}/search', '/files', '/files/{file_id}', '/files/{file_id}/content', '/answers', '/classifications', '/fine-tunes', '/fine-tunes/{fine_tune_id}', '/fine-tunes/{fine_tune_id}/cancel', '/fine-tunes/{fine_tune_id}/events', '/models', '/models/{model}', '/moderations'] Thought: I now know the path for the /completions endpoint Final Answer: The path for the /completions endpoint is data["paths"][2] > Finished chain. Observation: The path for the /completions endpoint is data["paths"][2] Thought: I should find the required parameters for the POST request. Action: json_explorer Action Input: What are the required parameters for a POST request to the /completions endpoint? > Entering new AgentExecutor chain... Action: json_spec_list_keys Action Input: data Observation: ['openapi', 'info', 'servers', 'tags', 'paths', 'components', 'x-oaiMeta'] Thought: I should look at the paths key to see what endpoints exist Action: json_spec_list_keys Action Input: data["paths"] Observation: ['/engines', '/engines/{engine_id}', '/completions', '/chat/completions', '/edits', '/images/generations', '/images/edits', '/images/variations', '/embeddings', '/audio/transcriptions', '/audio/translations', '/engines/{engine_id}/search', '/files', '/files/{file_id}', '/files/{file_id}/content', '/answers', '/classifications', '/fine-tunes', '/fine-tunes/{fine_tune_id}', '/fine-tunes/{fine_tune_id}/cancel', '/fine-tunes/{fine_tune_id}/events', '/models', '/models/{model}', '/moderations'] Thought: I should look at the /completions endpoint to see what parameters are required Action: json_spec_list_keys Action Input: data["paths"]["/completions"] Observation: ['post'] Thought: I should look at the post key to see what parameters are required Action: json_spec_list_keys
We can construct agents to consume arbitrary APIs, here APIs conformant to the OpenAPI/Swagger specification.
We can construct agents to consume arbitrary APIs, here APIs conformant to the OpenAPI/Swagger specification. ->: '/edits', '/images/generations', '/images/edits', '/images/variations', '/embeddings', '/audio/transcriptions', '/audio/translations', '/engines/{engine_id}/search', '/files', '/files/{file_id}', '/files/{file_id}/content', '/answers', '/classifications', '/fine-tunes', '/fine-tunes/{fine_tune_id}', '/fine-tunes/{fine_tune_id}/cancel', '/fine-tunes/{fine_tune_id}/events', '/models', '/models/{model}', '/moderations'] Thought: I now know the path for the /completions endpoint Final Answer: The path for the /completions endpoint is data["paths"][2] > Finished chain. Observation: The path for the /completions endpoint is data["paths"][2] Thought: I should find the required parameters for the POST request. Action: json_explorer Action Input: What are the required parameters for a POST request to the /completions endpoint? > Entering new AgentExecutor chain... Action: json_spec_list_keys Action Input: data Observation: ['openapi', 'info', 'servers', 'tags', 'paths', 'components', 'x-oaiMeta'] Thought: I should look at the paths key to see what endpoints exist Action: json_spec_list_keys Action Input: data["paths"] Observation: ['/engines', '/engines/{engine_id}', '/completions', '/chat/completions', '/edits', '/images/generations', '/images/edits', '/images/variations', '/embeddings', '/audio/transcriptions', '/audio/translations', '/engines/{engine_id}/search', '/files', '/files/{file_id}', '/files/{file_id}/content', '/answers', '/classifications', '/fine-tunes', '/fine-tunes/{fine_tune_id}', '/fine-tunes/{fine_tune_id}/cancel', '/fine-tunes/{fine_tune_id}/events', '/models', '/models/{model}', '/moderations'] Thought: I should look at the /completions endpoint to see what parameters are required Action: json_spec_list_keys Action Input: data["paths"]["/completions"] Observation: ['post'] Thought: I should look at the post key to see what parameters are required Action: json_spec_list_keys
2,774
are required Action: json_spec_list_keys Action Input: data["paths"]["/completions"]["post"] Observation: ['operationId', 'tags', 'summary', 'requestBody', 'responses', 'x-oaiMeta'] Thought: I should look at the requestBody key to see what parameters are required Action: json_spec_list_keys Action Input: data["paths"]["/completions"]["post"]["requestBody"] Observation: ['required', 'content'] Thought: I should look at the content key to see what parameters are required Action: json_spec_list_keys Action Input: data["paths"]["/completions"]["post"]["requestBody"]["content"] Observation: ['application/json'] Thought: I should look at the application/json key to see what parameters are required Action: json_spec_list_keys Action Input: data["paths"]["/completions"]["post"]["requestBody"]["content"]["application/json"] Observation: ['schema'] Thought: I should look at the schema key to see what parameters are required Action: json_spec_list_keys Action Input: data["paths"]["/completions"]["post"]["requestBody"]["content"]["application/json"]["schema"] Observation: ['$ref'] Thought: I should look at the $ref key to see what parameters are required Action: json_spec_list_keys Action Input: data["paths"]["/completions"]["post"]["requestBody"]["content"]["application/json"]["schema"]["$ref"] Observation: ValueError('Value at path `data["paths"]["/completions"]["post"]["requestBody"]["content"]["application/json"]["schema"]["$ref"]` is not a dict, get the value directly.') Thought: I should look at the $ref key to get the value directly Action: json_spec_get_value Action Input: data["paths"]["/completions"]["post"]["requestBody"]["content"]["application/json"]["schema"]["$ref"] Observation: #/components/schemas/CreateCompletionRequest Thought: I should look at the CreateCompletionRequest schema to see what parameters are required Action: json_spec_list_keys Action Input:
We can construct agents to consume arbitrary APIs, here APIs conformant to the OpenAPI/Swagger specification.
We can construct agents to consume arbitrary APIs, here APIs conformant to the OpenAPI/Swagger specification. ->: are required Action: json_spec_list_keys Action Input: data["paths"]["/completions"]["post"] Observation: ['operationId', 'tags', 'summary', 'requestBody', 'responses', 'x-oaiMeta'] Thought: I should look at the requestBody key to see what parameters are required Action: json_spec_list_keys Action Input: data["paths"]["/completions"]["post"]["requestBody"] Observation: ['required', 'content'] Thought: I should look at the content key to see what parameters are required Action: json_spec_list_keys Action Input: data["paths"]["/completions"]["post"]["requestBody"]["content"] Observation: ['application/json'] Thought: I should look at the application/json key to see what parameters are required Action: json_spec_list_keys Action Input: data["paths"]["/completions"]["post"]["requestBody"]["content"]["application/json"] Observation: ['schema'] Thought: I should look at the schema key to see what parameters are required Action: json_spec_list_keys Action Input: data["paths"]["/completions"]["post"]["requestBody"]["content"]["application/json"]["schema"] Observation: ['$ref'] Thought: I should look at the $ref key to see what parameters are required Action: json_spec_list_keys Action Input: data["paths"]["/completions"]["post"]["requestBody"]["content"]["application/json"]["schema"]["$ref"] Observation: ValueError('Value at path `data["paths"]["/completions"]["post"]["requestBody"]["content"]["application/json"]["schema"]["$ref"]` is not a dict, get the value directly.') Thought: I should look at the $ref key to get the value directly Action: json_spec_get_value Action Input: data["paths"]["/completions"]["post"]["requestBody"]["content"]["application/json"]["schema"]["$ref"] Observation: #/components/schemas/CreateCompletionRequest Thought: I should look at the CreateCompletionRequest schema to see what parameters are required Action: json_spec_list_keys Action Input:
2,775
Action: json_spec_list_keys Action Input: data["components"]["schemas"]["CreateCompletionRequest"] Observation: ['type', 'properties', 'required'] Thought: I should look at the required key to see what parameters are required Action: json_spec_get_value Action Input: data["components"]["schemas"]["CreateCompletionRequest"]["required"] Observation: ['model'] Thought: I now know the final answer Final Answer: The required parameters for a POST request to the /completions endpoint are 'model'. > Finished chain. Observation: The required parameters for a POST request to the /completions endpoint are 'model'. Thought: I now know the parameters needed to make the request. Action: requests_post Action Input: { "url": "https://api.openai.com/v1/completions", "data": { "model": "davinci", "prompt": "tell me a joke" } } Observation: {"id":"cmpl-70Ivzip3dazrIXU8DSVJGzFJj2rdv","object":"text_completion","created":1680307139,"model":"davinci","choices":[{"text":" with mummy not there”\n\nYou dig deep and come up with,","index":0,"logprobs":null,"finish_reason":"length"}],"usage":{"prompt_tokens":4,"completion_tokens":16,"total_tokens":20}} Thought: I now know the final answer. Final Answer: The response of the POST request is {"id":"cmpl-70Ivzip3dazrIXU8DSVJGzFJj2rdv","object":"text_completion","created":1680307139,"model":"davinci","choices":[{"text":" with mummy not there”\n\nYou dig deep and come up with,","index":0,"logprobs":null,"finish_reason":"length"}],"usage":{"prompt_tokens":4,"completion_tokens":16,"total_tokens":20}} > Finished chain. 'The response of the POST request is {"id":"cmpl-70Ivzip3dazrIXU8DSVJGzFJj2rdv","object":"text_completion","created":1680307139,"model":"davinci","choices":[{"text":" with mummy not there”\\n\\nYou dig deep and come up
We can construct agents to consume arbitrary APIs, here APIs conformant to the OpenAPI/Swagger specification.
We can construct agents to consume arbitrary APIs, here APIs conformant to the OpenAPI/Swagger specification. ->: Action: json_spec_list_keys Action Input: data["components"]["schemas"]["CreateCompletionRequest"] Observation: ['type', 'properties', 'required'] Thought: I should look at the required key to see what parameters are required Action: json_spec_get_value Action Input: data["components"]["schemas"]["CreateCompletionRequest"]["required"] Observation: ['model'] Thought: I now know the final answer Final Answer: The required parameters for a POST request to the /completions endpoint are 'model'. > Finished chain. Observation: The required parameters for a POST request to the /completions endpoint are 'model'. Thought: I now know the parameters needed to make the request. Action: requests_post Action Input: { "url": "https://api.openai.com/v1/completions", "data": { "model": "davinci", "prompt": "tell me a joke" } } Observation: {"id":"cmpl-70Ivzip3dazrIXU8DSVJGzFJj2rdv","object":"text_completion","created":1680307139,"model":"davinci","choices":[{"text":" with mummy not there”\n\nYou dig deep and come up with,","index":0,"logprobs":null,"finish_reason":"length"}],"usage":{"prompt_tokens":4,"completion_tokens":16,"total_tokens":20}} Thought: I now know the final answer. Final Answer: The response of the POST request is {"id":"cmpl-70Ivzip3dazrIXU8DSVJGzFJj2rdv","object":"text_completion","created":1680307139,"model":"davinci","choices":[{"text":" with mummy not there”\n\nYou dig deep and come up with,","index":0,"logprobs":null,"finish_reason":"length"}],"usage":{"prompt_tokens":4,"completion_tokens":16,"total_tokens":20}} > Finished chain. 'The response of the POST request is {"id":"cmpl-70Ivzip3dazrIXU8DSVJGzFJj2rdv","object":"text_completion","created":1680307139,"model":"davinci","choices":[{"text":" with mummy not there”\\n\\nYou dig deep and come up
2,776
mummy not there”\\n\\nYou dig deep and come up with,","index":0,"logprobs":null,"finish_reason":"length"}],"usage":{"prompt_tokens":4,"completion_tokens":16,"total_tokens":20}}'PreviousOffice365NextNatural Language APIs1st example: hierarchical planning agentTo start, let's collect some OpenAPI specs.How big is this spec?Let's see some examples!2nd example: "json explorer" agentCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
We can construct agents to consume arbitrary APIs, here APIs conformant to the OpenAPI/Swagger specification.
We can construct agents to consume arbitrary APIs, here APIs conformant to the OpenAPI/Swagger specification. ->: mummy not there”\\n\\nYou dig deep and come up with,","index":0,"logprobs":null,"finish_reason":"length"}],"usage":{"prompt_tokens":4,"completion_tokens":16,"total_tokens":20}}'PreviousOffice365NextNatural Language APIs1st example: hierarchical planning agentTo start, let's collect some OpenAPI specs.How big is this spec?Let's see some examples!2nd example: "json explorer" agentCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
2,777
MultiOn | 🦜️🔗 Langchain Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKProvidersAnthropicAWSGoogleMicrosoftOpenAIMoreComponentsLLMsChat modelsDocument loadersDocument transformersText embedding modelsVector storesRetrieversToolsAgents and toolkitsAINetworkAirbyte Question AnsweringAmadeusAzure Cognitive ServicesClickUp Langchain ToolkitCSVDocument ComparisonGithubGitlabGmailGoogle Drive toolJiraJSONMultiOnOffice365OpenAPINatural Language APIsPandas DataframePlayWright BrowserPowerBI DatasetPythonSpark DataframeSpark SQLSQL DatabaseVectorstoreXorbitsMemoryCallbacksChat loadersComponentsAgents and toolkitsMultiOnOn this pageMultiOnThis 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 langchain -qfrom langchain.agents.agent_toolkits import MultionToolkitimport ostoolkit = MultionToolkit()toolkittools = toolkit.get_tools()toolsMultiOn Setup​Login to establish connection with your extension.# Authorize connection to your Browser extentionimport multionmultion.login()Use Multion Toolkit within an Agent​from langchain.llms import OpenAIfrom langchain.agents import initialize_agent, AgentTypellm = OpenAI(temperature=0)from langchain.agents.agent_toolkits import MultionToolkittoolkit = MultionToolkit()tools=toolkit.get_tools()agent = initialize_agent( tools=toolkit.get_tools(), llm=llm, agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose = True)agent.run( "Tweet 'Hi from MultiOn'")PreviousJSONNextOffice365MultiOn SetupUse Multion Toolkit within an AgentCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
This notebook walks you through connecting LangChain to the MultiOn Client in your browser
This notebook walks you through connecting LangChain to the MultiOn Client in your browser ->: MultiOn | 🦜️🔗 Langchain Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKProvidersAnthropicAWSGoogleMicrosoftOpenAIMoreComponentsLLMsChat modelsDocument loadersDocument transformersText embedding modelsVector storesRetrieversToolsAgents and toolkitsAINetworkAirbyte Question AnsweringAmadeusAzure Cognitive ServicesClickUp Langchain ToolkitCSVDocument ComparisonGithubGitlabGmailGoogle Drive toolJiraJSONMultiOnOffice365OpenAPINatural Language APIsPandas DataframePlayWright BrowserPowerBI DatasetPythonSpark DataframeSpark SQLSQL DatabaseVectorstoreXorbitsMemoryCallbacksChat loadersComponentsAgents and toolkitsMultiOnOn this pageMultiOnThis 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 langchain -qfrom langchain.agents.agent_toolkits import MultionToolkitimport ostoolkit = MultionToolkit()toolkittools = toolkit.get_tools()toolsMultiOn Setup​Login to establish connection with your extension.# Authorize connection to your Browser extentionimport multionmultion.login()Use Multion Toolkit within an Agent​from langchain.llms import OpenAIfrom langchain.agents import initialize_agent, AgentTypellm = OpenAI(temperature=0)from langchain.agents.agent_toolkits import MultionToolkittoolkit = MultionToolkit()tools=toolkit.get_tools()agent = initialize_agent( tools=toolkit.get_tools(), llm=llm, agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose = True)agent.run( "Tweet 'Hi from MultiOn'")PreviousJSONNextOffice365MultiOn SetupUse Multion Toolkit within an AgentCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
2,778
SQL Database | 🦜️🔗 Langchain
This notebook showcases an agent designed to interact with a SQL databases.
This notebook showcases an agent designed to interact with a SQL databases. ->: SQL Database | 🦜️🔗 Langchain
2,779
Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKProvidersAnthropicAWSGoogleMicrosoftOpenAIMoreComponentsLLMsChat modelsDocument loadersDocument transformersText embedding modelsVector storesRetrieversToolsAgents and toolkitsAINetworkAirbyte Question AnsweringAmadeusAzure Cognitive ServicesClickUp Langchain ToolkitCSVDocument ComparisonGithubGitlabGmailGoogle Drive toolJiraJSONMultiOnOffice365OpenAPINatural Language APIsPandas DataframePlayWright BrowserPowerBI DatasetPythonSpark DataframeSpark SQLSQL DatabaseVectorstoreXorbitsMemoryCallbacksChat loadersComponentsAgents and toolkitsSQL DatabaseOn this pageSQL DatabaseThis notebook showcases an agent designed to interact with a SQL databases.
This notebook showcases an agent designed to interact with a SQL databases.
This notebook showcases an agent designed to interact with a SQL databases. ->: Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKProvidersAnthropicAWSGoogleMicrosoftOpenAIMoreComponentsLLMsChat modelsDocument loadersDocument transformersText embedding modelsVector storesRetrieversToolsAgents and toolkitsAINetworkAirbyte Question AnsweringAmadeusAzure Cognitive ServicesClickUp Langchain ToolkitCSVDocument ComparisonGithubGitlabGmailGoogle Drive toolJiraJSONMultiOnOffice365OpenAPINatural Language APIsPandas DataframePlayWright BrowserPowerBI DatasetPythonSpark DataframeSpark SQLSQL DatabaseVectorstoreXorbitsMemoryCallbacksChat loadersComponentsAgents and toolkitsSQL DatabaseOn this pageSQL DatabaseThis notebook showcases an agent designed to interact with a SQL databases.
2,780
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 shows how to initialize the agent using the ZERO_SHOT_REACT_DESCRIPTION agent type.agent_executor = create_sql_agent( llm=OpenAI(temperature=0), toolkit=toolkit, 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_sql_agent(# llm=ChatOpenAI(temperature=0, model="gpt-3.5-turbo-0613"),# toolkit=toolkit,# verbose=True,# agent_type=AgentType.OPENAI_FUNCTIONS# )Disclaimer ⚠️​The query chain may generate insert/update/delete queries. When this is not expected, use a custom prompt or create a SQL users without write permissions.The final user might overload your SQL database by asking a simple question such as "run the biggest query possible". The generated query
This notebook showcases an agent designed to interact with a SQL databases.
This 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 shows how to initialize the agent using the ZERO_SHOT_REACT_DESCRIPTION agent type.agent_executor = create_sql_agent( llm=OpenAI(temperature=0), toolkit=toolkit, 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_sql_agent(# llm=ChatOpenAI(temperature=0, model="gpt-3.5-turbo-0613"),# toolkit=toolkit,# verbose=True,# agent_type=AgentType.OPENAI_FUNCTIONS# )Disclaimer ⚠️​The query chain may generate insert/update/delete queries. When this is not expected, use a custom prompt or create a SQL users without write permissions.The final user might overload your SQL database by asking a simple question such as "run the biggest query possible". The generated query
2,781
the biggest query possible". The generated query might look like:SELECT * FROM "public"."users" JOIN "public"."user_permissions" ON "public"."users".id = "public"."user_permissions".user_id JOIN "public"."projects" ON "public"."users".id = "public"."projects".user_id JOIN "public"."events" ON "public"."projects".id = "public"."events".project_id;For a transactional SQL database, if one of the table above contains millions of rows, the query might cause trouble to other applications using the same database.Most datawarehouse oriented databases support user-level quota, for limiting resource usage.Example: describing a table‚Äãagent_executor.run("Describe the playlisttrack table") > Entering new chain... Invoking: `list_tables_sql_db` with `{}` Album, Artist, Track, PlaylistTrack, InvoiceLine, sales_table, Playlist, Genre, Employee, Customer, Invoice, MediaType Invoking: `schema_sql_db` with `PlaylistTrack` CREATE TABLE "PlaylistTrack" ( "PlaylistId" INTEGER NOT NULL, "TrackId" INTEGER NOT NULL, PRIMARY KEY ("PlaylistId", "TrackId"), FOREIGN KEY("TrackId") REFERENCES "Track" ("TrackId"), FOREIGN KEY("PlaylistId") REFERENCES "Playlist" ("PlaylistId") ) /* 3 rows from PlaylistTrack table: PlaylistId TrackId 1 3402 1 3389 1 3390 */The `PlaylistTrack` table has two columns: `PlaylistId` and `TrackId`. It is a junction table that represents the relationship between playlists and tracks. Here is the schema of the `PlaylistTrack` table: ``` CREATE TABLE "PlaylistTrack" ( "PlaylistId" INTEGER NOT NULL, "TrackId" INTEGER NOT NULL, PRIMARY KEY ("PlaylistId", "TrackId"), FOREIGN KEY("TrackId") REFERENCES "Track" ("TrackId"), FOREIGN KEY("PlaylistId") REFERENCES "Playlist" ("PlaylistId") ) ``` Here are three sample rows from the `PlaylistTrack` table: ``` PlaylistId
This notebook showcases an agent designed to interact with a SQL databases.
This notebook showcases an agent designed to interact with a SQL databases. ->: the biggest query possible". The generated query might look like:SELECT * FROM "public"."users" JOIN "public"."user_permissions" ON "public"."users".id = "public"."user_permissions".user_id JOIN "public"."projects" ON "public"."users".id = "public"."projects".user_id JOIN "public"."events" ON "public"."projects".id = "public"."events".project_id;For a transactional SQL database, if one of the table above contains millions of rows, the query might cause trouble to other applications using the same database.Most datawarehouse oriented databases support user-level quota, for limiting resource usage.Example: describing a table‚Äãagent_executor.run("Describe the playlisttrack table") > Entering new chain... Invoking: `list_tables_sql_db` with `{}` Album, Artist, Track, PlaylistTrack, InvoiceLine, sales_table, Playlist, Genre, Employee, Customer, Invoice, MediaType Invoking: `schema_sql_db` with `PlaylistTrack` CREATE TABLE "PlaylistTrack" ( "PlaylistId" INTEGER NOT NULL, "TrackId" INTEGER NOT NULL, PRIMARY KEY ("PlaylistId", "TrackId"), FOREIGN KEY("TrackId") REFERENCES "Track" ("TrackId"), FOREIGN KEY("PlaylistId") REFERENCES "Playlist" ("PlaylistId") ) /* 3 rows from PlaylistTrack table: PlaylistId TrackId 1 3402 1 3389 1 3390 */The `PlaylistTrack` table has two columns: `PlaylistId` and `TrackId`. It is a junction table that represents the relationship between playlists and tracks. Here is the schema of the `PlaylistTrack` table: ``` CREATE TABLE "PlaylistTrack" ( "PlaylistId" INTEGER NOT NULL, "TrackId" INTEGER NOT NULL, PRIMARY KEY ("PlaylistId", "TrackId"), FOREIGN KEY("TrackId") REFERENCES "Track" ("TrackId"), FOREIGN KEY("PlaylistId") REFERENCES "Playlist" ("PlaylistId") ) ``` Here are three sample rows from the `PlaylistTrack` table: ``` PlaylistId
2,782
`PlaylistTrack` table: ``` PlaylistId TrackId 1 3402 1 3389 1 3390 ``` Please let me know if there is anything else I can help you with. > Finished chain. 'The `PlaylistTrack` table has two columns: `PlaylistId` and `TrackId`. It is a junction table that represents the relationship between playlists and tracks. \n\nHere is the schema of the `PlaylistTrack` table:\n\n```\nCREATE TABLE "PlaylistTrack" (\n\t"PlaylistId" INTEGER NOT NULL, \n\t"TrackId" INTEGER NOT NULL, \n\tPRIMARY KEY ("PlaylistId", "TrackId"), \n\tFOREIGN KEY("TrackId") REFERENCES "Track" ("TrackId"), \n\tFOREIGN KEY("PlaylistId") REFERENCES "Playlist" ("PlaylistId")\n)\n```\n\nHere are three sample rows from the `PlaylistTrack` table:\n\n```\nPlaylistId TrackId\n1 3402\n1 3389\n1 3390\n```\n\nPlease let me know if there is anything else I can help you with.'Example: describing a table, recovering from an error‚ÄãIn this example, the agent tries to search for a table that doesn't exist, but finds the next best resultagent_executor.run("Describe the playlistsong table") > Entering new AgentExecutor chain... Action: list_tables_sql_db Action Input: "" Observation: Genre, PlaylistTrack, MediaType, Invoice, InvoiceLine, Track, Playlist, Customer, Album, Employee, Artist Thought: I should look at the schema of the PlaylistSong table Action: schema_sql_db Action Input: "PlaylistSong" Observation: Error: table_names {'PlaylistSong'} not found in database Thought: I should check the spelling of the table Action: list_tables_sql_db Action Input: "" Observation: Genre, PlaylistTrack, MediaType, Invoice, InvoiceLine, Track, Playlist, Customer, Album, Employee, Artist Thought: The table is called PlaylistTrack Action: schema_sql_db Action Input: "PlaylistTrack" Observation: CREATE TABLE "PlaylistTrack" ( "PlaylistId" INTEGER NOT NULL,
This notebook showcases an agent designed to interact with a SQL databases.
This notebook showcases an agent designed to interact with a SQL databases. ->: `PlaylistTrack` table: ``` PlaylistId TrackId 1 3402 1 3389 1 3390 ``` Please let me know if there is anything else I can help you with. > Finished chain. 'The `PlaylistTrack` table has two columns: `PlaylistId` and `TrackId`. It is a junction table that represents the relationship between playlists and tracks. \n\nHere is the schema of the `PlaylistTrack` table:\n\n```\nCREATE TABLE "PlaylistTrack" (\n\t"PlaylistId" INTEGER NOT NULL, \n\t"TrackId" INTEGER NOT NULL, \n\tPRIMARY KEY ("PlaylistId", "TrackId"), \n\tFOREIGN KEY("TrackId") REFERENCES "Track" ("TrackId"), \n\tFOREIGN KEY("PlaylistId") REFERENCES "Playlist" ("PlaylistId")\n)\n```\n\nHere are three sample rows from the `PlaylistTrack` table:\n\n```\nPlaylistId TrackId\n1 3402\n1 3389\n1 3390\n```\n\nPlease let me know if there is anything else I can help you with.'Example: describing a table, recovering from an error‚ÄãIn this example, the agent tries to search for a table that doesn't exist, but finds the next best resultagent_executor.run("Describe the playlistsong table") > Entering new AgentExecutor chain... Action: list_tables_sql_db Action Input: "" Observation: Genre, PlaylistTrack, MediaType, Invoice, InvoiceLine, Track, Playlist, Customer, Album, Employee, Artist Thought: I should look at the schema of the PlaylistSong table Action: schema_sql_db Action Input: "PlaylistSong" Observation: Error: table_names {'PlaylistSong'} not found in database Thought: I should check the spelling of the table Action: list_tables_sql_db Action Input: "" Observation: Genre, PlaylistTrack, MediaType, Invoice, InvoiceLine, Track, Playlist, Customer, Album, Employee, Artist Thought: The table is called PlaylistTrack Action: schema_sql_db Action Input: "PlaylistTrack" Observation: CREATE TABLE "PlaylistTrack" ( "PlaylistId" INTEGER NOT NULL,
2,783
( "PlaylistId" INTEGER NOT NULL, "TrackId" INTEGER NOT NULL, PRIMARY KEY ("PlaylistId", "TrackId"), FOREIGN KEY("TrackId") REFERENCES "Track" ("TrackId"), FOREIGN KEY("PlaylistId") REFERENCES "Playlist" ("PlaylistId") ) SELECT * FROM 'PlaylistTrack' LIMIT 3; PlaylistId TrackId 1 3402 1 3389 1 3390 Thought: I now know the final answer Final Answer: The PlaylistTrack table contains two columns, PlaylistId and TrackId, which are both integers and are used to link Playlist and Track tables. > Finished chain. 'The PlaylistTrack table contains two columns, PlaylistId and TrackId, which are both integers and are used to link Playlist and Track tables.'Example: running queries​agent_executor.run( "List the total sales per country. Which country's customers spent the most?") > Entering new AgentExecutor chain... Action: list_tables_sql_db Action Input: "" Observation: Invoice, MediaType, Artist, InvoiceLine, Genre, Playlist, Employee, Album, PlaylistTrack, Track, Customer Thought: I should look at the schema of the relevant tables to see what columns I can use. Action: schema_sql_db Action Input: "Invoice, Customer" Observation: CREATE TABLE "Customer" ( "CustomerId" INTEGER NOT NULL, "FirstName" NVARCHAR(40) NOT NULL, "LastName" NVARCHAR(20) NOT NULL, "Company" NVARCHAR(80), "Address" NVARCHAR(70), "City" NVARCHAR(40), "State" NVARCHAR(40), "Country" NVARCHAR(40), "PostalCode" NVARCHAR(10), "Phone" NVARCHAR(24), "Fax" NVARCHAR(24), "Email" NVARCHAR(60) NOT NULL, "SupportRepId" INTEGER, PRIMARY KEY ("CustomerId"), FOREIGN KEY("SupportRepId") REFERENCES "Employee" ("EmployeeId") ) SELECT * FROM 'Customer' LIMIT 3; CustomerId FirstName LastName Company Address City State Country PostalCode Phone Fax Email SupportRepId 1 Luís
This notebook showcases an agent designed to interact with a SQL databases.
This notebook showcases an agent designed to interact with a SQL databases. ->: ( "PlaylistId" INTEGER NOT NULL, "TrackId" INTEGER NOT NULL, PRIMARY KEY ("PlaylistId", "TrackId"), FOREIGN KEY("TrackId") REFERENCES "Track" ("TrackId"), FOREIGN KEY("PlaylistId") REFERENCES "Playlist" ("PlaylistId") ) SELECT * FROM 'PlaylistTrack' LIMIT 3; PlaylistId TrackId 1 3402 1 3389 1 3390 Thought: I now know the final answer Final Answer: The PlaylistTrack table contains two columns, PlaylistId and TrackId, which are both integers and are used to link Playlist and Track tables. > Finished chain. 'The PlaylistTrack table contains two columns, PlaylistId and TrackId, which are both integers and are used to link Playlist and Track tables.'Example: running queries​agent_executor.run( "List the total sales per country. Which country's customers spent the most?") > Entering new AgentExecutor chain... Action: list_tables_sql_db Action Input: "" Observation: Invoice, MediaType, Artist, InvoiceLine, Genre, Playlist, Employee, Album, PlaylistTrack, Track, Customer Thought: I should look at the schema of the relevant tables to see what columns I can use. Action: schema_sql_db Action Input: "Invoice, Customer" Observation: CREATE TABLE "Customer" ( "CustomerId" INTEGER NOT NULL, "FirstName" NVARCHAR(40) NOT NULL, "LastName" NVARCHAR(20) NOT NULL, "Company" NVARCHAR(80), "Address" NVARCHAR(70), "City" NVARCHAR(40), "State" NVARCHAR(40), "Country" NVARCHAR(40), "PostalCode" NVARCHAR(10), "Phone" NVARCHAR(24), "Fax" NVARCHAR(24), "Email" NVARCHAR(60) NOT NULL, "SupportRepId" INTEGER, PRIMARY KEY ("CustomerId"), FOREIGN KEY("SupportRepId") REFERENCES "Employee" ("EmployeeId") ) SELECT * FROM 'Customer' LIMIT 3; CustomerId FirstName LastName Company Address City State Country PostalCode Phone Fax Email SupportRepId 1 Luís
2,784
Phone Fax Email SupportRepId 1 Lu√≠s Gon√ßalves Embraer - Empresa Brasileira de Aeron√°utica S.A. Av. Brigadeiro Faria Lima, 2170 S√£o Jos√© dos Campos SP Brazil 12227-000 +55 (12) 3923-5555 +55 (12) 3923-5566 [email protected] 3 2 Leonie K√∂hler None Theodor-Heuss-Stra√üe 34 Stuttgart None Germany 70174 +49 0711 2842222 None [email protected] 5 3 Fran√ßois Tremblay None 1498 rue B√©langer Montr√©al QC Canada H2G 1A7 +1 (514) 721-4711 None [email protected] 3 CREATE TABLE "Invoice" ( "InvoiceId" INTEGER NOT NULL, "CustomerId" INTEGER NOT NULL, "InvoiceDate" DATETIME NOT NULL, "BillingAddress" NVARCHAR(70), "BillingCity" NVARCHAR(40), "BillingState" NVARCHAR(40), "BillingCountry" NVARCHAR(40), "BillingPostalCode" NVARCHAR(10), "Total" NUMERIC(10, 2) NOT NULL, PRIMARY KEY ("InvoiceId"), FOREIGN KEY("CustomerId") REFERENCES "Customer" ("CustomerId") ) SELECT * FROM 'Invoice' LIMIT 3; InvoiceId CustomerId InvoiceDate BillingAddress BillingCity BillingState BillingCountry BillingPostalCode Total 1 2 2009-01-01 00:00:00 Theodor-Heuss-Stra√üe 34 Stuttgart None Germany 70174 1.98 2 4 2009-01-02 00:00:00 Ullev√•lsveien 14 Oslo None Norway 0171 3.96 3 8 2009-01-03 00:00:00 Gr√©trystraat 63 Brussels None Belgium 1000 5.94 Thought: I should query the Invoice and Customer tables to get the total sales per country. Action: query_sql_db Action Input: SELECT c.Country, SUM(i.Total) AS TotalSales FROM Invoice i INNER JOIN Customer c ON i.CustomerId = c.CustomerId GROUP BY c.Country ORDER BY TotalSales DESC LIMIT 10 Observation: [('USA', 523.0600000000003), ('Canada', 303.9599999999999), ('France', 195.09999999999994), ('Brazil', 190.09999999999997), ('Germany', 156.48), ('United Kingdom', 112.85999999999999), ('Czech Republic', 90.24000000000001), ('Portugal', 77.23999999999998), ('India', 75.25999999999999), ('Chile', 46.62)]
This notebook showcases an agent designed to interact with a SQL databases.
This notebook showcases an agent designed to interact with a SQL databases. ->: Phone Fax Email SupportRepId 1 Lu√≠s Gon√ßalves Embraer - Empresa Brasileira de Aeron√°utica S.A. Av. Brigadeiro Faria Lima, 2170 S√£o Jos√© dos Campos SP Brazil 12227-000 +55 (12) 3923-5555 +55 (12) 3923-5566 [email protected] 3 2 Leonie K√∂hler None Theodor-Heuss-Stra√üe 34 Stuttgart None Germany 70174 +49 0711 2842222 None [email protected] 5 3 Fran√ßois Tremblay None 1498 rue B√©langer Montr√©al QC Canada H2G 1A7 +1 (514) 721-4711 None [email protected] 3 CREATE TABLE "Invoice" ( "InvoiceId" INTEGER NOT NULL, "CustomerId" INTEGER NOT NULL, "InvoiceDate" DATETIME NOT NULL, "BillingAddress" NVARCHAR(70), "BillingCity" NVARCHAR(40), "BillingState" NVARCHAR(40), "BillingCountry" NVARCHAR(40), "BillingPostalCode" NVARCHAR(10), "Total" NUMERIC(10, 2) NOT NULL, PRIMARY KEY ("InvoiceId"), FOREIGN KEY("CustomerId") REFERENCES "Customer" ("CustomerId") ) SELECT * FROM 'Invoice' LIMIT 3; InvoiceId CustomerId InvoiceDate BillingAddress BillingCity BillingState BillingCountry BillingPostalCode Total 1 2 2009-01-01 00:00:00 Theodor-Heuss-Stra√üe 34 Stuttgart None Germany 70174 1.98 2 4 2009-01-02 00:00:00 Ullev√•lsveien 14 Oslo None Norway 0171 3.96 3 8 2009-01-03 00:00:00 Gr√©trystraat 63 Brussels None Belgium 1000 5.94 Thought: I should query the Invoice and Customer tables to get the total sales per country. Action: query_sql_db Action Input: SELECT c.Country, SUM(i.Total) AS TotalSales FROM Invoice i INNER JOIN Customer c ON i.CustomerId = c.CustomerId GROUP BY c.Country ORDER BY TotalSales DESC LIMIT 10 Observation: [('USA', 523.0600000000003), ('Canada', 303.9599999999999), ('France', 195.09999999999994), ('Brazil', 190.09999999999997), ('Germany', 156.48), ('United Kingdom', 112.85999999999999), ('Czech Republic', 90.24000000000001), ('Portugal', 77.23999999999998), ('India', 75.25999999999999), ('Chile', 46.62)]
2,785
75.25999999999999), ('Chile', 46.62)] Thought: I now know the final answer Final Answer: The customers from the USA spent the most, with a total of $523.06. > Finished chain. 'The customers from the USA spent the most, with a total of $523.06.'agent_executor.run( "Show the total number of tracks in each playlist. The Playlist name should be included in the result.") > Entering new AgentExecutor chain... Action: list_tables_sql_db Action Input: "" Observation: Invoice, MediaType, Artist, InvoiceLine, Genre, Playlist, Employee, Album, PlaylistTrack, Track, Customer Thought: I should look at the schema of the Playlist and PlaylistTrack tables to see what columns I can use. Action: schema_sql_db Action Input: "Playlist, PlaylistTrack" Observation: CREATE TABLE "Playlist" ( "PlaylistId" INTEGER NOT NULL, "Name" NVARCHAR(120), PRIMARY KEY ("PlaylistId") ) SELECT * FROM 'Playlist' LIMIT 3; PlaylistId Name 1 Music 2 Movies 3 TV Shows CREATE TABLE "PlaylistTrack" ( "PlaylistId" INTEGER NOT NULL, "TrackId" INTEGER NOT NULL, PRIMARY KEY ("PlaylistId", "TrackId"), FOREIGN KEY("TrackId") REFERENCES "Track" ("TrackId"), FOREIGN KEY("PlaylistId") REFERENCES "Playlist" ("PlaylistId") ) SELECT * FROM 'PlaylistTrack' LIMIT 3; PlaylistId TrackId 1 3402 1 3389 1 3390 Thought: I can use a SELECT statement to get the total number of tracks in each playlist. Action: query_checker_sql_db Action Input: SELECT Playlist.Name, COUNT(PlaylistTrack.TrackId) AS TotalTracks FROM Playlist INNER JOIN PlaylistTrack ON Playlist.PlaylistId = PlaylistTrack.PlaylistId GROUP BY Playlist.Name Observation: SELECT Playlist.Name, COUNT(PlaylistTrack.TrackId) AS TotalTracks FROM Playlist INNER JOIN PlaylistTrack ON Playlist.PlaylistId = PlaylistTrack.PlaylistId GROUP BY Playlist.Name Thought: The query looks correct,
This notebook showcases an agent designed to interact with a SQL databases.
This notebook showcases an agent designed to interact with a SQL databases. ->: 75.25999999999999), ('Chile', 46.62)] Thought: I now know the final answer Final Answer: The customers from the USA spent the most, with a total of $523.06. > Finished chain. 'The customers from the USA spent the most, with a total of $523.06.'agent_executor.run( "Show the total number of tracks in each playlist. The Playlist name should be included in the result.") > Entering new AgentExecutor chain... Action: list_tables_sql_db Action Input: "" Observation: Invoice, MediaType, Artist, InvoiceLine, Genre, Playlist, Employee, Album, PlaylistTrack, Track, Customer Thought: I should look at the schema of the Playlist and PlaylistTrack tables to see what columns I can use. Action: schema_sql_db Action Input: "Playlist, PlaylistTrack" Observation: CREATE TABLE "Playlist" ( "PlaylistId" INTEGER NOT NULL, "Name" NVARCHAR(120), PRIMARY KEY ("PlaylistId") ) SELECT * FROM 'Playlist' LIMIT 3; PlaylistId Name 1 Music 2 Movies 3 TV Shows CREATE TABLE "PlaylistTrack" ( "PlaylistId" INTEGER NOT NULL, "TrackId" INTEGER NOT NULL, PRIMARY KEY ("PlaylistId", "TrackId"), FOREIGN KEY("TrackId") REFERENCES "Track" ("TrackId"), FOREIGN KEY("PlaylistId") REFERENCES "Playlist" ("PlaylistId") ) SELECT * FROM 'PlaylistTrack' LIMIT 3; PlaylistId TrackId 1 3402 1 3389 1 3390 Thought: I can use a SELECT statement to get the total number of tracks in each playlist. Action: query_checker_sql_db Action Input: SELECT Playlist.Name, COUNT(PlaylistTrack.TrackId) AS TotalTracks FROM Playlist INNER JOIN PlaylistTrack ON Playlist.PlaylistId = PlaylistTrack.PlaylistId GROUP BY Playlist.Name Observation: SELECT Playlist.Name, COUNT(PlaylistTrack.TrackId) AS TotalTracks FROM Playlist INNER JOIN PlaylistTrack ON Playlist.PlaylistId = PlaylistTrack.PlaylistId GROUP BY Playlist.Name Thought: The query looks correct,
2,786
Thought: The query looks correct, I can now execute it. Action: query_sql_db Action Input: SELECT Playlist.Name, COUNT(PlaylistTrack.TrackId) AS TotalTracks FROM Playlist INNER JOIN PlaylistTrack ON Playlist.PlaylistId = PlaylistTrack.PlaylistId GROUP BY Playlist.Name LIMIT 10 Observation: [('90’s Music', 1477), ('Brazilian Music', 39), ('Classical', 75), ('Classical 101 - Deep Cuts', 25), ('Classical 101 - Next Steps', 25), ('Classical 101 - The Basics', 25), ('Grunge', 15), ('Heavy Metal Classic', 26), ('Music', 6580), ('Music Videos', 1)] Thought: I now know the final answer. Final Answer: The total number of tracks in each playlist are: '90’s Music' (1477), 'Brazilian Music' (39), 'Classical' (75), 'Classical 101 - Deep Cuts' (25), 'Classical 101 - Next Steps' (25), 'Classical 101 - The Basics' (25), 'Grunge' (15), 'Heavy Metal Classic' (26), 'Music' (6580), 'Music Videos' (1). > Finished chain. "The total number of tracks in each playlist are: '90’s Music' (1477), 'Brazilian Music' (39), 'Classical' (75), 'Classical 101 - Deep Cuts' (25), 'Classical 101 - Next Steps' (25), 'Classical 101 - The Basics' (25), 'Grunge' (15), 'Heavy Metal Classic' (26), 'Music' (6580), 'Music Videos' (1)."Recovering from an error​In this example, the agent is able to recover from an error after initially trying to access an attribute (Track.ArtistId) which doesn't exist.agent_executor.run("Who are the top 3 best selling artists?") > Entering new AgentExecutor chain... Action: list_tables_sql_db Action Input: "" Observation: MediaType, Track, Invoice, Album, Playlist, Customer, Employee, InvoiceLine, PlaylistTrack, Genre, Artist Thought: I should look at the schema of the Artist, InvoiceLine, and Track tables to see what columns I can use. Action: schema_sql_db Action Input: "Artist, InvoiceLine, Track" Observation: CREATE TABLE "Artist" ( "ArtistId" INTEGER NOT NULL, "Name" NVARCHAR(120),
This notebook showcases an agent designed to interact with a SQL databases.
This notebook showcases an agent designed to interact with a SQL databases. ->: Thought: The query looks correct, I can now execute it. Action: query_sql_db Action Input: SELECT Playlist.Name, COUNT(PlaylistTrack.TrackId) AS TotalTracks FROM Playlist INNER JOIN PlaylistTrack ON Playlist.PlaylistId = PlaylistTrack.PlaylistId GROUP BY Playlist.Name LIMIT 10 Observation: [('90’s Music', 1477), ('Brazilian Music', 39), ('Classical', 75), ('Classical 101 - Deep Cuts', 25), ('Classical 101 - Next Steps', 25), ('Classical 101 - The Basics', 25), ('Grunge', 15), ('Heavy Metal Classic', 26), ('Music', 6580), ('Music Videos', 1)] Thought: I now know the final answer. Final Answer: The total number of tracks in each playlist are: '90’s Music' (1477), 'Brazilian Music' (39), 'Classical' (75), 'Classical 101 - Deep Cuts' (25), 'Classical 101 - Next Steps' (25), 'Classical 101 - The Basics' (25), 'Grunge' (15), 'Heavy Metal Classic' (26), 'Music' (6580), 'Music Videos' (1). > Finished chain. "The total number of tracks in each playlist are: '90’s Music' (1477), 'Brazilian Music' (39), 'Classical' (75), 'Classical 101 - Deep Cuts' (25), 'Classical 101 - Next Steps' (25), 'Classical 101 - The Basics' (25), 'Grunge' (15), 'Heavy Metal Classic' (26), 'Music' (6580), 'Music Videos' (1)."Recovering from an error​In this example, the agent is able to recover from an error after initially trying to access an attribute (Track.ArtistId) which doesn't exist.agent_executor.run("Who are the top 3 best selling artists?") > Entering new AgentExecutor chain... Action: list_tables_sql_db Action Input: "" Observation: MediaType, Track, Invoice, Album, Playlist, Customer, Employee, InvoiceLine, PlaylistTrack, Genre, Artist Thought: I should look at the schema of the Artist, InvoiceLine, and Track tables to see what columns I can use. Action: schema_sql_db Action Input: "Artist, InvoiceLine, Track" Observation: CREATE TABLE "Artist" ( "ArtistId" INTEGER NOT NULL, "Name" NVARCHAR(120),
2,787
NOT NULL, "Name" NVARCHAR(120), PRIMARY KEY ("ArtistId") ) SELECT * FROM 'Artist' LIMIT 3; ArtistId Name 1 AC/DC 2 Accept 3 Aerosmith CREATE TABLE "Track" ( "TrackId" INTEGER NOT NULL, "Name" NVARCHAR(200) NOT NULL, "AlbumId" INTEGER, "MediaTypeId" INTEGER NOT NULL, "GenreId" INTEGER, "Composer" NVARCHAR(220), "Milliseconds" INTEGER NOT NULL, "Bytes" INTEGER, "UnitPrice" NUMERIC(10, 2) NOT NULL, PRIMARY KEY ("TrackId"), FOREIGN KEY("MediaTypeId") REFERENCES "MediaType" ("MediaTypeId"), FOREIGN KEY("GenreId") REFERENCES "Genre" ("GenreId"), FOREIGN KEY("AlbumId") REFERENCES "Album" ("AlbumId") ) SELECT * FROM 'Track' LIMIT 3; TrackId Name AlbumId MediaTypeId GenreId Composer Milliseconds Bytes UnitPrice 1 For Those About To Rock (We Salute You) 1 1 1 Angus Young, Malcolm Young, Brian Johnson 343719 11170334 0.99 2 Balls to the Wall 2 2 1 None 342562 5510424 0.99 3 Fast As a Shark 3 2 1 F. Baltes, S. Kaufman, U. Dirkscneider & W. Hoffman 230619 3990994 0.99 CREATE TABLE "InvoiceLine" ( "InvoiceLineId" INTEGER NOT NULL, "InvoiceId" INTEGER NOT NULL, "TrackId" INTEGER NOT NULL, "UnitPrice" NUMERIC(10, 2) NOT NULL, "Quantity" INTEGER NOT NULL, PRIMARY KEY ("InvoiceLineId"), FOREIGN KEY("TrackId") REFERENCES "Track" ("TrackId"), FOREIGN KEY("InvoiceId") REFERENCES "Invoice" ("InvoiceId") ) SELECT * FROM 'InvoiceLine' LIMIT 3; InvoiceLineId InvoiceId TrackId UnitPrice Quantity 1 1 2 0.99 1 2 1 4 0.99 1 3 2 6 0.99 1 Thought: I should query the database to get the top 3 best selling artists. Action: query_sql_db Action Input: SELECT Artist.Name, SUM(InvoiceLine.Quantity) AS TotalQuantity FROM Artist INNER JOIN Track ON Artist.ArtistId = Track.ArtistId INNER JOIN InvoiceLine ON Track.TrackId =
This notebook showcases an agent designed to interact with a SQL databases.
This notebook showcases an agent designed to interact with a SQL databases. ->: NOT NULL, "Name" NVARCHAR(120), PRIMARY KEY ("ArtistId") ) SELECT * FROM 'Artist' LIMIT 3; ArtistId Name 1 AC/DC 2 Accept 3 Aerosmith CREATE TABLE "Track" ( "TrackId" INTEGER NOT NULL, "Name" NVARCHAR(200) NOT NULL, "AlbumId" INTEGER, "MediaTypeId" INTEGER NOT NULL, "GenreId" INTEGER, "Composer" NVARCHAR(220), "Milliseconds" INTEGER NOT NULL, "Bytes" INTEGER, "UnitPrice" NUMERIC(10, 2) NOT NULL, PRIMARY KEY ("TrackId"), FOREIGN KEY("MediaTypeId") REFERENCES "MediaType" ("MediaTypeId"), FOREIGN KEY("GenreId") REFERENCES "Genre" ("GenreId"), FOREIGN KEY("AlbumId") REFERENCES "Album" ("AlbumId") ) SELECT * FROM 'Track' LIMIT 3; TrackId Name AlbumId MediaTypeId GenreId Composer Milliseconds Bytes UnitPrice 1 For Those About To Rock (We Salute You) 1 1 1 Angus Young, Malcolm Young, Brian Johnson 343719 11170334 0.99 2 Balls to the Wall 2 2 1 None 342562 5510424 0.99 3 Fast As a Shark 3 2 1 F. Baltes, S. Kaufman, U. Dirkscneider & W. Hoffman 230619 3990994 0.99 CREATE TABLE "InvoiceLine" ( "InvoiceLineId" INTEGER NOT NULL, "InvoiceId" INTEGER NOT NULL, "TrackId" INTEGER NOT NULL, "UnitPrice" NUMERIC(10, 2) NOT NULL, "Quantity" INTEGER NOT NULL, PRIMARY KEY ("InvoiceLineId"), FOREIGN KEY("TrackId") REFERENCES "Track" ("TrackId"), FOREIGN KEY("InvoiceId") REFERENCES "Invoice" ("InvoiceId") ) SELECT * FROM 'InvoiceLine' LIMIT 3; InvoiceLineId InvoiceId TrackId UnitPrice Quantity 1 1 2 0.99 1 2 1 4 0.99 1 3 2 6 0.99 1 Thought: I should query the database to get the top 3 best selling artists. Action: query_sql_db Action Input: SELECT Artist.Name, SUM(InvoiceLine.Quantity) AS TotalQuantity FROM Artist INNER JOIN Track ON Artist.ArtistId = Track.ArtistId INNER JOIN InvoiceLine ON Track.TrackId =
2,788
INNER JOIN InvoiceLine ON Track.TrackId = InvoiceLine.TrackId GROUP BY Artist.Name ORDER BY TotalQuantity DESC LIMIT 3 Observation: Error: (sqlite3.OperationalError) no such column: Track.ArtistId [SQL: SELECT Artist.Name, SUM(InvoiceLine.Quantity) AS TotalQuantity FROM Artist INNER JOIN Track ON Artist.ArtistId = Track.ArtistId INNER JOIN InvoiceLine ON Track.TrackId = InvoiceLine.TrackId GROUP BY Artist.Name ORDER BY TotalQuantity DESC LIMIT 3] (Background on this error at: https://sqlalche.me/e/14/e3q8) Thought: I should double check my query before executing it. Action: query_checker_sql_db Action Input: SELECT Artist.Name, SUM(InvoiceLine.Quantity) AS TotalQuantity FROM Artist INNER JOIN Track ON Artist.ArtistId = Track.ArtistId INNER JOIN InvoiceLine ON Track.TrackId = InvoiceLine.TrackId GROUP BY Artist.Name ORDER BY TotalQuantity DESC LIMIT 3 Observation: SELECT Artist.Name, SUM(InvoiceLine.Quantity) AS TotalQuantity FROM Artist INNER JOIN Track ON Artist.ArtistId = Track.ArtistId INNER JOIN InvoiceLine ON Track.TrackId = InvoiceLine.TrackId GROUP BY Artist.Name ORDER BY TotalQuantity DESC LIMIT 3; Thought: I now know the final answer. Action: query_sql_db Action Input: SELECT Artist.Name, SUM(InvoiceLine.Quantity) AS TotalQuantity FROM Artist INNER JOIN Album ON Artist.ArtistId = Album.ArtistId INNER JOIN Track ON Album.AlbumId = Track.AlbumId INNER JOIN InvoiceLine ON Track.TrackId = InvoiceLine.TrackId GROUP BY Artist.Name ORDER BY TotalQuantity DESC LIMIT 3 Observation: [('Iron Maiden', 140), ('U2', 107), ('Metallica', 91)] Thought: I now know the final answer. Final Answer: The top 3 best selling artists are Iron Maiden, U2, and Metallica. > Finished chain. 'The top 3 best selling artists are Iron Maiden, U2, and Metallica.'PreviousSpark SQLNextVectorstoreInitializationUsing ZERO_SHOT_REACT_DESCRIPTIONUsing OpenAI FunctionsDisclaimer ⚠️Example: describing a
This notebook showcases an agent designed to interact with a SQL databases.
This notebook showcases an agent designed to interact with a SQL databases. ->: INNER JOIN InvoiceLine ON Track.TrackId = InvoiceLine.TrackId GROUP BY Artist.Name ORDER BY TotalQuantity DESC LIMIT 3 Observation: Error: (sqlite3.OperationalError) no such column: Track.ArtistId [SQL: SELECT Artist.Name, SUM(InvoiceLine.Quantity) AS TotalQuantity FROM Artist INNER JOIN Track ON Artist.ArtistId = Track.ArtistId INNER JOIN InvoiceLine ON Track.TrackId = InvoiceLine.TrackId GROUP BY Artist.Name ORDER BY TotalQuantity DESC LIMIT 3] (Background on this error at: https://sqlalche.me/e/14/e3q8) Thought: I should double check my query before executing it. Action: query_checker_sql_db Action Input: SELECT Artist.Name, SUM(InvoiceLine.Quantity) AS TotalQuantity FROM Artist INNER JOIN Track ON Artist.ArtistId = Track.ArtistId INNER JOIN InvoiceLine ON Track.TrackId = InvoiceLine.TrackId GROUP BY Artist.Name ORDER BY TotalQuantity DESC LIMIT 3 Observation: SELECT Artist.Name, SUM(InvoiceLine.Quantity) AS TotalQuantity FROM Artist INNER JOIN Track ON Artist.ArtistId = Track.ArtistId INNER JOIN InvoiceLine ON Track.TrackId = InvoiceLine.TrackId GROUP BY Artist.Name ORDER BY TotalQuantity DESC LIMIT 3; Thought: I now know the final answer. Action: query_sql_db Action Input: SELECT Artist.Name, SUM(InvoiceLine.Quantity) AS TotalQuantity FROM Artist INNER JOIN Album ON Artist.ArtistId = Album.ArtistId INNER JOIN Track ON Album.AlbumId = Track.AlbumId INNER JOIN InvoiceLine ON Track.TrackId = InvoiceLine.TrackId GROUP BY Artist.Name ORDER BY TotalQuantity DESC LIMIT 3 Observation: [('Iron Maiden', 140), ('U2', 107), ('Metallica', 91)] Thought: I now know the final answer. Final Answer: The top 3 best selling artists are Iron Maiden, U2, and Metallica. > Finished chain. 'The top 3 best selling artists are Iron Maiden, U2, and Metallica.'PreviousSpark SQLNextVectorstoreInitializationUsing ZERO_SHOT_REACT_DESCRIPTIONUsing OpenAI FunctionsDisclaimer ⚠️Example: describing a
2,789
FunctionsDisclaimer ⚠️Example: describing a tableExample: describing a table, recovering from an errorExample: running queriesRecovering from an errorCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
This notebook showcases an agent designed to interact with a SQL databases.
This notebook showcases an agent designed to interact with a SQL databases. ->: FunctionsDisclaimer ⚠️Example: describing a tableExample: describing a table, recovering from an errorExample: running queriesRecovering from an errorCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
2,790
Office365 | 🦜️🔗 Langchain
This notebook walks through connecting LangChain to Office365 email and calendar.
This notebook walks through connecting LangChain to Office365 email and calendar. ->: Office365 | 🦜️🔗 Langchain
2,791
Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKProvidersAnthropicAWSGoogleMicrosoftOpenAIMoreComponentsLLMsChat modelsDocument loadersDocument transformersText embedding modelsVector storesRetrieversToolsAgents and toolkitsAINetworkAirbyte Question AnsweringAmadeusAzure Cognitive ServicesClickUp Langchain ToolkitCSVDocument ComparisonGithubGitlabGmailGoogle Drive toolJiraJSONMultiOnOffice365OpenAPINatural Language APIsPandas DataframePlayWright BrowserPowerBI DatasetPythonSpark DataframeSpark SQLSQL DatabaseVectorstoreXorbitsMemoryCallbacksChat loadersComponentsAgents and toolkitsOffice365On this pageOffice365This notebook walks through connecting LangChain to Office365 email and calendar.To use this toolkit, you will need to set up your credentials explained in the Microsoft Graph authentication and authorization overview. Once you've received a CLIENT_ID and CLIENT_SECRET, you can input them as environmental variables below.pip install --upgrade O365 > /dev/nullpip install beautifulsoup4 > /dev/null # This is optional but is useful for parsing HTML messagesAssign Environmental Variables​The toolkit will read the CLIENT_ID and 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 hereCreate the Toolkit and Get Tools​To start, you need to create the toolkit, so you can access its tools later.from langchain.agents.agent_toolkits import O365Toolkittoolkit = O365Toolkit()tools = toolkit.get_tools()tools [O365SearchEvents(name='events_search', description=" Use this tool to search for the user's calendar events. The input must be the start and end datetimes for the search query. The output is a JSON list of all the events in the user's calendar between the start and end times. You can assume that the user can not schedule any meeting over existing
This notebook walks through connecting LangChain to Office365 email and calendar.
This notebook walks through connecting LangChain to Office365 email and calendar. ->: Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKProvidersAnthropicAWSGoogleMicrosoftOpenAIMoreComponentsLLMsChat modelsDocument loadersDocument transformersText embedding modelsVector storesRetrieversToolsAgents and toolkitsAINetworkAirbyte Question AnsweringAmadeusAzure Cognitive ServicesClickUp Langchain ToolkitCSVDocument ComparisonGithubGitlabGmailGoogle Drive toolJiraJSONMultiOnOffice365OpenAPINatural Language APIsPandas DataframePlayWright BrowserPowerBI DatasetPythonSpark DataframeSpark SQLSQL DatabaseVectorstoreXorbitsMemoryCallbacksChat loadersComponentsAgents and toolkitsOffice365On this pageOffice365This notebook walks through connecting LangChain to Office365 email and calendar.To use this toolkit, you will need to set up your credentials explained in the Microsoft Graph authentication and authorization overview. Once you've received a CLIENT_ID and CLIENT_SECRET, you can input them as environmental variables below.pip install --upgrade O365 > /dev/nullpip install beautifulsoup4 > /dev/null # This is optional but is useful for parsing HTML messagesAssign Environmental Variables​The toolkit will read the CLIENT_ID and 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 hereCreate the Toolkit and Get Tools​To start, you need to create the toolkit, so you can access its tools later.from langchain.agents.agent_toolkits import O365Toolkittoolkit = O365Toolkit()tools = toolkit.get_tools()tools [O365SearchEvents(name='events_search', description=" Use this tool to search for the user's calendar events. The input must be the start and end datetimes for the search query. The output is a JSON list of all the events in the user's calendar between the start and end times. You can assume that the user can not schedule any meeting over existing
2,792
user can not schedule any meeting over existing meetings, and that the user is busy during meetings. Any times without events are free for the user. ", args_schema=<class 'langchain.tools.office365.events_search.SearchEventsInput'>, return_direct=False, verbose=False, callbacks=None, callback_manager=None, handle_tool_error=False, account=Account Client Id: f32a022c-3c4c-4d10-a9d8-f6a9a9055302), O365CreateDraftMessage(name='create_email_draft', description='Use this tool to create a draft email with the provided message fields.', args_schema=<class 'langchain.tools.office365.create_draft_message.CreateDraftMessageSchema'>, return_direct=False, verbose=False, callbacks=None, callback_manager=None, handle_tool_error=False, account=Account Client Id: f32a022c-3c4c-4d10-a9d8-f6a9a9055302), O365SearchEmails(name='messages_search', description='Use this tool to search for email messages. The input must be a valid Microsoft Graph v1.0 $search query. The output is a JSON list of the requested resource.', args_schema=<class 'langchain.tools.office365.messages_search.SearchEmailsInput'>, return_direct=False, verbose=False, callbacks=None, callback_manager=None, handle_tool_error=False, account=Account Client Id: f32a022c-3c4c-4d10-a9d8-f6a9a9055302), O365SendEvent(name='send_event', description='Use this tool to create and send an event with the provided event fields.', args_schema=<class 'langchain.tools.office365.send_event.SendEventSchema'>, return_direct=False, verbose=False, callbacks=None, callback_manager=None, handle_tool_error=False, account=Account Client Id: f32a022c-3c4c-4d10-a9d8-f6a9a9055302), O365SendMessage(name='send_email', description='Use this tool to send an email with the provided message fields.', args_schema=<class 'langchain.tools.office365.send_message.SendMessageSchema'>, return_direct=False, verbose=False, callbacks=None, callback_manager=None, handle_tool_error=False, account=Account Client Id:
This notebook walks through connecting LangChain to Office365 email and calendar.
This notebook walks through connecting LangChain to Office365 email and calendar. ->: user can not schedule any meeting over existing meetings, and that the user is busy during meetings. Any times without events are free for the user. ", args_schema=<class 'langchain.tools.office365.events_search.SearchEventsInput'>, return_direct=False, verbose=False, callbacks=None, callback_manager=None, handle_tool_error=False, account=Account Client Id: f32a022c-3c4c-4d10-a9d8-f6a9a9055302), O365CreateDraftMessage(name='create_email_draft', description='Use this tool to create a draft email with the provided message fields.', args_schema=<class 'langchain.tools.office365.create_draft_message.CreateDraftMessageSchema'>, return_direct=False, verbose=False, callbacks=None, callback_manager=None, handle_tool_error=False, account=Account Client Id: f32a022c-3c4c-4d10-a9d8-f6a9a9055302), O365SearchEmails(name='messages_search', description='Use this tool to search for email messages. The input must be a valid Microsoft Graph v1.0 $search query. The output is a JSON list of the requested resource.', args_schema=<class 'langchain.tools.office365.messages_search.SearchEmailsInput'>, return_direct=False, verbose=False, callbacks=None, callback_manager=None, handle_tool_error=False, account=Account Client Id: f32a022c-3c4c-4d10-a9d8-f6a9a9055302), O365SendEvent(name='send_event', description='Use this tool to create and send an event with the provided event fields.', args_schema=<class 'langchain.tools.office365.send_event.SendEventSchema'>, return_direct=False, verbose=False, callbacks=None, callback_manager=None, handle_tool_error=False, account=Account Client Id: f32a022c-3c4c-4d10-a9d8-f6a9a9055302), O365SendMessage(name='send_email', description='Use this tool to send an email with the provided message fields.', args_schema=<class 'langchain.tools.office365.send_message.SendMessageSchema'>, return_direct=False, verbose=False, callbacks=None, callback_manager=None, handle_tool_error=False, account=Account Client Id:
2,793
account=Account Client Id: f32a022c-3c4c-4d10-a9d8-f6a9a9055302)]Use within an Agent‚Äãfrom langchain.llms import OpenAIfrom langchain.agents import initialize_agent, AgentTypellm = OpenAI(temperature=0)agent = initialize_agent( tools=toolkit.get_tools(), llm=llm, verbose=False, agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION,)agent.run( "Create an email 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.") 'The draft email was created correctly.'agent.run( "Could you search in my drafts folder and let me know if any of them are about collaboration?") "I found one draft in your drafts folder about collaboration. It was sent on 2023-06-16T18:22:17+0000 and the subject was 'Collaboration Request'."agent.run( "Can you schedule a 30 minute meeting with a sentient parrot to discuss research collaborations on October 3, 2023 at 2 pm Easter Time?") /home/vscode/langchain-py-env/lib/python3.11/site-packages/O365/utils/windows_tz.py:639: PytzUsageWarning: The zone attribute is specific to pytz's interface; please migrate to a new time zone provider. For more details on how to do so, see https://pytz-deprecation-shim.readthedocs.io/en/latest/migration.html iana_tz.zone if isinstance(iana_tz, tzinfo) else iana_tz) /home/vscode/langchain-py-env/lib/python3.11/site-packages/O365/utils/utils.py:463: PytzUsageWarning: The zone attribute is specific to pytz's interface; please migrate to a new time zone provider. For more details on how to do so, see https://pytz-deprecation-shim.readthedocs.io/en/latest/migration.html timezone = date_time.tzinfo.zone if date_time.tzinfo is not None else None 'I have scheduled a meeting with a sentient parrot to discuss research collaborations on October 3, 2023 at 2 pm Easter Time. Please let me know if you need to
This notebook walks through connecting LangChain to Office365 email and calendar.
This notebook walks through connecting LangChain to Office365 email and calendar. ->: account=Account Client Id: f32a022c-3c4c-4d10-a9d8-f6a9a9055302)]Use within an Agent‚Äãfrom langchain.llms import OpenAIfrom langchain.agents import initialize_agent, AgentTypellm = OpenAI(temperature=0)agent = initialize_agent( tools=toolkit.get_tools(), llm=llm, verbose=False, agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION,)agent.run( "Create an email 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.") 'The draft email was created correctly.'agent.run( "Could you search in my drafts folder and let me know if any of them are about collaboration?") "I found one draft in your drafts folder about collaboration. It was sent on 2023-06-16T18:22:17+0000 and the subject was 'Collaboration Request'."agent.run( "Can you schedule a 30 minute meeting with a sentient parrot to discuss research collaborations on October 3, 2023 at 2 pm Easter Time?") /home/vscode/langchain-py-env/lib/python3.11/site-packages/O365/utils/windows_tz.py:639: PytzUsageWarning: The zone attribute is specific to pytz's interface; please migrate to a new time zone provider. For more details on how to do so, see https://pytz-deprecation-shim.readthedocs.io/en/latest/migration.html iana_tz.zone if isinstance(iana_tz, tzinfo) else iana_tz) /home/vscode/langchain-py-env/lib/python3.11/site-packages/O365/utils/utils.py:463: PytzUsageWarning: The zone attribute is specific to pytz's interface; please migrate to a new time zone provider. For more details on how to do so, see https://pytz-deprecation-shim.readthedocs.io/en/latest/migration.html timezone = date_time.tzinfo.zone if date_time.tzinfo is not None else None 'I have scheduled a meeting with a sentient parrot to discuss research collaborations on October 3, 2023 at 2 pm Easter Time. Please let me know if you need to
2,794
pm Easter Time. Please let me know if you need to make any changes.'agent.run( "Can you tell me if I have any events on October 3, 2023 in Eastern Time, and if so, tell me if any of them are with a sentient parrot?") "Yes, you have an event on October 3, 2023 with a sentient parrot. The event is titled 'Meeting with sentient parrot' and is scheduled from 6:00 PM to 6:30 PM."PreviousMultiOnNextOpenAPIAssign Environmental VariablesCreate the Toolkit and Get ToolsUse within an AgentCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
This notebook walks through connecting LangChain to Office365 email and calendar.
This notebook walks through connecting LangChain to Office365 email and calendar. ->: pm Easter Time. Please let me know if you need to make any changes.'agent.run( "Can you tell me if I have any events on October 3, 2023 in Eastern Time, and if so, tell me if any of them are with a sentient parrot?") "Yes, you have an event on October 3, 2023 with a sentient parrot. The event is titled 'Meeting with sentient parrot' and is scheduled from 6:00 PM to 6:30 PM."PreviousMultiOnNextOpenAPIAssign Environmental VariablesCreate the Toolkit and Get ToolsUse within an AgentCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
2,795
Spark SQL | 🦜️🔗 Langchain
This notebook shows how to use agents to interact with Spark SQL. Similar to SQL Database Agent, it is designed to address general inquiries about Spark SQL and facilitate error recovery.
This notebook shows how to use agents to interact with Spark SQL. Similar to SQL Database Agent, it is designed to address general inquiries about Spark SQL and facilitate error recovery. ->: Spark SQL | 🦜️🔗 Langchain
2,796
Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKProvidersAnthropicAWSGoogleMicrosoftOpenAIMoreComponentsLLMsChat modelsDocument loadersDocument transformersText embedding modelsVector storesRetrieversToolsAgents and toolkitsAINetworkAirbyte Question AnsweringAmadeusAzure Cognitive ServicesClickUp Langchain ToolkitCSVDocument ComparisonGithubGitlabGmailGoogle Drive toolJiraJSONMultiOnOffice365OpenAPINatural Language APIsPandas DataframePlayWright BrowserPowerBI DatasetPythonSpark DataframeSpark SQLSQL DatabaseVectorstoreXorbitsMemoryCallbacksChat loadersComponentsAgents and toolkitsSpark SQLOn this pageSpark SQLThis notebook shows how to use agents to interact with 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). 23/05/18 16:03:10 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
This notebook shows how to use agents to interact with Spark SQL. Similar to SQL Database Agent, it is designed to address general inquiries about Spark SQL and facilitate error recovery.
This notebook shows how to use agents to interact with Spark SQL. Similar to SQL Database Agent, it is designed to address general inquiries about Spark SQL and facilitate error recovery. ->: Skip to main content🦜️🔗 LangChainDocsUse casesIntegrationsAPICommunityChat our docsLangSmithJS/TS DocsSearchCTRLKProvidersAnthropicAWSGoogleMicrosoftOpenAIMoreComponentsLLMsChat modelsDocument loadersDocument transformersText embedding modelsVector storesRetrieversToolsAgents and toolkitsAINetworkAirbyte Question AnsweringAmadeusAzure Cognitive ServicesClickUp Langchain ToolkitCSVDocument ComparisonGithubGitlabGmailGoogle Drive toolJiraJSONMultiOnOffice365OpenAPINatural Language APIsPandas DataframePlayWright BrowserPowerBI DatasetPythonSpark DataframeSpark SQLSQL DatabaseVectorstoreXorbitsMemoryCallbacksChat loadersComponentsAgents and toolkitsSpark SQLOn this pageSpark SQLThis notebook shows how to use agents to interact with 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). 23/05/18 16:03:10 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
2,797
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| 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| 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| 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|
This notebook shows how to use agents to interact with Spark SQL. Similar to SQL Database Agent, it is designed to address general inquiries about Spark SQL and facilitate error recovery.
This notebook shows how to use agents to interact with Spark SQL. Similar to SQL Database Agent, it is designed to address general inquiries about Spark SQL and facilitate error recovery. ->: 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| 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| 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| 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|
2,798
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| 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| +-----------+--------+------+--------------------+------+----+-----+-----+----------------+-------+-----+--------+ 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 Pclass
This notebook shows how to use agents to interact with Spark SQL. Similar to SQL Database Agent, it is designed to address general inquiries about Spark SQL and facilitate error recovery.
This notebook shows how to use agents to interact with Spark SQL. Similar to SQL Database Agent, it is designed to address general inquiries about Spark SQL and facilitate error recovery. ->: 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| 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| +-----------+--------+------+--------------------+------+----+-----+-----+----------------+-------+-----+--------+ 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 Pclass
2,799
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: 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, Survived: 1, Pclass: 1, Name: Cumings, Mrs. John Bradley (Florence Briggs Thayer), Sex: female, Age: 38.0, SibSp: 1, Parch: 0,
This notebook shows how to use agents to interact with Spark SQL. Similar to SQL Database Agent, it is designed to address general inquiries about Spark SQL and facilitate error recovery.
This notebook shows how to use agents to interact with Spark SQL. Similar to SQL Database Agent, it is designed to address general inquiries about Spark SQL and facilitate error recovery. ->: 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: 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, Survived: 1, Pclass: 1, Name: Cumings, Mrs. John Bradley (Florence Briggs Thayer), Sex: female, Age: 38.0, SibSp: 1, Parch: 0,