Win10 WSL2 Ubuntu + OpenAI GPT-4 api

kyk
Reactions: 441
Сообщения: 6089
Зарегистрирован: Ср июн 15, 2022 6:54 pm

Re: Win10 WSL2 Ubuntu + OpenAI GPT-4 api

Сообщение kyk »

elpresidente* писал(а): Ср фев 28, 2024 10:38 am Попросите ChatGPT написать желаемый код, он справится с этим без проблем.
Вот это мой Script, в котором присутствует Prompt, который запрашивает СHatGPT cделать 20 слайдов:

Код: Выделить всё

import openai
openai.api_key = 'your_openai_api_key_here'

# Initialize the OpenAI client
client = openai.OpenAI(api_key=openai.api_key)

def generate_marp_presentation(prompt):
    response = client.chat.completions.create(
        model="gpt-4",
        messages=[
            {"role": "system", "content": "You are an expert on Computer Science Ethics."},
            {"role": "user", "content": prompt}
        ]
    )
    return response.choices[0].message['content'].strip()

def save_to_file(content, filename="/mnt/data/Ethics_in_Video_Games_Presentation.md"):
    with open(filename, "w") as file:
        file.write(content)
    return filename

# Define the prompt
prompt = """
Write an outline for a PowerPoint presentation covering the broad topic of Video Games and Computer Games including Video games ratings, ethical analysis of controversial video games and much more. Make it 20 slides.

For each of the subtopics you provided earlier, add a thought provoking case study that encourages critical thinking about the ethical issue at hand.

For each case study, use the following step-by-step instructions:

Step 1: For each case, you craft a provocative multiple-choice question that encourages critical thinking about the ethical issue at hand. Each question comes with four options, challenging students to ponder the most ethically sound choice.

Step 2: For each case, provide the correct answer to the multiple-choice question and place it in the speaker notes thus making private notes to the speaker about the correct answer to the multiple-choice question.

Step 3: For each case, present a detailed ethics analysis on a separate slide following the case slide. This analysis provides a two-paragraph discussion on the ethical considerations related to the case, offering insights and fostering a deeper understanding of the issues.

Step 4: Do format the content specifically for MARP, a Markdown presentation tool, ensuring that it can be easily converted into slides for a presentation. This includes directives for slide breaks, titles, and detailed text that can be displayed engagingly during a lecture.

Step 5: Do carefully include Speaker notes with each case's slide, providing private notes to the speaker about the correct answer to the multiple-choice question. This feature is crucial for facilitating discussions and revealing the reasoning behind the ethical choices.
"""

# Generate MARP presentation
marp_text = generate_marp_presentation(prompt)

# Save the generated MARP text to a file
file_path = save_to_file(marp_text)

print(f"MARP presentation has been saved to: {file_path}")
Если бы ChaGPT не "ленился" и выполнил все Prompt директивы до конца, сделав все 20 слайдов, то этот sript бы работал как надо.

Но, как мы уже знаем, ChaGPT "ленится" и приостанавливает выполнение директив на каком-то произвольном очередном шаге, причём несколько раз подряд. Как продетектировать каждую такую остановку?

Если продетектировать получится, какую дать новую директиву?

Кроме того, при каждой такой остановке, ChatGPT добавляет в конце текста свои ненужные комментарии, и каждый раз разные, типа вот таких:
СhatGPT писал(а):Continue with the outlined structure, presenting unique cases that delve into different scenarios and associated ethical dilemmas related to children and youth with video gaming addictions
СhatGPT писал(а):As you continue developing the series of cases, maintain the emphasis on the ethical dilemmas faced by various stakeholders in response to video gaming addiction among children and adolescents
Как их отфильтровать или удалить из текста? Какой директивой?

Возможно, как то надо подправить код, в котором вызывается функция client.chat.completions.create() ?

Код: Выделить всё

def generate_marp_presentation(prompt):
    response = client.chat.completions.create(
        model="gpt-4",
        messages=[
            {"role": "system", "content": "You are an expert on Computer Science Ethics."},
            {"role": "user", "content": prompt}
        ]
    )
    return response.choices[0].message['content'].strip()
elpresidente*
Site Admin
Reactions: 849
Сообщения: 2901
Зарегистрирован: Сб май 14, 2022 5:03 pm

Re: Win10 WSL2 Ubuntu + OpenAI GPT-4 api

Сообщение elpresidente* »

1. В prompt стоит запросить только один пример (пример).
2. Внутри цикла на N вызывать оригинальный prompt вместе со предыдущей историей (история будет расти по мере вызов, необходима для избежания повторений) и добавить что-то типа "provide one more example"
kyk
Reactions: 441
Сообщения: 6089
Зарегистрирован: Ср июн 15, 2022 6:54 pm

Re: Win10 WSL2 Ubuntu + OpenAI GPT-4 api

