Automate Your Customer Support: Integrating ChatGPT with Odoo HelpDesk

Automate Your Customer Support: Integrating ChatGPT with Odoo HelpDesk

·

12 min read

Introduction

In the dynamic landscape of business management, Odoo stands out as a comprehensive solution, offering a versatile platform that caters to diverse organizational needs. The Odoo Helpdesk module is a crucial component for managing customer inquiries, issues, and feedback.

Odoo Helpdesk serves as the nerve center for efficient customer support within the Odoo ecosystem. It empowers organizations to streamline their customer interactions, providing a centralized hub for managing tickets, resolving issues, and ensuring customer satisfaction.

As businesses seek innovative ways to enhance customer support, the fusion of ChatGPT with Odoo Helpdesk using Python emerges as a revolutionary approach. ChatGPT places a strong emphasis on natural language processing. The integration of ChatGPT with Odoo Helpdesk signifies a shift towards automated, intelligent responses that not only address customer queries but also elevate the overall support experience.

Setting up the development environment

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

Initializing the odoorpc library :

The odoorpc library facilitates communication with an Odoo instance, allowing you to perform various operations programmatically.

pip install odoorpc

Connecting to Odoo Helpdesk:

import odoorpc

# Define the data for connecting to the Odoo Helpdesk.
db_name = "Your Odoo Helpdesk database name"
username = "Your Odoo Helpdesk username"
password = "Your Odoo Helpdesk password"

# Initialize an 'odoo' object using odoorpc. Set the Odoo Helpdesk domain, protocol, and port.
# In this example, we use the 'jsonrpc+ssl' protocol and port 443, which is common for secure connections.
odoo = odoorpc.ODOO('Your Odoo Helpdesk domain', protocol='jsonrpc+ssl', port=443)

# Login to the Odoo Helpdesk with the provided database name, username, and password.
odoo.login(db_name, username, password)
  • The odoo variable is created as an instance of the ODOO class from the odoorpc library.

  • The ODOO class takes the Odoo Helpdesk URL, the protocol used (JSON-RPC with SSL in this case), and the port number.

  • The login method is then called to authenticate and log in to the Odoo instance using the provided database name, username, and password.

Odoo helpdesk models :

    • helpdesk_team_model: This variable is assigned the value of the Odoo model associated with helpdesk teams.

         # This allows you to interact with the 'helpdesk.team' model. 
         helpdesk_team_model = odoo.env['helpdesk.team']
      
      • odoo.env['helpdesk.team'] : This expression accesses the Odoo environment (odoo.env) and specifies the model related to helpdesk teams. In Odoo, a "team" in the helpdesk context might refer to a group of individuals responsible for handling specific types of inquiries or support tickets.
    • helpdesk_ticket_model: This variable is assigned the value of the Odoo model associated with helpdesk tickets.

         # This allows you to interact with 'helpdesk.ticket' model.
         helpdesk_ticket_model = odoo.env['helpdesk.ticket']
      
      • odoo.env['helpdesk.ticket']: This expression accesses the Odoo environment and specifies the model related to helpdesk tickets. In Odoo, a "ticket" typically represents a customer inquiry, issue, or support request.

Creating Helpdesk Team:

To effectively manage customer inquiries and support tickets, establishing teams within the helpdesk module is crucial.

# Define team data
team_data = {
    'name': 'Sales order team',
    'description': 'Sales order team to handling order issue given by customer.',
}
# Create a helpdesk team
team_id = helpdesk_team_model.create(team_data)
print(f"Sales order team (ID: {team_id}) is created!")

team_data encapsulates essential information about the new helpdesk team, such as its name and a brief description. The helpdesk_team_model.create() method is then utilized to create a new team in the Odoo helpdesk module, with the provided data. The unique identifier (ID) assigned to the newly created team is stored in the variable team_id.

We can observe that helpdesk team as been created on our Odoo Helpdesk.

Ticket Management

Creating a Ticket:

