Automate Customer Support with Freshchat and ChatGPT Integration

Pawan TPawan T
12 min read

Introduction

Freshchat is a customer engagement solution that enables businesses to interact with their customers seamlessly. It offers a range of features to enhance communication, support, and marketing efforts. The platform is particularly known for its live chat capabilities, allowing businesses to engage with website visitors and app users in real time.

The Freshchat API is a set of rules and tools that allows developers to programmatically interact with Freshchat's messaging platform. This API enables businesses to integrate Freshchat functionality into their own applications, websites, or systems, providing a way to automate processes, extract data, and extend the capabilities of Freshchat.

ChatGPT, powered by OpenAI's language model, introduces an intelligent layer to Freshchat interactions. By leveraging OpenAI's powerful language model ChatGPT, alongside the capabilities of Freshchat, businesses can provide intelligent and automated responses to user inquiries. Importantly, this automation allows for efficient communication without the need for a human agent, contributing to quicker response times and 24/7 availability. This integration holds immense potential for improving the overall efficiency, responsiveness, and personalization of customer communication processes.

Prerequisites

Obtaining a Freshchat API Key and Freshchat URL:

To interact with the Freshchat API, acquiring an Freshchat API key and Freshchat URL is a fundamental step .

  1. Log in to Freshchat :

    Accessing a Freshchat account involves credentials to login. If we don't have a Freshchat account, we can sign up for a free trial on the Freshchat website and activate a account through a verification email, and then log in to Freshchat using email address and password or google account.

  2. After Login to Freshchat account obtain Freshchat API Key and Freshchat URL :

Setting up the development environment:

Once we obtained Freshchat API key and Freshchat URL, the next step is to set up development environment.

  1. Access to a Python Environment: Make sure to set up a Python environment on a machine.

  2. Install Required Libraries: Ensure that we have the required libraries installed, with a primary emphasis on using the 'requests' library for handling HTTP requests in Python. I can install it using:

       pip install requests
    
  3. Freshchat API Documentation:

    • Get to know the Freshchat API documentation to understand the available endpoints, request/response formats, and any specific requirements.

Freshchat API Operations

For Performing Freshchat API Operations mainly we need to provide FRESHCHAT_API_KEY and FRESHCHAT_API_URL for the code snippet.

import requests

FRESHCHAT_API_KEY = 'Your Freshchat API Key'
FRESHCHAT_API_URL = f'Your Freshchat URL'

Freshchat User Operations :

  1. Creating a Freshchat User

    The create_freshchat_user function creates the user in Freshchat. that allows businesses to manage and engage with their customer base efficiently.

     def create_freshchat_user(FRESHCHAT_API_KEY, FRESHCHAT_API_URL, user_payload):
         endpoint = 'users'
    
         # Construct the complete URL for the API request
         url = FRESHCHAT_API_URL + endpoint
    
         # Set up headers with authorization and accept content type
         headers = {
             'Authorization': f'Bearer {FRESHCHAT_API_KEY}',
             'Content-Type': 'application/json'
         }
    
         try:
             # Make a POST request to the Freshchat API
             response = requests.post(url, headers=headers, json=user_payload)
             response.raise_for_status()
             return {"data": response.json(), "response_text": response.text}
         except requests.RequestException as e:
             return {"error": f"Error accessing Freshchat API: {str(e)}", "response_text": response.text}
    
     # Example user payload
     user_payload = {
         "email": "william.jack@email.com",
         "first_name": "william",
         "last_name": "jack",
         "phone": "9873783842",
     }
    
     # Creating a Freshchat user
     result = create_freshchat_user(FRESHCHAT_API_KEY, FRESHCHAT_API_URL, user_payload)
    
     # Checking for errors and displaying the result
     if 'error' in result:
         print(f"Error: {result['error']}")
     else:
         print("User created successfully.")
         print("Result:", result['data'])
    

    create_freshchat_user function takes the Freshchat API key, API URL, and user payload as parameters, and it sends a POST request to the Freshchat API to create a new user.

  2. Retrieving Freshchat User Details

    The get_freshchat_user function facilitates the retrieval of user information based on a user ID, providing businesses with a streamlined approach to user management.

     def get_freshchat_user(FRESHCHAT_API_KEY, FRESHCHAT_API_URL, user_id):
         endpoint = f'users/{user_id}'
    
         # Construct the complete URL for the API request
         url = FRESHCHAT_API_URL + endpoint
    
         # Set up headers with authorization and accept content type
         headers = {
             'Authorization': f'Bearer {FRESHCHAT_API_KEY}',
             'Content-Type': 'application/json',
         }
    
         try:
             # Make a GET request to the Freshchat API
             response = requests.get(url, headers=headers)
    
             if response.status_code == 200:
                 return response.json()
             else:
                 print(f"Error: {response.status_code}\n{response.text}")
                 return None
    
         except requests.RequestException as e:
             print(f"Error accessing Freshchat API: {str(e)}")
             return None
    
     # Example user ID to retrieve
     user_id_to_retrieve = '1f3ead9d-9e1c-4b28-9075-14dbe45e1eda'
    
     # Retrieving Freshchat user details
     user_details = get_freshchat_user(FRESHCHAT_API_KEY, FRESHCHAT_API_URL, user_id_to_retrieve)
    
     # Checking for successful retrieval and displaying user details
     if user_details:
         print("User details retrieved successfully.")
         print("User Details:", user_details)
    

    the get_freshchat_user function takes the Freshchat API key, API URL, and a specific user ID as parameters. It sends a GET request to the Freshchat API to retrieve user details.

