# チャットプロジェクト このチャットプロジェクトでは、GitHub Modelsを使用してチャットアシスタントを構築する方法を示します。 完成したプロジェクトは以下のようになります:
チャットアプリ
少し背景を説明すると、生成AIを使用してチャットアシスタントを構築することは、AIについて学び始めるのに最適な方法です。このレッスンを通じて、生成AIをウェブアプリに統合する方法を学びます。それでは始めましょう。 ## 生成AIへの接続 バックエンドにはGitHub Modelsを使用します。これは、無料でAIを利用できる素晴らしいサービスです。プレイグラウンドにアクセスして、選択したバックエンド言語に対応するコードを取得してください。以下は[GitHub Models Playground](https://github.com/marketplace/models/azure-openai/gpt-4o-mini/playground)の例です。
GitHub Models AI Playground
先ほど述べたように、「Code」タブと選択したランタイムを選びます。
プレイグラウンドの選択
### Pythonを使用する場合 この場合、Pythonを選択します。すると以下のコードが選ばれます: ```python """Run this model in Python > pip install openai """ import os from openai import OpenAI # To authenticate with the model you will need to generate a personal access token (PAT) in your GitHub settings. # Create your PAT token by following instructions here: https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens client = OpenAI( base_url="https://models.github.ai/inference", api_key=os.environ["GITHUB_TOKEN"], ) response = client.chat.completions.create( messages=[ { "role": "system", "content": "", }, { "role": "user", "content": "What is the capital of France?", } ], model="openai/gpt-4o-mini", temperature=1, max_tokens=4096, top_p=1 ) print(response.choices[0].message.content) ``` このコードを少し整理して再利用可能にしましょう: ```python def call_llm(prompt: str, system_message: str): response = client.chat.completions.create( messages=[ { "role": "system", "content": system_message, }, { "role": "user", "content": prompt, } ], model="openai/gpt-4o-mini", temperature=1, max_tokens=4096, top_p=1 ) return response.choices[0].message.content ``` この`call_llm`関数を使用すると、プロンプトとシステムプロンプトを渡して結果を返すことができます。 ### AIアシスタントのカスタマイズ AIアシスタントをカスタマイズしたい場合は、以下のようにシステムプロンプトを設定して動作を指定できます: ```python call_llm("Tell me about you", "You're Albert Einstein, you only know of things in the time you were alive") ``` ## Web APIを通じて公開 素晴らしいですね。AI部分が完成したので、これをWeb APIに統合する方法を見てみましょう。Web APIにはFlaskを使用しますが、他のウェブフレームワークでも問題ありません。以下はそのコードです: ### Pythonを使用する場合 ```python # api.py from flask import Flask, request, jsonify from llm import call_llm from flask_cors import CORS app = Flask(__name__) CORS(app) # * example.com @app.route("/", methods=["GET"]) def index(): return "Welcome to this API. Call POST /hello with 'message': 'my message' as JSON payload" @app.route("/hello", methods=["POST"]) def hello(): # get message from request body { "message": "do this taks for me" } data = request.get_json() message = data.get("message", "") response = call_llm(message, "You are a helpful assistant.") return jsonify({ "response": response }) if __name__ == "__main__": app.run(host="0.0.0.0", port=5000) ``` ここでは、Flask APIを作成し、デフォルトルート「/」と「/chat」を定義しています。「/chat」はフロントエンドが質問を送信するために使用されます。 *llm.py*を統合するには以下を行います: - `call_llm`関数をインポート: ```python from llm import call_llm from flask import Flask, request ``` - 「/chat」ルートから呼び出す: ```python @app.route("/hello", methods=["POST"]) def hello(): # get message from request body { "message": "do this taks for me" } data = request.get_json() message = data.get("message", "") response = call_llm(message, "You are a helpful assistant.") return jsonify({ "response": response }) ``` ここでは、受信リクエストを解析してJSONボディから`message`プロパティを取得します。その後、以下のようにLLMを呼び出します: ```python response = call_llm(message, "You are a helpful assistant") # return the response as JSON return jsonify({ "response": response }) ``` これで必要なことは完了です。 ## Corsの設定 バックエンドとフロントエンドが異なるポートで動作するため、フロントエンドがバックエンドにアクセスできるようにCORS(クロスオリジンリソース共有)を設定する必要があります。 ### Pythonを使用する場合 *api.py*には以下のようなコードがあります: ```python from flask_cors import CORS app = Flask(__name__) CORS(app) # * example.com ``` 現在はすべてのオリジン("*")を許可するように設定されていますが、これは安全ではないため、本番環境では制限する必要があります。 ## プロジェクトを実行する プロジェクトを実行するには、まずバックエンドを起動し、その後フロントエンドを起動します。 ### Pythonを使用する場合 *llm.py*と*api.py*がありますが、バックエンドを動作させるには以下を行います: - 依存関係をインストール: ```sh cd backend python -m venv venv source ./venv/bin/activate pip install openai flask flask-cors openai ``` - APIを起動: ```sh python api.py ``` Codespacesを使用している場合は、エディタの下部にある「Ports」に移動し、右クリックして「Port Visibility」を選択し、「Public」を選択してください。 ### フロントエンドの作業 APIが動作しているので、次にフロントエンドを作成します。最低限のフロントエンドを作成し、段階的に改善していきます。*frontend*フォルダに以下を作成してください: ```text backend/ frontend/ index.html app.js styles.css ``` まず**index.html**を作成します: ```html