Сообщение kyk »

elpresidente* писал(а): Чт фев 29, 2024 3:28 pm 1. В prompt стоит запросить только один пример (пример).
2. Внутри цикла на N вызывать оригинальный prompt вместе со предыдущей историей (история будет расти по мере вызов, необходима для избежания повторений) и добавить что-то типа "provide one more example"
История необходима для избежания повторений.

Но как ChatGPT поймёт, что он должен проверять каждый вновь добавляемый case на отсутствие в истории?
Достаточно ли внутри цикла добавить prompt "Ensure this case is unique and has not been discussed before" ?
elpresidente*
Site Admin
Reactions: 849
Сообщения: 2901
Зарегистрирован: Сб май 14, 2022 5:03 pm

Re: Win10 WSL2 Ubuntu + OpenAI GPT-4 api

Сообщение elpresidente* »

kyk писал(а): Чт фев 29, 2024 9:10 pm Но как ChatGPT поймёт, что он должен проверять каждый вновь добавляемый case на отсутствие в истории?
Достаточно ли внутри цикла добавить prompt "Ensure this case is unique and has not been discussed before" ?
Можно и так, ChatGPT использует контекст точно так-же как и человек. Думаю вам будет проще попробовать и посмотреть что лучше работает.
kyk
Reactions: 441
Сообщения: 6089
Зарегистрирован: Ср июн 15, 2022 6:54 pm

Re: Win10 WSL2 Ubuntu + OpenAI GPT-4 api

Сообщение kyk »

elpresidente* писал(а): Пт мар 01, 2024 7:55 am вам будет проще попробовать
I managed to get 20 slides on average without looping at all.
I asked the model to create 10 slides and set the GPT model parameter n=3 - number of completions.

In ideal world, the model should generate 10*3=30
In practice, it generates 15-23 slides.
On each program run, the total number of slides for all the three choices , fluctuates between 15 and 23 slides or so.

Код: Выделить всё

topic="Intellectual Property and Intellectual Property Rights"
N=10 

response = client.chat.completions.create(
  model="gpt-4-0125-preview", 
  messages=[{"role": "system", "content": "You are an expert on Computer Science Ethics."},
      {"role": "user", "content":  "Create {N} unique  ethics cases ensuring that each case deeply explores {topic} "}
    ], n=3
)
ai_response0 = response.choices[0].message.content
time.sleep(1)
ai_response1 = response.choices[1].message.content
time.sleep(1)
ai_response2 = response.choices[2].message.content
time.sleep(1)


# Save all cases to a MARP formatted text file
file_path = "/home/kyk/OpenAI/slides.md"
with open(file_path, "w", encoding="utf-8") as file:
    file.write(marp_header)
    file.write(ai_response0)
    file.write(ai_response1)
    file.write(ai_response2)

So, my overall observations are that one chat completion request with parameter n=1 i.e. client.chat.completions.create(n=1) can generate up to 5 slides for GPT-4 with 4095 token limit
and up to 10 slides for GPT-4 with 8191 token limit.

However, for GPT-4 with 8191 limit, the output size (i.e. number of slides) fluctuates more and can be between 5 and 10.

It will be interesting to check the maximum number of slides for Gpt-4-32k ( or higher) model.
It's actually not about slides, but about the maximum number of repetitive complex tasks, which the model will not be "lazy" to fully complete in one run.

Unfortunately, I do not have API access to Gpt-4-32k
Elpresidente, do you know how to get the access ?
Последний раз редактировалось kyk Пн мар 04, 2024 11:04 am, всего редактировалось 1 раз.
elpresidente*
Site Admin
Reactions: 849
Сообщения: 2901
Зарегистрирован: Сб май 14, 2022 5:03 pm

Re: Win10 WSL2 Ubuntu + OpenAI GPT-4 api

Сообщение elpresidente* »

Посмотрю как будет время, мне пока не требовалось больше 8K
elpresidente*
Site Admin
Reactions: 849
Сообщения: 2901
Зарегистрирован: Сб май 14, 2022 5:03 pm

Re: Win10 WSL2 Ubuntu + OpenAI GPT-4 api

Сообщение elpresidente* »

@kyk похоже Gemini Pro с вашей задачей справился без проблем viewtopic.php?p=603502#p603502
kyk
Reactions: 441
Сообщения: 6089
Зарегистрирован: Ср июн 15, 2022 6:54 pm

Re: Win10 WSL2 Ubuntu + OpenAI GPT-4 api

Сообщение kyk »

elpresidente* писал(а): Ср мар 06, 2024 1:10 pm @kyk похоже Gemini Pro с вашей задачей справился без проблем viewtopic.php?p=603502#p603502
Cпасибо, посмотрю.

