Creating a New Conversation and Sending Messages with the CustomGPT API

Author Image

Written by: Priyansh Khodiyar

In this guide, you’ll learn how to create a new conversation and send multiple messages using the CustomGPT API. We’ll walk through each step—from generating an agent and conversation to sending both streaming and non-streaming requests—while highlighting best practices and troubleshooting tips. By following along, you’ll be able to build interactive chat experiences quickly and easily.

Make sure you have read our Getting Started with CustomGPT.ai for New Developers blog to get an overview of the entire platform.

1. Prerequisites to use CustomGPT API

Before you begin, make sure you have the following:

  • CustomGPT.ai Account: Sign up at CustomGPT.ai if you haven’t already.
  • API Key: Retrieve your API token from your account dashboard.
  • Basic Python Knowledge: Familiarity with Python and REST APIs is helpful.
  • Google Colab (Recommended): We’ll demonstrate these steps in a Colab notebook for ease of setup.

2. Setting Up Your Environment in Google Colab

Upload the Notebook File: Open Google Colab and upload the Create_a_new_conversation_and_send_a_message_to_the_conversation.ipynb file.

Verify Libraries:  This notebook uses the standard requests and json libraries as well as sseclient-py for streaming responses. Make sure to run the !pip install sseclient-py command where prompted.

Configuring Your API Key and Endpoints:  At the top of the notebook, you will see:

api_endpoint = 'https://app.customgpt.ai/api/v1/'

api_token = 'YOUR_API_TOKEN'

Replace ‘YOUR_API_TOKEN‘ with your real API token. This token authenticates your CustomGPT API calls, so keep it secure.

Get Your API Key

To get your API key, there are two ways:

Method 1 – Via Agent

  1. Agent > All Agents.
  2. Select your agent and go to deploy, click on the API key section and create an API. 

Method 2 – Via Profile section.

  1. Go to profile (top right corner of your screen)
  2. Click on My Profile
  3. You will see the screen something like this (below screenshot). Here you can click on “Create API key”, give it a name and copy the key.

Please save this secret key somewhere safe and accessible. For security reasons, You won’t be able to view it again through your CustomGPT.ai account. If you lose this secret key, you’ll need to generate a new one.

Now that you have your environment set up and your API key configured, let’s move on to creating your agent.

3. Code Walkthrough

This section breaks down the code step-by-step to help you understand how to interact with the API.

3.1 Agent Creation

Agent Setup: You begin by giving your agent a descriptive name and linking it to a sample sitemap URL.

project_name = 'Example ChatBot using Sitemap'

sitemap_path = 'https://adorosario.github.io/small-sitemap.xml'

payload = json.dumps({

    "project_name": project_name,

    "sitemap_path": sitemap_path

})

Note: Although the variable is named project_name in the code, think of it as the name for your agent.

Making the Request: The following code sends the payload to the projects endpoint of the CustomGPT API to create your agent.

url = api_endpoint + 'projects'

create_project = requests.request('POST', url, headers=headers, data=payload)

print(create_project.text)

Check the output from print(create_project.text) to confirm that your agent was created successfully.

Extracting the Agent ID: After creation, the API returns data that includes a unique identifier for your agent.

data = json.loads(create_project.text)["data"]

project_id = data['id']

This unique project_id (agent ID) lets you create new conversation and send messages within your agent.

With your agent successfully created and its ID extracted, you are ready to start a conversation with it.

3.2 Conversation Creation

Defining the Conversation: Next, you create a new conversation by specifying a name. Although the code uses the same name as the agent for simplicity, you can customize it as desired.

name = 'Test Converasation'

payload = json.dumps({

    "name": project_name

})

Sending the Conversation Request: A POST request is then sent to the conversations endpoint associated with your agent.

url = api_endpoint + 'projects' + f"/{project_id}" + '/conversations'

create_conversation = requests.request('POST', url, headers=headers, data=payload)

print(create_conversation.text)

The response will include details about the new conversation, such as a session ID.

Extracting the Session ID: This session ID is essential for tracking and continuing the conversation.

conversation_data = json.loads(create_conversation.text)["data"]

session_id = conversation_data["session_id"]

Now that your conversation has been created and you have the session ID, let’s move on to sending messages.

3.3 Sending a Streaming Message

Installing and Importing SSE Client: To handle streaming responses, install the SSE client library and import it:

!pip install sseclient-py

from sseclient import SSEClient

The sseclient-py library allows you to work with Server-Sent Events (SSE), which are used to stream responses from the API.

Constructing the Streaming Request: Prepare your prompt and set the stream flag to 1 for streaming responses.

prompt = "Who is Tom Brady"

