Salesforce
This notebook shows how to use the Salesforce tools in LangChain.
The Salesforce integration provides tools for:
- Querying Salesforce data using SOQL
- Getting information about Salesforce objects
- Listing available Salesforce objects
Installationโ
First, you need to install the simple-salesforce
package:
pip install simple-salesforce
from simple_salesforce import Salesforce
from langchain_community.tools.salesforce import (
QuerySalesforceTool,
InfoSalesforceTool,
ListSalesforceTool
)
Setupโ
You can initialize the Salesforce tools in two ways:
- Using direct credentials
- Using an existing Salesforce instance
Option 1: Using Direct Credentialsโ
# Initialize Salesforce with credentials
sf = Salesforce(
username='your_username',
password='your_password',
security_token='your_token',
domain='test' # Use 'test' for sandbox, remove for production
)
# Create tools
tools = [
QuerySalesforceTool(sfdc_instance=sf),
InfoSalesforceTool(sfdc_instance=sf),
ListSalesforceTool(sfdc_instance=sf)
]
Using the Toolsโ
1. List Available Objectsโ
# List all queryable objects in your Salesforce instance
result = list_tool.run("")
print(result)
2. Get Object Informationโ
# Get information about specific objects
result = info_tool.run("Account,Contact")
print(result)
3. Query Salesforce Dataโ
# Execute a SOQL query
query = "SELECT Id, Name, Industry FROM Account LIMIT 5"
result = query_tool.run(query)
print(result)
Using with an Agentโ
The Salesforce tools can be used with LangChain agents to enable natural language interactions with your Salesforce data:
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from langchain.agents import create_openai_functions_agent
from langchain.agents import AgentExecutor
# Initialize the language model
llm = ChatOpenAI(temperature=0)
# Create a prompt template
prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant that can query Salesforce data. "
"Use the available tools to help answer questions about Salesforce data."),
("user", "{input}")
])
# Create the agent
agent = create_openai_functions_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
# Example: Ask the agent to get information about accounts
result = agent_executor.invoke(
{"input": "What are the top 5 accounts by revenue?"}
)
print(result["output"])
Error Handlingโ
The tools are designed to handle errors gracefully:
# Example: Invalid SOQL query
result = query_tool.run("SELECT Invalid FROM Account")
print(result)
# Example: Invalid object name
result = info_tool.run("InvalidObject")
print(result)
Relatedโ
- Tool conceptual guide
- Tool how-to guides