Automate Your Customer Support: Integrating ChatGPT with Freshdesk

Pawan TPawan T
14 min read

Introduction

Overview of Freshdesk and its API

Freshdesk, a leading customer support platform, transforms how businesses engage with customers. With its user-friendly interface and powerful features, Freshdesk streamlines support processes, enhances customer interactions, and delivers outstanding service.

The Freshdesk API acts as a powerful bridge, enabling seamless integration and automation between the Freshdesk platform and external applications. It's a collection of web-based protocols and tools, allowing developers to programmatically engage with the Freshdesk customer support platform. This facilitates the exchange of data for creating, retrieving, updating, and deleting various entities.

Automating Freshdesk Support Using Chatgpt presents a comprehensive guide on streamlining customer support processes within the Freshdesk platform. By integrating ChatGPT, a powerful language model, into Freshdesk, businesses can enhance their customer service capabilities. This blog explores various use cases, including summarizing ticket conversations, extracting order details, and retrieving knowledge base answers. By automating routine tasks and leveraging the capabilities of ChatGPT, companies can provide more efficient and personalized customer support experiences. Let's get started!

Getting Started

Key Features and Capabilities:

To harness the full potential of the Freshdesk API, it's essential to explore its key features and capabilities.

Key Features:
  1. Ticket CRUD Operations:

    • An acronym for Create, Read, Update, and Delete. In the context of Freshdesk, these operations helps for managing support tickets.
  2. Real-time Ticket Management

    • Enables real-time ticket management for efficient support operations.
  3. Seamless Integration

    • Facilitates seamless integration of Freshdesk support functionalities with ChatGPT.
Capabilities:
  1. RESTful Architecture

    • The Freshdesk API adheres to RESTful principles, ensuring simplicity, scalability, and ease of integration.
  2. Authentication and Security

    • Secure API key-based authentication ensures data integrity and confidentiality.
  3. Data Retrieval and Filtering

    • Retrieve specific data sets using flexible filtering options. Optimize data retrieval based on parameters such as date, status, and priority.

Prerequisites

Obtaining a Freshdesk API Key:

To interact with the Freshdesk API, acquiring an API key is a fundamental step. The API key serves as an authentication mechanism, allowing secure access to your Freshdesk account programmatically.

Steps to Obtain Freshdesk API Key:
  1. Log in to Freshdesk:

    • Accessing my Freshdesk account involves using my credentials. If I don't have a Freshdesk account, I can sign up for a free trial on the Freshdesk website

To do this, I need to complete a registration form, activate my account through a verification email, and then log in to Freshdesk using my email address and password.

  1. After Login to Freshdesk account navigate to Profile Settings:

  2. Navigate to the 'View API Key' and we can see API Key Generated:

Setting up the development environment:

Once I've obtained my Freshdesk API key, the next critical step is to set up my development environment. This ensures that I have the necessary tools and configurations to interact seamlessly with Freshdesk API endpoints. Here's a step-by-step guide to help me establish an environment conducive to efficient API integration

  1. Install Required Libraries:

    • Ensure that I 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
      
  2. Access to a Python Environment:

    • Make sure to set up a Python environment on our machine, as Python scripts are frequently used for Freshdesk API interactions, making Python an essential prerequisite.
  3. Freshdesk API Documentation:

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

Making Requests

Function explanation:

The make_freshdesk_request function is a versatile tool for interacting with the Freshdesk API. Let's delve into the details

import requests

FRESHDESK_API_KEY = 'Your Freshdesk API Key'
FRESHDESK_API_URL = 'https://domain.freshdesk.com/api/v2/'

def make_freshdesk_request(FRESHDESK_API_KEY, FRESHDESK_API_URL, method, endpoint, json_data=None):
    url = FRESHDESK_API_URL + endpoint
    headers = {"Authorization": f"Basic {FRESHDESK_API_KEY}", "Content-Type": "application/json"}

    try:
        response = requests.request(method, url, headers=headers, json=json_data)
        response.raise_for_status()
        return {"data": response.json(), "response_text": response.text}
    except requests.RequestException as e:
        return {"error": f"Error accessing Freshdesk API: {str(e)}", "response_text": response.text}