Freshchat Channel Operation :

  1. Listing Freshchat Channels

    The get_freshchat_channels function allows businesses to fetch information about the available channels within their Freshchat instance.

     def get_freshchat_channels(FRESHCHAT_API_KEY, FRESHCHAT_API_URL):
         endpoint = 'channels'
    
         # Construct the complete URL for the API request
         url = FRESHCHAT_API_URL + endpoint
    
         # Set up headers with authorization and accept content type
         headers = {
             'Authorization': f'Bearer {FRESHCHAT_API_KEY}',
             'Accept': 'application/json',
         }
    
         # Define parameters for the API request, such as pagination and sorting
         params = {
             'page': 1,
             'items_per_page': 10,
             'sort_order': 'asc',
             'sort_by': 'name'
         }
    
         try:
             # Make a GET request to the Freshchat API
             response = requests.get(url, headers=headers, params=params)
             response.raise_for_status()
    
             return response.json()
    
         except requests.RequestException as e:
             print(f"Error accessing Freshchat API: {str(e)}")
             return None
    
     # Call the function with Freshchat API key and API URL to get the list of channels
     channels_result = get_freshchat_channels(FRESHCHAT_API_KEY, FRESHCHAT_API_URL)
    
     if channels_result:
         print("Result:", channels_result)
    

    The get_freshchat_channels function constructs a GET request to the Freshchat API, specifically targeting the 'channels' endpoint. The request includes the provided FRESHCHAT_API_KEY key for authentication and is enhanced with parameters such as page number, items per page, and sorting criteria to customize the result set.

    Upon execution, the script calls the function with the Freshchat API key and API URL and retrieves the list of channels.