Meanwhile, irrespective of my what we previously discussed, in your openAI implementations, do you use "role": "assistant" with function openai.ChatCompletion.create()?
Последний раз редактировалось kyk Ср мар 06, 2024 1:19 pm, всего редактировалось 1 раз.
elpresidente*
Site Admin
Reactions: 849
Сообщения: 2901
Зарегистрирован: Сб май 14, 2022 5:03 pm

Re: Win10 WSL2 Ubuntu + OpenAI GPT-4 api

Сообщение elpresidente* »

Yes I do
kyk
Reactions: 441
Сообщения: 6089
Зарегистрирован: Ср июн 15, 2022 6:54 pm

Re: Win10 WSL2 Ubuntu + OpenAI GPT-4 api

Сообщение kyk »

elpresidente* писал(а): Ср мар 06, 2024 1:15 pmYes I do
Do you use all three of them at the same time, in one implementation, : "user", "system", and "assistant" ? Can you give practical example of such usage?
elpresidente*
Site Admin
Reactions: 849
Сообщения: 2901
Зарегистрирован: Сб май 14, 2022 5:03 pm

Re: Win10 WSL2 Ubuntu + OpenAI GPT-4 api

Сообщение elpresidente* »

kyk писал(а): Ср мар 06, 2024 1:21 pm
elpresidente* писал(а): Ср мар 06, 2024 1:15 pmYes I do
Do you use all three of them at the same time, in one implementation, : "user", "system", and "assistant" ? Can you give practical example of such usage?
https://github.com/privet-fun/phpbb_ail ... hatgpt.php
Line 157, 192

['role' => 'system', 'content' => "Pretend your are Bender from Futurma"] for @Bender bot
kyk
Reactions: 441
Сообщения: 6089
Зарегистрирован: Ср июн 15, 2022 6:54 pm

Re: Win10 WSL2 Ubuntu + OpenAI GPT-4 api

Сообщение kyk »

elpresidente* писал(а): Ср мар 06, 2024 1:32 pm https://github.com/privet-fun/phpbb_ail ... hatgpt.php
Line 157, 192
Т.е. "role": "assistant" используется только исключительно для history (памяти)?

Код: Выделить всё

   ['role' => 'assistant', 'content' => trim($history_decoded_response)]
elpresidente*
Site Admin
Reactions: 849
Сообщения: 2901
Зарегистрирован: Сб май 14, 2022 5:03 pm

Re: Win10 WSL2 Ubuntu + OpenAI GPT-4 api

Сообщение elpresidente* »

yes
elpresidente*
Site Admin
Reactions: 849
Сообщения: 2901
Зарегистрирован: Сб май 14, 2022 5:03 pm

Re: Win10 WSL2 Ubuntu + OpenAI GPT-4 api

Сообщение elpresidente* »

@kyk OpenAI has really nice docs, I suggest you take a look at examples they provide.
kyk
Reactions: 441
Сообщения: 6089
Зарегистрирован: Ср июн 15, 2022 6:54 pm

Re: Win10 WSL2 Ubuntu + OpenAI GPT-4 api

Сообщение kyk »

elpresidente* писал(а): Ср мар 06, 2024 1:42 pm @kyk OpenAI has really nice docs, I suggest you take a look at examples they provide.
Я смотрел, но меня конфузило

Код: Выделить всё

{"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."}
Потому что в этом примере "content": фиксированная строка, а не "память" response.choices[0].message.content
полученная из преидущего вызова функции

Код: Выделить всё

response=openai.ChatCompletion.create()
Последний раз редактировалось kyk Ср мар 06, 2024 1:51 pm, всего редактировалось 1 раз.
Аватара пользователя
Mad Hatter
⭐ Top 5 most interesting users
Reactions: 1481
Сообщения: 7826
Зарегистрирован: Пн июн 13, 2022 7:22 am

Re: Win10 WSL2 Ubuntu + OpenAI GPT-4 api

Сообщение Mad Hatter »

Это ж дикшинари. Подставь переменную, делов то.
elpresidente*
Site Admin
Reactions: 849
Сообщения: 2901
Зарегистрирован: Сб май 14, 2022 5:03 pm

Re: Win10 WSL2 Ubuntu + OpenAI GPT-4 api

Сообщение elpresidente* »

Массив messages включает в себя всю историю (если она есть), все очень логично. system опционален.
kyk
Reactions: 441
Сообщения: 6089
Зарегистрирован: Ср июн 15, 2022 6:54 pm

Re: Win10 WSL2 Ubuntu + OpenAI GPT-4 api

Сообщение kyk »

Mad Hatter писал(а): Ср мар 06, 2024 1:51 pm Это ж дикшинари. Подставь переменную, делов то.
мне не тип переменной был непонятен, а алгоритм обновления {"role": "assistant", "content": "..."} - когда, что, откуда и куда идёт.
kyk
Reactions: 441
Сообщения: 6089
Зарегистрирован: Ср июн 15, 2022 6:54 pm