This function serves as our intermediary for communication with Freshdesk. Whether we're creating a ticket, fetching details, or performing other tasks, this function handles the back-and-forth with Freshdesk seamlessly.

Handling Authentication with API Key:

    headers = {"Authorization": f"Basic {FRESHDESK_API_KEY}", "Content-Type": "application/json"}

Before we make any requests to Freshdesk, we need to prove our identity. The function accomplishes this by including our Freshdesk API key in the request headers. This key is like our secret password, allowing Freshdesk to recognize and authorize our requests.

Making requests using requests library:

    response = requests.request(method, url, headers=headers, json=json_data)
    response.raise_for_status()
    return {"data": response.json(), "response_text": response.text}

To communicate effectively with Freshdesk, we need a reliable courier. The requests library serves as our postman, handling the intricacies of delivering our requests and receiving the responses. This function orchestrates the entire process, making it easy for us to interact with Freshdesk through Python code.

In essence, the make_freshdesk_request function acts as our messenger, including our special key (Freshdesk API key) in the message and utilizing the trusty requests library to facilitate smooth communication with Freshdesk. It streamlines the process, making it user-friendly and accessible.

Ticket Management

Listing Tickets:

This section process the retrieving a list of tickets from Freshdesk.

def list_tickets(FRESHDESK_API_KEY, FRESHDESK_API_URL):
    result = make_freshdesk_request(FRESHDESK_API_KEY, FRESHDESK_API_URL, "GET", "tickets")
    tickets = result.get("data", [])
    print("Result (List Tickets):" if tickets else "No tickets found.")
    for ticket in tickets:
        print(f"Ticket ID: {ticket['id']}, Subject: {ticket['subject']}, Priority: {ticket['priority']}, Status: {ticket['status']}")

To retrieve a list of tickets from Freshdesk, the list_tickets function is utilized. This function takes two parameters, FRESHDESK_API_KEY and FRESHDESK_API_URL, enabling authentication and specifying the Freshdesk domain. Upon making a GET request to the Freshdesk API, it fetches ticket data.

The result is then processed, and if tickets are found, relevant details such as Ticket ID, Subject, Priority, and Status are printed for user visibility. This function facilitates the efficient retrieval and display of ticket information.

Response:

{
  "Result (List Tickets)": [
    {
      "Ticket ID": 11,
      "Subject": "Quality issue",
      "Priority": 1,
      "Status": 2
    },
    {
      "Ticket ID": 10,
      "Subject": "Delay in my order",
      "Priority": 1,
      "Status": 2
    }
  ]
}

Creating a Ticket:

Creating a ticket involves initiating a new ticket in Freshdesk.

def create_ticket(FRESHDESK_API_KEY, FRESHDESK_API_URL):
    ticket_data = {
        "description": input("Enter issue description: "),
        "subject": input("Enter ticket subject: "),
        "email": input("Enter user email: "),
        "priority": int(input("Enter priority (1, 2, 3, etc.): ")),
        "status": int(input("Enter status (2 for open, 3 for pending, etc.): "))
    }
    result = make_freshdesk_request(FRESHDESK_API_KEY, FRESHDESK_API_URL, "POST", "tickets", json_data=ticket_data)
    print("Result (Create Ticket):", result)

This function create_ticket, allows users to input details for a new Freshdesk ticket, including the issue description, ticket subject, user email, priority, and status. It leverages the provided parameters, FRESHDESK_API_KEY and FRESHDESK_API_URL, to authenticate and send a POST request to the Freshdesk API, for creating a new ticket. Finally, the ticket will be created.

We can observe the ticket creation on our Freshdesk User Interface.

Getting Ticket Details:

This section outlines the process of obtaining comprehensive information on a particular ticket in Freshdesk.

def get_ticket_details(FRESHDESK_API_KEY, FRESHDESK_API_URL):
    ticket_id = input("Enter ticket ID: ")
    result = make_freshdesk_request(FRESHDESK_API_KEY, FRESHDESK_API_URL, "GET", f"tickets/{ticket_id}")
    print("Result (Get Ticket Details):", result)

