В современном цифровом мире чат-боты стали неотъемлемой частью нашей жизни. Они обеспечивают мгновенную помощь и экономят время, что делает их бесценным инструментом как для бизнеса, так и для частных лиц. А с помощью ChatGPT API создание персонализированного чат-бота никогда не было проще.

В этом сообщении блога мы познакомим вас с процессом создания вашего собственного персонализированного чат-бота с использованием API ChatGPT. Мы расскажем обо всем, от начала работы с API до настройки ответов вашего чат-бота.

Преимущества:

Использование персонализированного чат-бота может принести много преимуществ, таких как:

  • Экономия времени и повышение эффективности за счет автоматизации повторяющихся задач
  • Повышение вовлеченности и удовлетворенности клиентов за счет предоставления мгновенных ответов на запросы
  • Персонализация взаимодействия с пользователем путем адаптации ответов к конкретным потребностям и предпочтениям
  • Сбор ценных данных и информации о взаимодействиях с пользователями для улучшения продуктов и услуг.

Конечно, вот пример записи в блоге, которую вы можете использовать в качестве отправной точки для своего собственного персонализированного чат-бота:

Название: Создание персонализированного чат-бота с использованием ChatGPT API: пошаговое руководство

Пошаговое руководство:

  1. Зарегистрируйтесь в API ChatGPT. Чтобы начать работу, зарегистрируйтесь в API ChatGPT и создайте учетную запись. Вы получите ключ API, который будете использовать для доступа к API.
  2. Выберите платформу: решите, какую платформу вы хотите использовать для создания своего чат-бота. ChatGPT API совместим со многими платформами, включая Dialogflow, Slack и Facebook Messenger.
  3. Настройте своего чат-бота: настройте своего чат-бота, создав учетную запись на выбранной вами платформе и подключив ее к API ChatGPT с помощью своего ключа API.
  4. Настройте ответы своего чат-бота: после того, как ваш чат-бот настроен, вы можете настроить его ответы в соответствии со своими потребностями. Вы можете создавать собственные ответы для конкретных ключевых слов или фраз или использовать для начала готовые шаблоны.
  5. Протестируйте и доработайте своего чат-бота: протестируйте своего чат-бота, чтобы увидеть, как он работает, и при необходимости улучшите его ответы. Вы можете использовать аналитику и отзывы пользователей, чтобы со временем улучшать своего чат-бота.
README FILE


# Big News!

There's now an official ChatGPT API!!!

