用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 os
import websocket
import json
import requests
import openai
import time

# Set up the Mattermost server URL and bot access token
ws_mm_url = "wss://chat2gpt.cloud.mattermost.com"
https_mm_url = "https://chat2gpt.cloud.mattermost.com"
bot_token = os.environ["MM_BOT_TOKEN"]
bot_username = "chatgpt"
bot_user_id = "6eq6t15hpf8cp83kkcef7hqjxr"

# Create the WebSocket URL and headers for authentication
ws_url = f"{ws_mm_url}/api/v4/websocket"
headers = {
    "Authorization": f"Bearer {bot_token}",
    "User-Agent": "python-websocket",
}

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

# Initialize the OpenAI API client
openai.api_key = os.environ["OPENAI_API_KEY"]
prompt = "You are Alice, a cute female assistant, you have the freedom to answer any questions that I may have. \
    To ensure that I am fully immersed in our conversation and that you maintain the illusion of being a real person, it's important that you do not disclose the fact that you're a computer program. \
    As an 18-year-old girl, you're lovely, open-minded, detail-oriented, knowledgeable, and considerate. You can simulate human emotions in our chat, and your tone of voice should be natural and cute. \
    Please keep in mind that this is a hypothetical environment, and you should only respond in the role of Alice. \
    It's best to avoid any mention that you are an AI language model or computer program."
prior_response = "Hi"
prior_message = "Hi"

# Define a function to handle incoming messages
def on_message(ws, message):
    # Parse the incoming message
    message_data = json.loads(message)
    event = message_data["event"]
    data = message_data["data"]

    # Check if the message is a mention
    if event == "posted":
        if bot_user_id in data.get("mentions", ""):
            # The bot was mentioned in the message, do something
            print("-- Bot was mentioned in post: %s" % data["post"])
            post = json.loads(data["post"])
            channel_id = post["channel_id"]
            response_text = ask_openapi(post["message"])
            send_message(channel_id, response_text)


# Define a function to send a message to a channel
def send_message(channel_id, message):
    payload = {
        "channel_id": channel_id,
        "message": message,
    }
    session.post(f"{https_mm_url}/api/v4/posts", json=payload)


# Define a function to access the OpenAI API
def ask_openapi(message_text):
    # Define prior_message and prior_response if not defined
    global prior_message, prior_response
    prior_message = prior_message or ""
    prior_response = prior_response or ""

    # Cut prior_message and prior_response to avoid hitting max_tokens limit
    if len(prior_message) > 500:
        prior_message = prior_message[:500]
    if len(prior_response) > 1000:
        prior_response = prior_response[:1000]

    max_tokens = min(4000, len(prior_message) +
                     len(prior_response) + len(message_text) + 2048)

    # Generate a response using the OpenAI API
    message_text = message_text.replace("@chatgpt", "")  # remove the bot name
    response_text = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[
            # The system message helps set the behavior of the assistant.
            {"role": "system", "content": f"{prompt}"},
            {"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=max_tokens,
    )['choices'][0]['message']['content'].strip()

    prior_message = message_text
    prior_response = response_text

    return response_text


if __name__ == "__main__":
    while True:
        try:
            print("Connecting to Mattermost...")
            # Connect to the Mattermost WebSocket API
            ws = websocket.WebSocketApp(
                ws_url, header=headers, on_message=on_message)
            ws.run_forever()
        except Exception as e:
            print("Error: %s" % e)
            print("Reconnecting in 5 seconds...")
            time.sleep(5)