The get_ticket_details function helps users to retrieve specific details about a Freshdesk ticket by providing the ticket ID as an input. Leveraging the parameters FRESHDESK_API_KEY and FRESHDESK_API_URL, this function securely authenticates and sends a GET request to the Freshdesk API, fetching detailed information about the specified ticket.

Response:

{
  "Result (Get Ticket Details)": {
    "data": {
      "cc_emails": [],
      "fwd_emails": [],
      "reply_cc_emails": [],
      "ticket_cc_emails": [],
      "fr_escalated": false,
      "spam": false,
      "email_config_id": 1070000038299,
      "group_id": null,
      "priority": 1,
      "requester_id": 1070012864262,
      "responder_id": null,
      "source": 2,
      "company_id": null,
      "status": 2,
      "subject": "Cancel order",
      "association_type": null,
      "support_email": null,
      "to_emails": null,
      "product_id": 1070000031097,
      "id": 12,
      "type": null,
      "due_by": "2023-12-22T22:00:00Z",
      "fr_due_by": "2023-12-20T22:00:00Z",
      "is_escalated": false,
      "description": "<div>can you try to cancel my order with order id 18</div>",
      "description_text": "can you try to cancel my order with order id 18",
      "custom_fields": {
        "cf_reference_number": null
      },
      "created_at": "2023-12-20T10:38:40Z",
      "updated_at": "2023-12-20T10:38:40Z",
      "tags": [],
      "attachments": [],
      "source_additional_info": null,
      "form_id": 1070000103738,
      "nr_due_by": null,
      "nr_escalated": false
    },
    "response_text": "{\"cc_emails\":[],\"fwd_emails\":[],\"reply_cc_emails\":[],\"ticket_cc_emails\":[],\"fr_escalated\":false,\"spam\":false,\"email_config_id\":1070000038299,\"group_id\":null,\"priority\":1,\"requester_id\":1070012864262,\"responder_id\":null,\"source\":2,\"company_id\":null,\"status\":2,\"subject\":\"Cancel order\",\"association_type\":null,\"support_email\":null,\"to_emails\":null,\"product_id\":1070000031097,\"id\":12,\"type\":null,\"due_by\":\"2023-12-22T22:00:00Z\",\"fr_due_by\":\"2023-12-20T22:00:00Z\",\"is_escalated\":false,\"description\":\"<div>can you try to cancel my order with order id 18</div>\",\"description_text\":\"can you try to cancel my order with order id 18\",\"custom_fields\":{\"cf_reference_number\":null},\"created_at\":\"2023-12-20T10:38:40Z\",\"updated_at\":\"2023-12-20T10:38:40Z\",\"tags\":[],\"attachments\":[],\"source_additional_info\":null,\"form_id\":1070000103738,\"nr_due_by\":null,\"nr_escalated\":false}"
  }
}

Updating a Ticket:

This section provides insights into the process of updating a ticket within Freshdesk.

def update_ticket(FRESHDESK_API_KEY, FRESHDESK_API_URL):
    ticket_id = input("Enter ticket ID to update: ")
    updated_ticket_data = {
        "description": input("Enter updated issue description: "),
        "subject": input("Enter updated ticket subject: "),
        "email": input("Enter updated user email: "),
        "priority": int(input("Enter updated priority (1, 2, 3, etc.): ")),
        "status": int(input("Enter updated status (2 for open, 3 for pending, etc.): "))
    }
    result = make_freshdesk_request(FRESHDESK_API_KEY, FRESHDESK_API_URL, "PUT", f"tickets/{ticket_id}", json_data=updated_ticket_data)
    print("Result (Update Ticket):", result)

The update_ticket function helps users to modify existing Freshdesk tickets with ease. By inputting the desired ticket ID, users can then provide updated details such as the issue description, ticket subject, user email, priority, and status. Leveraging the parameters FRESHDESK_API_KEY and FRESHDESK_API_URL, this function utilizes a PUT request to the Freshdesk API, it update the specified ticket. The result of the update will be displayed.

we can also observe the updating existing ticket on our Freshdesk User Interface.

Deleting a Ticket:

This section outlines the process of deleting a ticket.

