from typing import Any, Dict, List def main(args: Any) -> None: """ Main method. Parameters ---------- args : Any Command line arguments. """ messages: List[Dict[str, str]] = [ {"role": "system", "content": "あなたは日本語でコミュニケーションできる有能なアシスタントです。"} ] openai.api_key = os.getenv("OPENAI_API_KEY") _ = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=messages ) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 try: while True: request = input("You: ") messages.append({"role": "user", "content": request}) if len(messages) > 10: messages.pop(0) response = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=messages ) if response is not None: finish_reason = response["choices"][0]["finish_reason"] if finish_reason == "stop": answer = response["choices"][0]["message"]["content"] messages.append({"role": "assistant", "content": answer}) print(f"Assistant: {answer}") else: print(f"error: Invalid finish reason: {finish_reason}.") break else: print("error: response is null.") break except KeyboardInterrupt: pass except Exception as err: print(err) if __name__ == '__main__': main(None) 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 環境変数 "OPEN_AI_APIKEY" にAPIキーを設定し、以下のPythonスクリプトを実行