# 聊天項目 這個聊天項目展示了如何使用 GitHub Models 構建一個聊天助手。 以下是完成後的項目樣子: ![聊天應用](../../../translated_images/screenshot.0a1ee0d123df681b4501eb53ffb267519fcc20aa653eabecef1e7561ddfb1cab.hk.png) 一些背景資訊,使用生成式 AI 構建聊天助手是一個學習 AI 的好方法。在這節課中,你將學會如何將生成式 AI 整合到網頁應用中,讓我們開始吧。 ## 連接生成式 AI 在後端,我們使用 GitHub Models。這是一個很棒的服務,可以免費使用 AI。前往它的 Playground,獲取與你選擇的後端語言對應的代碼。以下是 [GitHub Models Playground](https://github.com/marketplace/models/azure-openai/gpt-4o-mini/playground) 的樣子: ![GitHub Models AI Playground](../../../translated_images/playground.d2b927122224ff8ff4028fc842176e353c339147d8925455f36c92fb1655c477.hk.png) 如我們所說,選擇 "Code" 標籤和你選擇的運行時環境。 ![Playground 選擇](../../../translated_images/playground-choice.1d23ba7d407f47584c9f446c77f0bcf70cae794cc9c8d7849a3cca4a3693e6c4.hk.png) ### 使用 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"。後者是為了讓前端傳遞問題給後端。 要整合 *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