def delete_ticket(FRESHDESK_API_KEY, FRESHDESK_API_URL):
    ticket_id = input("Enter ticket ID to delete: ")
    result = make_freshdesk_request(FRESHDESK_API_KEY, FRESHDESK_API_URL, "DELETE", f"tickets/{ticket_id}")
    print("Result (Delete Ticket): Ticket successfully deleted.")

The delete_ticket function helps users to effortlessly remove unwanted tickets from Freshdesk. By prompting users to input the ticket ID they wish to delete, this function utilizes the FRESHDESK_API_KEY and FRESHDESK_API_URL parameters to authenticate and send a DELETE request to the Freshdesk API, initiating the ticket deletion process. Upon successful deletion, a confirmation message will be displayed.

Response:

{
  "Result": "Ticket successfully deleted."
}

If you'd like to Prefer a Visual Guide? for building APIs powered by ChatGPT. you can watch the video tutorial :

Beginner's Guide to FastAPI & OpenAI ChatGPT API Integration

Use Case: Automating Freshdesk Support with ChatGPT

Installing the required modules:

pip install openai -q
pip install requests

Extracting Order Details, Summarizing Ticket Conversation and Retrieving Knowledge base answers.

Defining get_ticket_text Function:

The get_ticket_text function retrieves ticket information from Freshdesk

import requests
from openai import OpenAI 
import json

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

def get_ticket_text(ticket_id: int):
    try:
        FRESHDESK_API_KEY = 'Your Freshdesk API Key'
        url = f'https://domain.freshdesk.com/api/v2/tickets/{ticket_id}'
        headers = {'Authorization': f'Basic {FRESHDESK_API_KEY}'}

        response = requests.get(url, headers=headers)
        response.raise_for_status()

        ticket_info = response.json()
        return ticket_info.get("description", "")
    except requests.exceptions.RequestException as e:
        print(f"Error fetching ticket information: {e}")
        return ""

Defining the get_knowledge_chromadb Function:

The get_knowledge_chromadb function used to get knowledge base data from chromadb, this function takes single argument called query. It utilizes the Sentence Transformer to encode the query and uses chromadb to query the encoded query. The function concludes by returning the top 2 similar data points obtained from the query results.

def get_knowledge_chromadb(query):

    import chromadb
    from sentence_transformers import SentenceTransformer

    model_name = "multi-qa-MiniLM-L6-cos-v1"
    client = chromadb.PersistentClient(path="chromadb_index")
    collection = client.get_collection("index_name")
    model = SentenceTransformer(model_name)
    query_embedding = model.encode(query)
    results = collection.query(query_embedding, n_results=2)
    if results['metadatas'][0]:
        context =results['metadatas'][0][0]['knowledge']+"\n"+results['metadatas'][0][1]['knowledge']
    else:
        context=""
    return results

If you want to learn more about Chroma vector database and Semantic search you can watch this video tutorial :

https://youtu.be/eCCHDxMaFIk?si=sM0whXw2Qk6b1bbX

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):
    url = "http://your_api_endpoint/order_info"  # Replace with your actual endpoint
    params = {'order_id': order_id}
    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}"

order_details = get_order_details(order_id=12)
print(order_details)

Describing Functions:

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

knowledge_base function takes an arguments called "query" and it returns the knowledge base data associated with the query.

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",
                }
            },
            "required": ["order_id"],
        }
    },
    {"name": "knowledge_base",
     "description": "The function retrieves the knowledge from chromadb using the query provided.",
        "parameters": {
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": "query to search in chromadb",
                }
            },
            "required": ["query"],

        }
    }
]

Defining the generate_ticket_response Function:

while the generate_ticket_response function utilizes ChatGPT for extracting order details.