stream = 1  # 1 for streaming response

url = api_endpoint + 'projects/' + str(project_id) + '/conversations/' + str(session_id) + '/messages'

payload = json.dumps({

    "prompt": prompt,

    "custom_persona": "You are a custom chatbot assistant called *Story Teller*, a friendly story teller who works for Test and answers questions based on the given context. Be as helpful as possible. Always prioritize the customer. Escalate complex issues. Stay on topic. Use appropriate language, Acknowledge limitations.",

    "stream": stream

})

headers["Accept"] = "text/event-stream"

stream_response = requests.post(url, stream=False, headers=headers, data=payload)

client = SSEClient(stream_response)

for event in client.events():

    print(event.data)

Here, the custom_persona field personalizes your agent’s responses. The SSEClient listens for streaming data and prints each event as it is received.

With streaming messaging working, let’s now see how to send a non-streaming message for quick, single-response queries.

3.4 Sending a Non-Streaming Message

Constructing the Non-Streaming Request: In some cases, you may prefer to get a complete answer in one response rather than a stream. Set the stream flag to 0.

prompt = "Who is Tom"

stream = 0  # 0 for non-streaming response

url = api_endpoint + 'projects/' + str(project_id) + '/conversations/' + str(session_id) + '/messages'

payload = json.dumps({

    "prompt": prompt,

    "stream": stream

})

non_stream_response = requests.post(url, stream=False, headers=headers, data=payload)

print(non_stream_response)

print(non_stream_response.text)

Setting stream=0 tells the API to return the response as a single block rather than as a continuous stream. The printed output includes both the HTTP status code and the full JSON response containing the chatbot’s answer.

Having explored both streaming and non-streaming methods, you can now test and verify your complete conversation flow.

4. Running and Testing the Notebook

Step-by-Step Execution:

  1. Install and Import Libraries:  Start by installing and importing the necessary libraries.
  2. Create the Agent:  Run the code to create the agent and store its unique ID.
  3. Create a New Conversation:  Use the conversation creation code to retrieve the session ID.
  4. Send a Streaming Message: Observe the incremental responses from the streaming API.
  5. Send a Non-Streaming Message: See the single-block response and verify it against your expectations.

Monitor Output Logs:

  • Confirm the responses from both the agent creation and new conversation creation steps.
  • Observe the outputs for both streaming and non-streaming messages to ensure clarity.
  • Check for any error messages and troubleshoot as needed.

Verifying on CustomGPT.ai: Log into your CustomGPT.ai dashboard to view your newly created agent, conversation details, and usage statistics. This step helps you confirm that your API calls and conversation data are recorded correctly.

5. Troubleshooting Common Issues

Even in a straightforward notebook, you might face a few challenges:

  • Invalid API Key: Verify that your API token is valid, has not expired, and is correctly placed in the code.
  • Network or Firewall Problems: A stable internet connection is essential for streaming responses. If you experience timeout errors, check your network and firewall settings.
  • SSEClient Installation Errors: If streaming fails, ensure you have run !pip install sseclient-py before attempting to stream the new conversation.
  • JSON Parsing Issues: Review the structure of your request and response if you encounter unexpected JSON format errors.

For further support or to report issues, refer to the official CustomGPT.ai documentation or connect with the user community.

6. Conclusion

Congratulations! You’ve successfully:

  • Created an Agent: Set up an agent using the CustomGPT API.
  • Started a Conversation: Initiated a new conversation within that agent.
  • Sent Messages: Implemented both streaming and non-streaming messages.
  • Customized the Chatbot Persona: Adjusted the chatbot’s tone and behavior for tailored interactions.

With these building blocks, you can now integrate rich, interactive chat features into your own applications or dashboards.

Further Exploration:

  • Experiment with different custom logic in the custom_persona field to shape your agent’s tone.
  • Explore additional endpoints for updating agent settings, retrieving conversation history, and more.
  • Combine multiple functionalities into a single, menu-driven Python application for full workflow automation.

If you have any questions or need more help, feel free to reach out to the CustomGPT.ai community or consult the official documentation. Enjoy your journey building powerful chatbots with CustomGPT!

Build a Custom GPT for your business, in minutes.

Deliver exceptional customer experiences and maximize employee efficiency with custom AI agents.

Trusted by thousands of organizations worldwide

Related posts

Leave a reply

Your email address will not be published. Required fields are marked *

*

3x productivity.
Cut costs in half.

Launch a custom AI agent in minutes.

Instantly access all your data.
Automate customer service.
Streamline employee training.
Accelerate research.
Gain customer insights.

Try 100% free. Cancel anytime.