用OpenAI GPT-3和 Mattermost 打造 Chatbot

Page content

Mattermost

  • Mattermost is a free and open-source team collaboration platform that provides chat, file sharing, and other collaboration tools for teams and organizations. Mattermost is designed to be a self-hosted platform, which means that organizations can install and manage their own instance of the platform on their own servers or cloud infrastructure.

Opeai GPT-3

  • OpenAI GPT-3 is a language model that uses deep learning to produce human-like text. It is the third-generation language model from OpenAI, following GPT and GPT-2. GPT-3 is the largest language model ever released, with 175 billion parameters and 10 trillion connections. It is trained on a dataset of 45 GB of internet text, and is capable of generating coherent text in 40 languages.

Python Code

import requests
import json
import openai
import time

# Define the Mattermost server URL and API token
mattermost_url = "your_mm_url"
api_token = "your_mm_token"

# Define the bot username and channel name
bot_username = "chatgpt"
channel_name = "talkwithgpt"
team_name = "chat2ai"
bot_user_id = "6eq6t15hpf8cp83kkcef7hqjxr"
channel_id = "u348bdpb87dwpgz7odrjcr7fuw"


# Create a session object with the API token
session = requests.Session()
session.headers.update({"Authorization": f"Bearer {api_token}"})

# Initialize the OpenAI API client
openai.api_key = "your_opanai_key"

# Define the OpenAI API prompt
prompt = "You are a helpful AI assistant."
prior_response = "Provide helpful advice here."
prior_message = "Start a conversation here."

# Keep track of the IDs of messages that the bot has already replied to
replied_message_ids = set()
count = 0

while True:
    count += 1
    # Note: Sleep 1-2 seconds to reduce the QPS load on the Mattermost server
    try:
        # Use the Mattermost API to get the most recent post in the channe
        response = session.get(
            f"{mattermost_url}/channels/{channel_id}/posts?page=0&per_page=1")
        messages = json.loads(response.text)
        if len(messages) == 0 or messages.get("order") is None or messages.get("posts") is None:
            print("No messages, skipping...")
            time.sleep(2)  # Wait 2 second before checking for new messages
            continue

        order_list = messages['order']
        post_dict = messages['posts']
        latest_message = post_dict[order_list[0]]

        # Check whether the latest message has already been replied to
        if latest_message["id"] in replied_message_ids:
            print("Already replied to this message: %s, skipping..." %
                  latest_message["id"])
            time.sleep(2)  # Wait 2 second before checking for new messages
            continue

        # Check whether the latest message is from the bot itself
        if latest_message["user_id"] == bot_user_id:
            print("%d|Bot message, skipping..." % count)
            time.sleep(2)  # Wait 2 second before checking for new messages
            continue

        print("%d|User message, processing..." % count)
        # Check whether the latest message mentions the bot
        if f"@{bot_username}" not in latest_message["message"]:
            print("%d|No mention bot, skipping..." % count)
            time.sleep(2)  # Wait 2 second before checking for new messages
            continue

        # Extract the latest message text
        message_text = latest_message["message"]
        mm_user_id = latest_message["user_id"]

        # Generate a response using the OpenAI API
        response_text = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=[
                # The system message helps set the behavior of the assistant.
                {"role": "system", "content": "You are a helpful AI assistant."},
                {"role": "user", "content": f"{prior_message}"},  # user input
                # The assistant messages help store prior responses.
                {"role": "assistant", "content": f"{prior_response}"},
                # The user messages help instruct the assistant.
                {"role": "user", "content": f"{message_text}"},  # user input
            ],
            max_tokens=2048,  # limit at 2048 for free account
        )['choices'][0]['message']['content'].strip()

        # Reset the prior_response and prior_message
        prior_response = response_text
        prior_message = message_text

        # Post the response in the channel
        post_data = {"channel_id": channel_id, "message": response_text}
        session.post(f"{mattermost_url}/posts", data=json.dumps(post_data))
        # Add the latest message ID to the replied message IDs set
        replied_message_ids.add(latest_message["id"])

        time.sleep(1)  # Wait 1 second before checking for new messages

    except Exception as e:
        print(e)
        time.sleep(1)  # Wait 1 second before checking for new messages

本文由 络壳 原创或整理,转载请注明出处