Last active
April 28, 2023 04:57
-
-
Save ryu22e/601b0d82eb190f70edf28b7e49e10110 to your computer and use it in GitHub Desktop.
OpenAIライブラリ(Python)サンプル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import argparse | |
from enum import Enum | |
from typing import assert_never | |
import openai | |
class Mode(Enum): | |
normal = "normal" | |
kansai = "kansai" | |
ojosama = "ojosama" | |
samurai = "samurai" | |
def __str__(self): | |
return self.value | |
@property | |
def text(self): | |
match self: | |
case self.normal: | |
return "" | |
case self.kansai: | |
return "関西人風に話して下さい。一人称は「ワイ」です。" | |
case self.ojosama: | |
return "お嬢様風に話して下さい。一人称は「わたくし」です。" | |
case self.samurai: | |
return "侍風に話して下さい。一人称は「拙者」です。" | |
case _: | |
assert_never(self) | |
def main(args): | |
answers = [] | |
mode = args.mode.text | |
while question := input("あなたの質問: "): | |
messages = [ | |
{"role": "user", "content": question}, | |
] | |
if mode: | |
messages.append({"role": "system", "content": mode}) | |
if len(answers) > 0: | |
messages.extend(answers) | |
completion = openai.ChatCompletion.create( | |
model="gpt-3.5-turbo", | |
messages=messages, | |
) | |
answer = completion.choices[0].message.content.strip() | |
print("回答: " + answer) | |
answers.append({"role": "assistant", "content": answer}) | |
if __name__ == "__main__": | |
parser = argparse.ArgumentParser( | |
prog="OpenAI Practice", | |
) | |
parser.add_argument( | |
"-m", "--mode", type=Mode, choices=list(Mode), default=Mode.normal | |
) | |
args = parser.parse_args() | |
main(args) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
openai==0.27.2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Python.3.11以上が必要。
以下サイトからAPIキーを生成して環境変数
OPENAI_API_KEY
に設定すること。https://platform.openai.com/account/api-keys