はじめに
LLMや画像生成をするために,APIサーバーを作ろうとするとGoogle ColobやローカルPCを使うとサービス化およびpublic化が難しいためクラウドGPUを使用したいと考えていました。
その中で Modalをいうサービスを見つけたので,触ってみます
環境
実行
準備
サンプルコードが提供されているので,ベースはサンプルコードから作っていきます
06_gpu_and_ml/chatgpt/chatgpt_streaming.pyをベースに実行をしていきたいのですが,そのまま実行すると以下のエラーが出るため,少し変更をします
File "/usr/local/lib/python3.9/site-packages/openai/api_resources/abstract/engine_api_resource.py", line 151, in create ) = cls.__prepare_create_request( File "/usr/local/lib/python3.9/site-packages/openai/api_resources/abstract/engine_api_resource.py", line 108, in __prepare_create_request requestor = api_requestor.APIRequestor( File "/usr/local/lib/python3.9/site-packages/openai/api_requestor.py", line 139, in __init__ self.api_key = key or util.default_api_key() File "/usr/local/lib/python3.9/site-packages/openai/util.py", line 186, in default_api_key raise openai.error.AuthenticationError( openai.error.AuthenticationError: No API key provided. You can set your API key in code using 'openai.api_key = <API-KEY>', or you can set the environment variable OPENAI_API_KEY=<API-KEY>). If your API key is stored in a file, you can point the openai module at it with 'openai.api_key_path = <PATH>'. You can generate API keys in the OpenAI web interface. See https://platform.openai.com/account/api-keys for details.
実際にChatGPT APIを叩く関数の中でAPIキーを設定します
@stub.function() def stream_chat(prompt: str): import openai import os openai.api_key = os.environ["CHATGPT_KEY"] for chunk in openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[{"role": "user", "content": prompt}], stream=True, ): content = chunk["choices"][0].get("delta", {}).get("content") if content is not None: yield content
プロンプトと実行コードも記載します
default_prompt = ( "まどマギの中で一番可愛いキャラを理由をつけて100文字程度で教えてください。この時の口調をオタクっぽい口調にしてください" ) @stub.local_entrypoint() def main(prompt: str = default_prompt): for part in stream_chat.remote_gen(prompt=prompt): print(part, end="")
結果
いい感じに出力されています
「ほむらちゃんが一番可愛いよ!彼女は、強くて知的でありながらも、不器用な一面を持っていて、そのギャップがたまらないんだ!」 ✓ App completed.