The creation of a new helpdesk ticket within the Odoo platform.

# Define ticket data
ticket_data = {
    'name': 'Delay in order',
    'team_id': team_id,
    'description': 'I have ordered a product with order id 46 but still i didnt receive my order',
}
# Create a new ticket
ticket_id = helpdesk_ticket_model.create(ticket_data)
print(f"New Ticket (ID: {ticket_id}) is created!")

The ticket_data holds essential information about the ticket, such as its name, associated team ID, and a description of the reported issue. The helpdesk_ticket_model.create(ticket_data) function is then invoked, initiating the creation process of the new ticket. The unique identifier (ID) assigned to the newly created ticket is stored in the variable ticket_id.

We can observe that Ticket as been created on our Odoo Helpdesk.

Reading a Ticket :

Retrieving information about a specific helpdesk ticket within the Odoo system.

#read a ticket by providing ticket_id
read_ticket = helpdesk_ticket_model.read(ticket_id, ['name', 'description'])
print("Read Ticket Information:", read_ticket)

The helpdesk_ticket_model.read(ticket_id, ['name', 'description']) function is employed to extract specific details associated with the identified ticket, referenced by its unique identifier stored in the variable ticket_id. The parameters passed to the function, namely ['name', 'description'], indicate the specific fields of the ticket that should be included in the retrieval.

Updating a Ticket :

Updating the information associated with a specific helpdesk ticket.

# Provide a ticket_id to update
update_ticket_id = ticket_id 

# Define the values you want to update in the ticket
update_values = {'name' : 'Updated Ticket name',
                'description': 'Updated Tiket description' }

# Use the 'write' method to update the ticket with the specified values
helpdesk_ticket_model.write(update_ticket_id, update_values)
print("Ticket Updated Successfully")

The update_ticket_id as the identifier of the ticket that needs to be modified, and update_values containing the new information to be applied. The helpdesk_ticket_model.write(update_ticket_id, update_values) function is to execute the update. It takes the ticket's ID (update_ticket_id) and the updated values (update_values) as parameters, making the necessary modifications to the ticket's details.

Deleting a Ticket :

The process of deleting a helpdesk ticket within the Odoo platform.

# Use the unlink method to delete the ticket with the given ticket_id
helpdesk_ticket_model.unlink([ticket_id])
print("Ticket Deleted Successfully")

The helpdesk_ticket_model.unlink([ticket_id]) function is utilized to initiate the deletion of the specified ticket, identified by its ticket ID (ticket_id). The unlink method is the mechanism employed by Odoo to remove records from the database, and in this case, it targets the ticket identified by the provided ID.

Use case: Automating odoo helpdesk with chatgpt

Installing the OpenAI Python Package: To interact with OpenAI's APIs, start by installing the OpenAI Python package.

pip install openai -q

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

Setting up odoo helpdesk connection :

Please refer to the above explanation for connecting to Odoo Helpdesk.

from openai import OpenAI
import json
import odoorpc

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

db_name = "Your odoo helpdesk database name"
username = "Your odoo helpdesk username"
password = "Your odoo helpdesk password"

odoo = odoorpc.ODOO('Your odoo helpdesk domain', protocol='jsonrpc+ssl', port=443)
odoo.login(db_name, username, password)

Defining get_odoo_ticket_description Function:

The get_odoo_ticket_description function is to retrieve the description of a helpdesk ticket from odoo using the provided ticket ID.

def get_odoo_ticket_description(ticket_id : int):
    try:
        # Access the Odoo environment and retrieve the 'helpdesk.ticket' model
        helpdesk_ticket_model = odoo.env['helpdesk.ticket']

        # Read the description field for the specified ticket_id
        ticket_info = helpdesk_ticket_model.read(ticket_id, ['description'])

        # Check if ticket_info is a non-empty list
        if isinstance(ticket_info, list) and ticket_info:
            ticket_info = ticket_info[0]

        # Return the description field or an empty string if not found
        return ticket_info.get('description', "")
    except Exception as e:
        print(f"Error fetching ticket information from Odoo: {e}")
        return ""

