Build Powerful AI Workflows: Together AI + Klavis for Salesforce & Gmail Integration

ยท8 min read

Cover Image for Build Powerful AI Workflows: Together AI + Klavis for Salesforce & Gmail Integration

Imagine automating your entire sales follow-up process with AI: finding opportunities in Salesforce, updating next steps, and drafting personalized emails in Gmailโ€”all with a single command. This tutorial shows you exactly how to build this powerful workflow using Together AI's advanced language models and Klavis AI's Model Context Protocol (MCP) servers.

Watch the Demo

See this powerful integration in action:

Prerequisites

Before diving in, you'll need:

  • Together AI API key - Get yours at together.ai
  • Klavis AI API key - Get yours at klavis.ai
  • Access to Salesforce and Gmail accounts

Step 1: Installation and Setup

Start by installing the required packages:

pip install together klavis

Then set up your environment with the necessary API keys:

import os
import json
import webbrowser
from together import Together
from klavis import Klavis
from klavis.types import McpServerName, ToolFormat

# Set your API keys
os.environ["TOGETHER_API_KEY"] = "YOUR_TOGETHER_API_KEY"
os.environ["KLAVIS_API_KEY"] = "YOUR_KLAVIS_API_KEY"

# Initialize clients
together_client = Together(api_key=os.getenv("TOGETHER_API_KEY"))
klavis_client = Klavis(api_key=os.getenv("KLAVIS_API_KEY"))

Step 2: Create MCP Server Instances

Klavis makes it incredibly easy to connect to external services through MCP servers. Let's set up both Salesforce and Gmail:

Salesforce Integration

# Create Salesforce MCP Server instance
salesforce_mcp_instance = klavis_client.mcp_server.create_server_instance(
    server_name=McpServerName.SALESFORCE,
    user_id="1234", 
    platform_name="TogetherAI" 
)

# Open OAuth URL for Salesforce authorization
webbrowser.open(salesforce_mcp_instance.oauth_url)
print(f"๐Ÿ” Opening OAuth authorization for Salesforce...")

Gmail Integration

# Create Gmail MCP Server instance
gmail_mcp_instance = klavis_client.mcp_server.create_server_instance(
    server_name=McpServerName.GMAIL,
    user_id="1234",
    platform_name="TogetherAI"
)

# Open OAuth URL for Gmail authorization
webbrowser.open(gmail_mcp_instance.oauth_url)
print(f"๐Ÿ” Opening OAuth authorization for Gmail...")

Step 3: Build the Intelligent Workflow

Now comes the exciting partโ€”creating a workflow class that can intelligently coordinate between multiple services:

class Workflow:
    def __init__(self, together_client, klavis_client, mcp_server_urls, model="meta-llama/Llama-3.3-70B-Instruct-Turbo"):
        self.together = together_client
        self.klavis = klavis_client
        self.mcp_server_urls = mcp_server_urls
        self.model = model
    
    def process_request(self, user_message):
        # 1. Get available tools from all MCP servers
        all_tools = []
        tool_to_server = {}  # Maps tool names to their server URLs
        
        for server_url in self.mcp_server_urls:
            mcp_tools = self.klavis.mcp_server.list_tools(
                server_url=server_url,
                format=ToolFormat.OPENAI,
            )
            all_tools.extend(mcp_tools.tools)
            
            for tool in mcp_tools.tools:
                tool_to_server[tool["function"]["name"]] = server_url
        
        # 2. Initialize conversation with the AI
        messages = [
            {"role": "system", "content": "You are a helpful AI assistant with access to tools. Complete requested tasks step by step with the tools available. When all tasks are completed, end your response with 'Done'."},
            {"role": "user", "content": user_message}
        ]
        
        max_iterations = 10 
        iteration = 0
        
        # 3. Execute the workflow
        while iteration < max_iterations:
            iteration += 1
            
            # Call Together AI with all available tools
            response = self.together.chat.completions.create(
                model=self.model,
                messages=messages,
                tools=all_tools
            )
            
            assistant_message = response.choices[0].message
            messages.append(assistant_message)
                        
            # Handle tool calls
            if assistant_message.tool_calls:
                for tool_call in assistant_message.tool_calls:
                    tool_name = tool_call.function.name
                    tool_args = json.loads(tool_call.function.arguments)
                    
                    print(f"๐Ÿ› ๏ธ Calling tool: {tool_name} with args: {tool_args}")
                    
                    # Execute the tool on the correct server
                    if tool_name in tool_to_server:
                        server_url = tool_to_server[tool_name]
                        
                        try:
                            tool_result = self.klavis.mcp_server.call_tools(
                                server_url=server_url,
                                tool_name=tool_name,
                                tool_args=tool_args,
                            )
                            print(f"โœ… Tool {tool_name} executed successfully")
                        except Exception as e:
                            tool_result = f"Error executing tool {tool_name}: {str(e)}"
                            print(f"โŒ Tool {tool_name} failed: {str(e)}")
                    
                    messages.append({
                        "role": "tool",
                        "tool_call_id": tool_call.id,
                        "content": str(tool_result)
                    })
                
                continue
            
            else:
                # Check if task is complete
                content = assistant_message.content or ""
                if "done" in content.lower():
                    print(f"โœ… Task completed in {iteration} iterations")
                    return assistant_message.content
        
        return assistant_message.content

Step 4: Execute Your AI Workflow

Now let's put it all together and execute a complex, multi-step workflow:

# Create the workflow instance
workflow = Workflow(
    together_client=together_client,
    klavis_client=klavis_client,
    mcp_server_urls=[salesforce_mcp_instance.server_url, gmail_mcp_instance.server_url],
    model="meta-llama/Llama-3.3-70B-Instruct-Turbo"
)

# Execute a complex multi-step request
response = workflow.process_request("""
    1. List my Salesforce opportunities
    2. Update the Together AI opportunity's next step to "Meeting scheduled for 07/31/2025"
    3. Draft a professional follow-up email in Gmail for this next step
""")

print(response)

Expected Output:

๐Ÿ› ๏ธ Calling tool: salesforce_get_opportunities with args: {'fields': [], 'limit': 50}
โœ… Tool salesforce_get_opportunities executed successfully
๐Ÿ› ๏ธ Calling tool: salesforce_update_opportunity with args: {'next_step': 'Meeting schedule on 07/31/2025', 'opportunity_id': '006fJ0000080dpaQAA'}
โœ… Tool salesforce_update_opportunity executed successfully
๐Ÿ› ๏ธ Calling tool: gmail_draft_email with args: {'body': 'Next step: Meeting schedule on 07/31/2025', 'subject': 'Follow-up on Together AI Opportunity', 'to': ['together.ai@example.com']}
โœ… Tool gmail_draft_email executed successfully
โœ… Task completed in 6 iterations

A follow-up email for the next step has been drafted in your Gmail account with the subject "Follow-up on Together AI Opportunity" and the body "Next step: Meeting schedule on 07/31/2025".

Done

Conclusion

The combination of Together AI's powerful language models and Klavis AI's production-ready MCP servers creates unprecedented opportunities for intelligent workflow automation. What once required teams of developers and months of integration work can now be built in an afternoon.

This is just the beginning. As more MCP servers become available and language models continue to improve, the possibilities for intelligent automation are virtually limitless.

Ready to transform your workflows? Start building with Together AI and Klavis AI today!