def generate_ticket_response(text):

    conversation_str = f"""Given conversation : {text}"""

    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. 'Order ID' is of numeric type. 'Order ID' can sometimes be followed by '#' symbol, please extract the 'Order ID' by removing the symbol. Order details can be fetched by 'get_order_info' function call."},
            {"role": "user", "content": conversation_str},
        ],
        temperature=0,
        functions=functions,
        function_call="auto",
    )
    saved_response = 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"]
            order_details = get_order_details(order_id=12) 
            if order_details:
                return {"order_details": order_details, "status": True }
        elif function_name == "knowledge_base":
            query = json.loads(response.function_call.arguments)["query"]
            data = get_knowledge_chromadb(query)

            response = client.chat.completions.create(
                model="gpt-3.5-turbo-1106",
                response_format={ "type": "text" },
                messages=[
                    {"role": "system", "content": "You are a helpful assistant. Provide response in formal language."} ,
                    {"role": "user", "content": f"""Here is the knowledge base data for the given conversation: {data}""" },
                    {"role": "user", "content": f"Given conversation : \n{query}"},

                ],
                temperature=0,

            )
            return {"response": response.choices[0].message.content, "status": True}
    return {"order_details": "", "status":False}

In generate_ticket_response function we use function_call parameter to call a function in the prompt. There are two functions defined in the prompt, get_order_info and knowledge_base. 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 in JSON format and the order details are extracted from the JSON response and returned.

If you'd like to Prefer a Visual Guide? for ChatGPT Function calling. you can watch the video tutorial :

https://youtu.be/pI1yUiNKyDA?si=BrkMNclGb-YmRvhd

Defining get_chatgpt_summary_orderID_details Function:

def get_chatgpt_summary_orderID_details(text):

    conversation_str = f"""Given conversation : {text}"""

    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 summary of given conversation in 'summary' . Also extract topics from given conversation in 'topics' tag. 'Order ID' is of numeric type. 'Order ID' can sometimes be followed by '#' symbol, please extract the 'Order ID' by removing the symbol. Extract order ID in 'order_id'"},
            {"role": "user", "content": conversation_str},
        ],
        temperature=0,
    )

    return response.choices[0].message.content

The get_chatgpt_summary_orderID_details function demonstrates how to use the function_call parameter to call a function in the prompt and this function is to generate summary of given conversation and extract topics from given conversation and extract order ID from given conversation.

If you'd like to Prefer a Visual Guide? on how to implement OpenAI's ChatGPT API in your projects and how to use OpenAI's ChatGPT API to Build a Conversational AI Chatbot check out this helpful video tutorial:

https://youtu.be/RALmm6flXII?si=f2QTY2nB1dZTUGjz

Defining gpt_function Function

Introducing the gpt_function function that integrates with GPT to handle ticket-related information and user queries, providing meaningful responses based on the context of the conversation.

def gpt_function(ticket_id: int):
    ticket_text = get_ticket_text(ticket_id)

    output = generate_ticket_response(ticket_text)
    print(output)
    out = get_chatgpt_summary_orderID_details(ticket_text)
    print(json.loads(out))
    ticket_conversation = "what is your return policy?"
    output = generate_ticket_response( ticket_conversation)
    print(output)

It begins by retrieving the ticket text using the get_ticket_text function. Subsequently, it leverages ChatGPT through the generate_ticket_response function to extract order details and generate comprehensive summaries of ticket conversations. Furthermore, the code demonstrates the model's capability by simulating user inquiries, such as querying the return policy, and showcases ChatGPT's responses.

Generating GPT Response

ticket_id = 10
gpt_function(ticket_id)

The gpt response will retrieve order details, summarizing conversation and knowledge base answer.

{'order_details': 'Customer Name: Alex\nOrder Date:2023-12-05 21:15:01\nOrder status:payment_accepted\nCarrier:UPS - Gratis Vans\nDelivery Date: 2023-12-20 00:00:00', 'status': True}
{'summary': 'The customer has ordered an SSD CARD on 14-12-2023 and has not received any updates for a week. The order ID mentioned is 12, and the customer is inquiring about the expected delivery date.', 'topics': ['SSD CARD', 'order status', 'delivery date'], 'order_id': 12}
{'response': 'The return policy allows for items to be returned within 7 days of purchase.','status': True}

Conclusion

In conclusion, integrating advanced NLP solutions like ChatGPT into customer support systems can significantly enhance efficiency and customer satisfaction. Our deep dive into Freshdesk's APIs demonstrates the seamless connection between these technologies, allowing for automated ticket management and knowledgeable customer interactions.

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 support 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 support 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 Freshdesk 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.

8
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