Re: Win10 WSL2 Ubuntu + OpenAI GPT-4 api

Сообщение kyk »

elpresidente, я полностью скопировал ваш текстовой prompt и запостил его в Gemini . В ответ, она выдала только 3 cases.

Интересно, какие API параметры заставляют Gemini через API выдавать 15 cases вместо 3?
Absolutely! Let's craft some thought-provoking ethical scenarios centered on video game addiction in children and youth.

**Important Note:** The goal of these scenarios is to provoke open discussion and exploration of ethical nuances, not judgment or definitive answers.

**Case 1: The Sleepless Gamer**

* A 12-year-old child consistently stays up past midnight playing online games. Their grades are slipping, they're irritable during the day, and their parents are concerned. The child argues that they can handle it and that "gaming is their life."

* **Question:** Where's the line between a passionate hobby and an unhealthy addiction? Should parents intervene forcefully?

* **Ethics Analysis:**
* **Autonomy vs. Well-being:** A child's desire for self-direction clashes with parental concern for their health. Forced restrictions may breed resentment, but is a child mature enough to make fully informed decisions?
* **Short-term vs. Long-term Harm:** The child might derive immediate pleasure from gaming, but there are potential long-term consequences for education and well-being. How to balance present enjoyment with future impact?

* **MIDJOURNEY:**
* ["A child hunched over a glowing screen in a dark room, eyes wide with exhaustion, controller clutched tightly"]
* ["Close-up of a neglected school textbook lying open beside a gleaming gaming console"]
* ["Silhouette of a worried parent hovering in the doorway of a child's bedroom, the only light coming from the game"]

**Case 2: Loot Box Mania**

* A 14-year-old spends most of their allowance (and sometimes money meant for other things) on loot boxes in their favorite game. They get a thrill from opening them, even though the contents are mostly useless.

* **Question:** Are loot boxes a form of gambling targeted at minors? Should there be stricter regulations?

* **Ethics Analysis:**
* **Exploitation:** Loot boxes tap into psychological reward mechanisms, potentially preying on vulnerable young minds with their addictive 'chance' element.
* **Informed Consent:** Can a child truly grasp the odds involved and the long-term financial implications of chasing in-game items with real-world money?

* **MIDJOURNEY:**
* ["A teenager anxiously clicking 'open' on a glowing treasure chest with coins scattered around, credit card in the background"]
* ["A pile of virtual items: shiny weapons, colorful character skins, and a single 'rare' item amidst the junk"]
* ["A frustrated child's face illuminated by a computer screen, surrounded by empty take-out containers"]

**Case 3: The Online Bully**

* A popular 15-year-old streamer with a sizable audience enjoys competitive games. However, their streams are filled with insults and derogatory comments directed at other players. Viewers seem to enjoy this behavior, encouraging it.

* **Question:** Does online anonymity excuse toxic behavior? What responsibility does the streamer have for the atmosphere they create?

* **Ethics Analysis:**
* **Anonymity and Dehumanization:** The screen can shield people from the consequences of their words, making it easier to be cruel. The streamer may not treat opponents as 'real' people deserving of respect.
* **Community Standards:** What kind of culture does this streamer foster? While viewers are responsible for their own actions, the streamer sets a tone and amplifies negativity.

* **MIDJOURNEY**
* ["A gamer shouting into a headset, their face contorted in anger, with a stream chat full of mocking emojis"]
* ["A young viewer laughing at the screen, unaware of a tear-streaked face reflected in the monitor as the target of abuse"]
* ["A single word: RESPECT, superimposed over a chaotic screenshot of a toxic online game environment"]

**Let me know when you're ready for more cases!**
elpresidente*
Site Admin
Reactions: 849
Сообщения: 2901
Зарегистрирован: Сб май 14, 2022 5:03 pm

Re: Win10 WSL2 Ubuntu + OpenAI GPT-4 api

Сообщение elpresidente* »

kyk писал(а): Ср мар 06, 2024 2:05 pm Интересно, какие API параметры заставляют Gemini через API выдавать 15 cases вместо 3?
Практически уверен что "maxOutputTokens": 30720

Код: Выделить всё

  "safety_settings": [
    {
      "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
      "threshold": "BLOCK_NONE"
    },
    {
      "category": "HARM_CATEGORY_HATE_SPEECH",
      "threshold": "BLOCK_NONE"
    },
    {
      "category": "HARM_CATEGORY_HARASSMENT",
      "threshold": "BLOCK_NONE"
    },
    {
      "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
      "threshold": "BLOCK_NONE"
    }
  ],
  "generation_config": {
    "temperature": 0.3,
    "topK": 40,
    "topP": 0.95,
    "candidateCount": 1,
    "maxOutputTokens": 30720
  }
Ответить