openaiapi1.py
事前に以下が必要
Python 3.10+
SSL の cert
これは環境によって必要だったり不要だったりするsta.icon
たぶんプロキシサーバがある環境で必要になる
二つのファイルをつくっておく
質問を書くファイル askai.md
過去の質問と回答を貯めるログファイル askailog.md
ちなみにaskaiはAsk AI
このスクリプト(下記)
実行はpython openaiapi1.py
が、ランチャーをつくるのも良い
windowsだと、
code:ai.bat
@echo off
python openaiapi1.py
SSLが要るなら
code:ai.bat
@echo off
python openaiapi1.py --use-ssl hogehoge.crt
こうすればaiと実行するだけで実行できる
以下は実行例
(askai.mdに質問書いてから実行する)
terminal
https://gyazo.com/af8dc0140754f0b596375c67104c9a7f
askai.md
https://gyazo.com/b1251e7b2b7bd4e9019baefe602ac7fa
askailog.md
https://gyazo.com/8abd3084bd4d5e84f22a090da1f954dd
code:openaiapi1.py
import datetime
import os
import openai
# ========
def parse_arguments():
import argparse
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument('--use-ssl', default=None)
args = parser.parse_args()
return args
# ========
def ask(prompt):
response = openai.ChatCompletion.create(
model='gpt-3.5-turbo',
messages=[
{'role': 'user', 'content': prompt},
]
)
return response
def todaystr_long():
todaydt = datetime.datetime.today()
datestr = todaydt.strftime('%Y/%m/%d')
timestr = todaydt.strftime('%H:%M:%S')
wd = todaydt.weekday()
return f'{datestr} {dow_e} {timestr}'
def file2str(filepath):
ret = ''
with open(filepath, encoding='utf8', mode='r') as f:
ret = f.read()
return ret
def str2file(filepath, s):
with open(filepath, encoding='utf8', mode='w') as f:
f.write(s)
class Outputter:
def __init__(self, prompt, response):
self._response = response
self._todaystr = todaystr_long()
self._prompt = prompt
self._answer = response.choices0.message.content self._answer_role = response.choices0.message.role self._consumed_prompt_token = response.usage.prompt_tokens
self._consumed_completion_token = response.usage.completion_tokens
def out(self):
raise NotImplementedError
class Logger(Outputter):
def __init__(self, prompt, response):
super().__init__(prompt, response)
self._logfilepath = 'PLEASE_GIVE_EXPLICITLY__askailog.md'
def set_target_filepath(self, markdown_filepath):
self._logfilepath = markdown_filepath
def out(self):
prependee = f"""# {self._todaystr} {self._consumed_prompt_token} {self._consumed_completion_token}
{self._prompt}
{self._answer}"""
logcontent = file2str(self._logfilepath)
outstr = f"""{prependee}
{logcontent}"""
str2file(self._logfilepath, outstr)
class Stdouter(Outputter):
def __init__(self, prompt, response):
super().__init__(prompt, response)
def out(self):
print('=== prompt ===')
print(self._prompt)
print('')
print('=== answer ===')
print(self._answer)
print('')
print(f'tokens : {self._consumed_prompt_token} {self._consumed_completion_token}')
# ========
args = parse_arguments()
if args.use_ssl:
q = file2str('askai.md')
prompt=q
response = ask(prompt)
stdouter = Stdouter(prompt, response)
logger = Logger(prompt, response)
logger.set_target_filepath('askailog.md')
logger.out()
stdouter.out()