Freshchat Conversation Operations :

  1. Creating a Freshchat Conversation

    The create_freshchat_conversation function facilitates this process, enabling businesses to automate the creation of conversations with users.

     def create_freshchat_conversation(FRESHCHAT_API_KEY, FRESHCHAT_API_URL):
         endpoint = 'conversations'
         url = FRESHCHAT_API_URL + endpoint
    
         headers = {
             'Authorization': f'Bearer {FRESHCHAT_API_KEY}',
             'Content-Type': 'application/json',
         }
    
         conversation_payload = {
             "Status": "new",
             "messages": [
                 {
                     "message_parts": [
                         {
                             "text": {
                                 "content": "Hello, can you give my order details for my order id 12 and email id is william.jack@email.com"
                             }
                         }
                     ],
                     "channel_id": "198bbfc7-5619-43b6-9c7d-f47758134af4",
                     "message_type": "normal",
                     "actor_type": "user",
                     "actor_id": "1f3ead9d-9e1c-4b28-9075-14dbe45e1eda"
                 }
             ],
             "channel_id": "198bbfc7-5619-43b6-9c7d-f47758134af4",
             "properties": {
                 "priority": "Low",
                 "cf_type": "General Query",
                 "cf_rating": "3",
                 "cf_supported_products": ["Freshchat", "Freshdesk"]
             },
             "users": [
                 {
                     "id": "1f3ead9d-9e1c-4b28-9075-14dbe45e1eda"
                 }
             ]
         }
    
         try:
             # Make a POST request to the Freshchat API
             response = requests.post(url, headers=headers, json=conversation_payload)
    
             if response.status_code == 201:
                 return response.json()
             else:
                 print(f"Error: {response.status_code}\n{response.text}")
                 return None
    
         except requests.RequestException as e:
             print(f"Error accessing Freshchat API: {str(e)}")
             return None
    
     # Example: Creating a Freshchat conversation
     conversation_result = create_freshchat_conversation(FRESHCHAT_API_KEY, FRESHCHAT_API_URL)
    
     # Checking for successful creation and displaying the result
     if conversation_result:
         print("Conversation created successfully.")
         print("Result:", conversation_result)
    

    The create_freshchat_conversation function constructs a POST request to the Freshchat API, targeting the 'conversations' endpoint. The request includes the provided conversation payload in the request body, featuring details such as the message content, channel information, priority, and user details.

    Upon execution, the script calls the function with the Freshchat API key and API URL, and creates a Freshchat conversation.

    We can observe the conversation created on our Freshchat.

  2. Retrieving Freshchat Conversation Details

    The get_freshchat_conversation function empowers businesses to programmatically retrieve details about a specific Freshchat conversation, facilitating a comprehensive understanding of user interactions.

     def get_freshchat_conversation(FRESHCHAT_API_KEY, FRESHCHAT_API_URL, conversation_id):
         endpoint = f'conversations/{conversation_id}'
         url = FRESHCHAT_API_URL + endpoint
    
         headers = {
             'Authorization': f'Bearer {FRESHCHAT_API_KEY}',
             'Accept': 'application/json',
         }
    
         try:
             # Make a GET request to the Freshchat API
             response = requests.get(url, headers=headers)
             response.raise_for_status()
             return response.json()
         except requests.RequestException as e:
             print(f"Error accessing Freshchat API: {str(e)}")
             return None
    
     # Example: Retrieving details for a Freshchat conversation
     conversation_id = 'b2c25cca-b0e2-4334-88b7-a891634827f2'
     conversation_result = get_freshchat_conversation(FRESHCHAT_API_KEY, FRESHCHAT_API_URL, conversation_id)
    
     # Checking for successful retrieval and displaying the result
     if conversation_result:
         print("Conversation retrieved successfully.")
         print("Result:", conversation_result)
    

    The get_freshchat_conversation function constructs a GET request to the Freshchat API, targeting the 'conversations' endpoint with a specific conversation ID. The request includes the Freshchat API key for authentication and is designed to retrieve detailed information about the specified conversation.

    Upon execution, the script calls the function with the Freshchat API key, API URL, and a conversation ID and it retrieves the conversation details.

Use Case: Integrating Freshchat with ChatGPT to Generate Response for user without an Agent.

Installing the required modules:

pip install openai -q
pip install requests

Defining get_freshchat_message Function:

The get_freshchat_message function plays a pivotal role in retrieving messages from a specific Freshchat conversation, offering insights into user queries and concerns.

import requests
from openai import OpenAI
import json

client = OpenAI(api_key="Your API Key ") # Replace with your OpenAI API key