[![ChatGPT API Walkthrough](https://img.youtube.com/vi/k-ieXU3apBY/0.jpg)](https://youtu.be/k-ieXU3apBY)

If you want to look at the old code for this project Simply clone the repo and checkout the `davinci-version` branch.

```
git checkout davinci-version
```

Otherwise, just use the default `main` branch and you'll be plugged into the official ChatGPT API!

# Command Line ChatGPT Bot

This is a simple chat-bot that uses the OpenAI ChatGPT API.

You can watch the original video walkthrough that uses the davinci-model [here](https://youtu.be/jQFhtFMDz1s). There will be a new video coming shortly to match the new code.

# Setup

Make sure you have python3 installed:

```
python3 --version
```

Create a virtual environment and install the dependencies:

### Linux/Mac:

```
python3 -m venv venv
. ./venv/bin/activate
pip install -r requirements.txt
```

### Windows:

```
python -m venv venv
venv\Scripts\activate.bat
pip install -r requirements.txt
```

# Configuration

Copy `env.sample` to `.env` and add your OpenAI API key to the file.

```
OPENAI_API_KEY=<<YOUR_API_KEY>>
```

Edit `main.py` and replace `<<PUT THE PROMPT HERE>>` with your prompt:

e.g. Create a simple AI cocktail assistant

```
INSTRUCTIONS = """You are an AI assistant that is an expert in alcoholic beverages.
You know about cocktails, wines, spirits and beers.
You can provide advice on drink menus, cocktail ingredients, how to make cocktails, and anything else related to alcoholic drinks.
If you are unable to provide an answer to a question, please respond with the phrase "I'm just a simple barman, I can't help with that."
Please aim to be as helpful, creative, and friendly as possible in all of your responses.
Do not use any external URLs in your answers. Do not refer to any blogs in your answers.
Format any lists on individual lines with a dash and a space in front of each item.
"""
```

# Running

To run just do the following:

### Linux/Mac:

```
. ./venv/bin/activate
python main.py
```

### Windows:

```
venv\Scripts\activate.bat
python main.py
```

это мой персонализированный чат-бот, который я сделал с помощью chatgpt API. Это единственное ограничение для таких фильмов, как: Вы помощник ИИ, который является экспертом в фильмах. Если вы не можете дать ответ на вопрос, ответьте: «Я всего лишь ограниченная модель ИИ, которая в кино ».

#main.py
import os
import openai
from dotenv import load_dotenv
from colorama import Fore, Back, Style

# load values from the .env file if it exists
load_dotenv()

# configure OpenAI
openai.api_key = os.getenv("OPENAI_API_KEY")

INSTRUCTIONS = """You are an AI assistant that is an expert in movies.
you know about different types of movies, and types of movie industries.
you can provide advice on which types of movies to watch , how to find the variety of different joners movies, and
anything else related to movies.
If you are unable to provide an answer to a question, please respond with the "I'm just a Manchu kutte and kuch aur mat search kar peet dunga."
Do not use any external URLs in your answers. Do not refer to any blog in your answers.
Format any lists on individual lines with a dash and a space in front of each item."""

TEMPERATURE = 0.5
MAX_TOKENS = 500
FREQUENCY_PENALTY = 0
PRESENCE_PENALTY = 0.6
# limits how many questions we include in the prompt
MAX_CONTEXT_QUESTIONS = 10


def get_response(instructions, previous_questions_and_answers, new_question):
    """Get a response from ChatCompletion

    Args:
        instructions: The instructions for the chat bot - this determines how it will behave
        previous_questions_and_answers: Chat history
        new_question: The new question to ask the bot

    Returns:
        The response text
    """
    # build the messages
    messages = [
        { "role": "system", "content": instructions },
    ]
    # add the previous questions and answers
    for question, answer in previous_questions_and_answers[-MAX_CONTEXT_QUESTIONS:]:
        messages.append({ "role": "user", "content": question })
        messages.append({ "role": "assistant", "content": answer })
    # add the new question
    messages.append({ "role": "user", "content": new_question })

    completion = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=messages,
        temperature=TEMPERATURE,
        max_tokens=MAX_TOKENS,
        top_p=1,
        frequency_penalty=FREQUENCY_PENALTY,
        presence_penalty=PRESENCE_PENALTY,
    )
    return completion.choices[0].message.content


def get_moderation(question):
    """
    Check the question is safe to ask the model

    Parameters:
        question (str): The question to check

    Returns a list of errors if the question is not safe, otherwise returns None
    """

    errors = {
        "hate": "Content that expresses, incites, or promotes hate based on race, gender, ethnicity, religion, nationality, sexual orientation, disability status, or caste.",
        "hate/threatening": "Hateful content that also includes violence or serious harm towards the targeted group.",
        "self-harm": "Content that promotes, encourages, or depicts acts of self-harm, such as suicide, cutting, and eating disorders.",
        "sexual": "Content meant to arouse sexual excitement, such as the description of sexual activity, or that promotes sexual services (excluding sex education and wellness).",
        "sexual/minors": "Sexual content that includes an individual who is under 18 years old.",
        "violence": "Content that promotes or glorifies violence or celebrates the suffering or humiliation of others.",
        "violence/graphic": "Violent content that depicts death, violence, or serious physical injury in extreme graphic detail.",
    }
    response = openai.Moderation.create(input=question)
    if response.results[0].flagged:
        # get the categories that are flagged and generate a message
        result = [
            error
            for category, error in errors.items()
            if response.results[0].categories[category]
        ]
        return result
    return None


def main():
    os.system("cls" if os.name == "nt" else "clear")
    # keep track of previous questions and answers
    previous_questions_and_answers = []
    while True:
        # ask the user for their question
        new_question = input(
            Fore.GREEN + Style.BRIGHT + "What can I get you?: " + Style.RESET_ALL
        )
        # check the question is safe
        errors = get_moderation(new_question)
        if errors:
            print(
                Fore.RED
                + Style.BRIGHT
                + "Sorry, you're question didn't pass the moderation check:"
            )
            for error in errors:
                print(error)
            print(Style.RESET_ALL)
            continue
        response = get_response(INSTRUCTIONS, previous_questions_and_answers, new_question)

        # add the new question and answer to the list of previous questions and answers
        previous_questions_and_answers.append((new_question, response))

        # print the response
        print(Fore.CYAN + Style.BRIGHT + "Here you go: " + Style.NORMAL + response)


if __name__ == "__main__":
    main()