The function uses the Odoo environment to access the helpdesk.ticket model, reads the description field for the specified ticket, and returns the description.

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

    # Specify the model for sentence embeddings
    model_name = "multi-qa-MiniLM-L6-cos-v1"

    # Initialize ChromaDB PersistentClient with the path to the index
    client = chromadb.PersistentClient(path="chromadb_index")

    # Retrieve the specified collection from ChromaDB
    collection = client.get_collection("index_name")

    #Load Sentence Transformer model
    model = SentenceTransformer(model_name) 

    # Encode the input query using the Sentence Transformer model
    query_embedding = model.encode(query)

    # Query the collection to retrieve relevant knowledge
    # n_results specifies the number of results to retrieve (here, 2 results)
    results = collection.query(query_embedding, n_results=2)
    if results['metadatas'][0]:
        # Extract knowledge from the metadata of the first two results
        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 :

Semantic Search with Open-Source Vector DB: Chroma DB

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

    # Give the parameters for the API request
    params = {'order_id': order_id}

    # Send a POST request to the API endpoint with the specified parameters
    response = requests.post(url, params=params)

    # Check if the API request was successful (status code 200)
    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=46)
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 from Chromadb using the query provided.

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}"""

    # Use OpenAI GPT-3.5-turbo to generate a response
    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

    # 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"]

            # Call the get_order_details function to fetch order details
            order_details = get_order_details(order_id=46) 
            if order_details:
                return {"order_details": order_details, "status": True }
        elif function_name == "knowledge_base":
            query = json.loads(response.function_call.arguments)["query"]

            #call the get_knowledge_chromadb function to get knowledge base data
            data = get_knowledge_chromadb(query)

            # Use GPT-3.5-turbo to generate a response in formal language
            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 want to learn more about the ChatGPT Function calling. you can watch this video tutorial :

OpenAI Function Calling Explained: Chat Completions & Assistants API

Defining get_chatgpt_summary_orderID_details Function:

def get_chatgpt_summary_orderID_details(text):

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

    # Use OpenAI GPT-3.5-turbo to generate a summary and extract information from the conversation
    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 this video tutorial:

Using OpenAI's ChatGPT API to Build a Conversational AI Chatbot

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):
    # Retrieve the description with the specified ticket_id
    ticket_text = get_odoo_ticket_description(ticket_id)

    # Generate a response using the retrieved ticket text 
    output = generate_ticket_response(ticket_text)
    print(output)

    # Obtain a summary of order details using the ticket text
    out = get_chatgpt_summary_orderID_details(ticket_text)
    print(json.loads(out))

    # Generate a response for the ticket conversation
    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_odoo_ticket_description 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 = 16
gpt_function(ticket_id)

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

{'order_details': 'Customer Name: John Doe\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 mentioned that they have ordered a product with order id 46 but have not received the order yet.', 'topics': ['order status', 'product delivery'], 'order_id': 46}
{'response': 'The return policy allows for items to be returned within 7 days of purchase', 'status': True}

Conclusion

In conclusion, the Odoo helpdesk and its integration with ChatGPT has illuminated the effective ticket management for customer support. The Odoo helpdesk module, with its versatile capabilities, serves a businesses seeking to provide exceptional customer service by managing inquiries and concerns efficiently.

The ChatGPT, a powerful language model, introduces a new era in customer interactions. With natural language processing at its core, ChatGPT enables intelligent, human like responses for customer support.

if you wish to integrate ChatGPT with Freshdesk for customer support you can refer this Freshdesk Blog.

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 , 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!

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

Keep up with the latest breakthroughs and fascinating insights in the world of AI by staying connected with FutureSmart AI. Discover AI Demos, for staying updated on the newest AI tools and applications. AI Demos is your top resource for both education and inspiration. Dive into the future of AI now by visiting aidemos.com.