def get_freshchat_message(conversation_id: str):
    try:
        FRESHCHAT_API_KEY = 'YOUR_FRESHCHAT_API_KEY'

        url = f'https://futuresmartai-660352448177757789-92a0b0db5e3f7c317037774.freshchat.com/v2/conversations/{conversation_id}/messages'

        # Set up headers for the API request, including authorization with the API key
        headers = {
            'accept': 'application/json',
            'Authorization': f'Bearer {FRESHCHAT_API_KEY}'
        }

        # Make a GET request to the Freshchat API
        response = requests.get(url, headers=headers)
        response.raise_for_status()  # Raise an exception for HTTP errors

        # Parse the JSON response containing messages data
        messages_data = response.json()

        if 'messages' in messages_data:
            # Find the latest message in the conversation
            latest_message = max(messages_data['messages'], key=lambda x: x.get('created_time', ''))

            # Extract actor type (user or system) and message content
            actor_type = latest_message.get('actor_type', '')
            message_content = latest_message.get('message_parts', [{}])[0].get('text', {}).get('content', '')

            print(f"{actor_type}: {message_content}")
            return message_content
        else:
            print("No 'messages' key found in the response.")
            return None

    except requests.exceptions.RequestException as e:
        print(f"Error fetching Freshchat messages: {e}")
        return None

The get_freshchat_message function utilizes a GET request to the Freshchat API, targeting the 'messages' endpoint within a specific conversation. It retrieves and prints the latest message content along with the actor type (user or system). This functionality is pivotal for seamlessly integrating Freshchat with ChatGPT, enabling personalized and automated responses based on the most recent user interactions.

  • Sequence of Message Reception: We need to address the sequence of message reception. When a user initiates a conversation, understanding whether the message reaches ChatGPT first or the agent is vital for comprehending the flow of interactions.

  • Defining the Interaction : It encompasses the touchpoints between Freshchat, ChatGPT, and the end user. By exploring and defining this interaction zone, we ensure a smooth and cohesive user experience.

  • Decoding Agent vs ChatGPT Responses: A common source of confusion lies in whether a response originates from the Agent or ChatGPT. We'll explore the decision-making process behind this, offering insights into how the system seamlessly navigates between user and AI-generated responses.

  • Agent Availability: The online presence of the agent is important in the interaction dynamics. Understanding whether the agent remains online consistently or if specific conditions govern their availability contributes to managing user expectations during the conversation.

Defining the get_order_details Function:

We define a function get_order_details, which makes an API request to retrieve information for a given order.

def get_order_details(order_id, email_id):
    # Replace the actual endpoint URL for fetching order details
    url = "http://your_api_endpoint/order_info"

    # Set up parameters for the POST request, including order_id and email_id
    params = {'order_id': order_id, 'email_id': email_id}

    # Make a POST request to the API endpoint
    response = requests.post(url, params=params)

    if response.status_code == 200:
        return response.json()['Result'][0]
    else:
        return f"Error: Unable to fetch order details. Status code: {response.status_code}"

Describing Functions:

get_order_info function takes an argument called "order_id" and "email_id". it returns the order details associated with the provided order_id and email_id.

functions = [
    {
        "name": "get_order_info",
        "description": "The function retrieves all the Order specific information associated with the provided Order ID.",
        "parameters": {
            "type": "object",
            "properties": {
                "order_id": {
                    "type": "string",
                    "description": "unique id of the order to fetch order details",
                },
                "email_id": {
                    "type": "string",
                    "description":"A email id requires to fetch order details",
                },
            },
            "required": ["order_id","email_id"]
        }
    }
]

Defining the get_chatgpt_response_for_freshchat Function:

The get_chatgpt_response_for_freshchat function utilizes ChatGPT for extracting order details.

