前置作業 在 OpenAI 註冊一個帳號,並且在 API keys 頁面產生一個 API 金鑰。
建立專案 建立專案。
1 2 mkdir openai-cli-python-examplecd openai-cli-python-example
建立虛擬環境 建立虛擬環境。
啟動虛擬環境。
1 source .venv/bin/activate
初始化版本控制 建立 .gitignore
檔。
1 2 3 .venv/ __pycache__/ .env
初始化版本控制。
將所有修改添加到暫存區。
提交修改。
1 git commit -m "Initial commit"
指定遠端儲存庫位址。
推送程式碼到遠端儲存庫。
安裝 Ruff 格式化工具 新增 requirements.txt
檔。
修改 requirements.txt
檔,添加 ruff
依賴套件。
安裝依賴套件。
1 pip install -r requirements.txt
新增 ruff.toml
檔。
1 2 3 4 5 line-length = 120 indent-width = 4 [format] quote-style = "double"
新增 .vscode/settings.json
檔。
1 2 3 4 5 6 7 8 { "editor.formatOnSave" : true , "editor.codeActionsOnSave" : { "source.fixAll" : "explicit" , "source.organizeImports" : "explicit" } , "editor.defaultFormatter" : "charliermarsh.ruff" }
提交修改。
1 2 git add . git commit -m "Add ruff dependency"
實作文字補全 修改 requirements.txt
檔,添加 requests
和 dotenv
依賴套件。
安裝依賴套件。
1 pip install -r requirements.txt
新增 .env.example
檔。
新增 .env
檔。
1 OPENAI_API_KEY=your-openai-api-key
建立 main.py
檔。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 import argparseimport osimport requestsfrom dotenv import load_dotenvload_dotenv() def get_completion (prompt: str ): """Send a request to the OpenAI API and retrieve a response""" api_key = os.getenv("OPENAI_API_KEY" ) if not api_key: print ("Error: Environment variable OPENAI_API_KEY is not set" ) return url = "https://api.openai.com/v1/completions" headers = {"Content-Type" : "application/json" , "Authorization" : f"Bearer {api_key} " } data = { "model" : "gpt-3.5-turbo-instruct" , "prompt" : prompt, "max_tokens" : 100 , "temperature" : 1 , } response = requests.post(url, headers=headers, json=data) print (f"API Response:\n{response.text} " ) def main (): parser = argparse.ArgumentParser(description="CLI tool for OpenAI API requests" ) parser.add_argument("prompt" , type =str , help ="Prompt text to send to OpenAI API" ) args = parser.parse_args() get_completion(args.prompt) if __name__ == "__main__" : main()
執行程式。
響應如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 API Response: { "id" : "cmpl-BFKZqv3El4WEskkNr1vzDKGHjtk69" , "object" : "text_completion" , "created" : 1742993718, "model" : "gpt-3.5-turbo-instruct:20230824-v2" , "choices" : [ { "text" : "\n\n我是一個人工智能,沒有生理感受,所以並不需要好壞的。謝謝關心。" , "index" : 0, "logprobs" : null, "finish_reason" : "stop" } ], "usage" : { "prompt_tokens" : 6, "completion_tokens" : 42, "total_tokens" : 48 } }
程式碼
參考資料