def get_chatgpt_response_for_freshchat(prompt):

    # Generate a response using ChatGPT
    response = client.chat.completions.create(
        model="gpt-3.5-turbo-1106",
        response_format={ "type": "json_object" },
        messages=[
            {"role": "system", "content": "You are a helpful assistant designed to output JSON. Please generate response for freshchat message, 'Order ID' is of numeric type and 'Email ID' is of string type. retrieve order id and email id from given conversation and Order details can be fetched by 'get_order_info' function call."},
            {"role": "user", "content": prompt},
        ],
        temperature=0,
        functions=functions,
        function_call="auto",
    )
    saved_response = response
    # Extract the message from the response
    response = response.choices[0].message

    if response.function_call:
        function_name = response.function_call.name
        if function_name == "get_order_info":
            order_id = json.loads(response.function_call.arguments)["order_id"]
            email_id = json.loads(response.function_call.arguments)["email_id"]
            # Call a function to get order details based on order ID and email ID
            order_details = get_order_details(order_id ,email_id)
            if order_details:
                 return {"order_details": order_details, "status": True }

    return {"order_details": "", "status":False}

In get_chatgpt_response_for_freshchat function we use function_call parameter to call a function in the prompt. The get_order_info functions defined in the prompt. The function_call parameter is set to "auto" to automatically call the function. GPT calls the function in the prompt and returns the order details.

  • Decision-Making Process: The Process to distinguish whether the response should be done by a human agent or generated using ChatGPT. This decision-making involves evaluating factors such as the query's nature, the ongoing conversation context, and predefined rules. These considerations are essential to meaningful and contextually relevant responses that enhance the user experience.

If you want to learn more about the ChatGPT Function calling. you can watch this video tutorial :

Defining gpt_function Function :

Introducing the gpt_function function that integrates with ChatGPT.

def gpt_function(conversation_id: str):

    # Retrieve the message with the specified conversation_id
    message_text = get_freshchat_message(conversation_id)

    extraction_prompt = f""" Given conversation: {message_text}"""

    # Generate a GPT response using the retrieved message text
    output = get_chatgpt_response_for_freshchat(extraction_prompt)
    print("GPT Response:", output)

It begins by retrieving the message text using the get_freshchat_message function. Subsequently, it leverages ChatGPT through the get_chatgpt_response_for_freshchat function to extract order details.

Generating GPT Response:

conversation_id = 'b2c25cca-b0e2-4334-88b7-a891634827f2'
gpt_function(conversation_id)

The GPT Response will retrieve the order details for provided order id and email id from user.

user: Hello, can you give my order details for my order id 12 and email id is william.jack@email.com
GPT Response: {'order_details': 'Order ID : 12\n Customer Name: william jack\n Order Date:2024-01-02 12:15:01\n Order status:payment_accepted\n Carrier:UPS - Gratis Vans\n Delivery Date: 2024-01-05 00:00:00', 'status': True}

Conclusion

In conclusion, the pivotal role of automation in achieving optimal customer engagement. By leveraging automated solutions, businesses can streamline and enhance their customer interactions, providing a seamless and efficient experience.

We have explored the integration of Freshchat and ChatGPT operations using Python, showcasing the power of these tools in revolutionizing customer engagement strategies. The emphasis on automation not only facilitates faster response times but also ensures a personalized and effective approach to addressing customer queries without an human agent.

If your company is looking to embark on a similar journey of transformation and you're in need of a tailored NLP solution, we're here to guide you every step of the way. Our team at FutureSmart AI specializes in crafting custom NLP applications, including generative NLP, RAG, and ChatGPT integrations, tailored to your specific needs.

Don't let your customer Engagement lag behind. Embrace the future of automated, intelligent customer interactions. Reach out to us at contact@futuresmart.ai, and let's discuss how we can build a smarter, more responsive customer Engagement system for your business. Join the ranks of forward-thinking companies leveraging the best of AI, and see the difference for yourself!

For further exploration and references, don't forget to check the Freshchat API documentation

Stay Connected with FutureSmart AI for the Latest in AI Insights - FutureSmart AI

Eager to stay informed about the cutting-edge advancements and captivating insights in the field of AI? Explore AI Demos, your ultimate destination for staying abreast of the newest AI tools and applications. AI Demos serves as your premier resource for education and inspiration. Immerse yourself in the future of AI today by visiting aidemos.com.

5
Subscribe to my newsletter

Read articles from Pawan T directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Pawan T
Pawan T