如何在Django項目中集成OpenAI GPT模型

作者選擇了直接救濟計劃作為為捐款而寫計劃的捐款對象。

介紹

OpenAI GPT 模型由於廣泛用於生成文本內容,例如起草電子郵件、回答客戶服務常見問題和語言翻譯等各種任務,而變得受歡迎。

這些 GPT 模型通常通過 OpenAI 發布的聊天機器人 ChatGPT,或通過提供更多控制功能的 API 和庫來使用。本教程將指導您如何在 Django Web 項目中使用 OpenAI API 利用這些模型。您將學習如何使用不同參數調用 ChatCompletion API,以及如何格式化和利用其響應。

完成本教程後,您將創建一個 Django 端點,當調用該端點時,它會向 OpenAI 發送請求,使用提供的單詞構建一個短故事並返回其響應。

先決條件

完成本教程,您需要:

  1. 一個現有的Django項目。如果您從頭開始,可以按照如何設置Django開發環境教程來設置Django項目。

  2. 一個OpenAI帳戶:前往OpenAI平台網站,尋找“註冊”按鈕。註冊後,您必須驗證您的電子郵件地址並輸入個人信息。

  3. 一個OpenAI API密鑰:設置完您的帳戶後,登錄並從您的儀表板中導航到API密鑰部分。點擊“創建新的密鑰”。您的API密鑰將生成,類似於sk-abcdefghijklmnop。請確保將此密鑰保存在安全的位置,因為您將無法再次看到它。

  4. OpenAI Python 套件:如果您已按照第一個先決條件中的教程進行操作,您應該已經在名為django-apps的目錄中啟用了名為env的虛擬環境。確保您的虛擬環境處於活動狀態,方法是確認其名稱出現在終端提示符的括號中。如果未啟用,您可以通過運行以下命令手動啟用它:

sammy@ubuntu:$ .env/bin/activate

django-apps目錄中的終端。一旦您的環境處於活動狀態,運行以下命令安裝 OpenAI Python 套件:

(env)sammy@ubuntu:$ pip install openai

步驟 1 — 調用 OpenAI

在這一步,您將向 OpenAI 客戶端添加您的 OpenAI API 金鑰並對 ChatCompletion API 進行一個簡單的 API 調用。您還將檢查您從 API 獲得的響應。

要開始,打開您的 Python 解釋器:

(env)sammy@ubuntu:$ python

首先,導入 OpenAI 客戶端並將您的 API 金鑰添加到客戶端:

from openai import OpenAI
client = OpenAI(api_key="your-api-key")

"your-api-key" 替換為您從 OpenAI 平台獲得的實際 API 金鑰。

現在,讓我們對 ChatCompletion API 進行一個 API 調用。使用 chat.completions.create() 方法:

response = client.chat.completions.create(model="gpt-3.5-turbo", messages=[{"role": "user", "content": "count 1 to 10"}])

在上面的代碼中,我們指定要使用的 模型gpt-3.5-turbo,添加了一個單獨的 消息 對象,其中包含角色 user(其他選項是 systemassistant)以及內容 / 提示 count 1 to 10

要查看從 API 調用的響應,您可以打印響應消息,該消息應包含一個漂亮的小列表,其中包含數字 1 到 10:

print(response.choices[0].message.content)

輸出:

Output
1, 2, 3, 4, 5, 6, 7, 8, 9, 10

恭喜!您已成功對 OpenAI 進行了一個簡單的 API 調用並檢索到了響應。我們將格式化並利用 API 響應來創建下一步中的一個短故事。

第 2 步 — 使用參數

現在您已成功地對ChatCompletion API進行了簡單的API調用,讓我們探索如何使用參數來自定義模型的行為。有幾個可用的參數可以讓您控制文本的生成。我們將看看以下三個。

1. 溫度:溫度參數決定了生成的內容有多隨機。較高的溫度值,如0.8,將產生更多樣化和有創意的回應,而較低的溫度值,如0.1,將產生更相似的回應。例如:

response = client.chat.completions.create(model="gpt-3.5-turbo", messages=[{"role": "user", "content": "mention five words"}], temperature=0.1)
print(response.choices[0].message.content)
Output
1. Apple 2. Elephant 3. Sunshine 4. Adventure 5. Serenity

讓我們再試一次temperature=0.1,看看新生成的文本:

response = client.chat.completions.create(model="gpt-3.5-turbo", messages=[{"role": "user", "content": "mention five words"}], temperature=0.1)
print(response.choices[0].message.content)
Output
1. Apple 2. Elephant 3. Sunshine 4. Adventure 5. Serenity

文本結果相同。現在,讓我們兩次嘗試temperature=0.8

response = client.chat.completions.create(model="gpt-3.5-turbo", messages=[{"role": "user", "content": "mention five words"}], temperature=0.8)
print(response.choices[0].message.content)
cat, apple, guitar, sky, book
response = client.chat.completions.create(model="gpt-3.5-turbo", messages=[{"role": "user", "content": "mention five words"}], temperature=0.8)
print(response.choices[0].message.content)
Output
1. Apple 2. Sunshine 3. Happiness 4. Love 5. Technology

2. 最大標記數:這允許您限制生成文本的長度。設置特定值可以確保響應不會超過一定數量的標記。標記與響應中的詞數成比例。例如:

response = client.chat.completions.create(model="gpt-3.5-turbo", messages=[{"role": "user", "content": "mention five words"}], max_tokens=10)
print(response.choices[0].message.content)
Output
1. Apple 2. Car

將值更改為20:

response = client.chat.completions.create(model="gpt-3.5-turbo", messages=[{"role": "user", "content": "mention five words"}], max_tokens=20)
print(response.choices[0].message.content)
Output
1. Apple 2. Car 3. Music 4. Ocean 5. Love

3. 流:這決定了回應是否應該流式傳輸還是返回。當設置為True時,API響應將以流的形式傳輸,這意味著您將在生成時以片段方式接收輸出。這對於長對話或實時應用程序非常有用。要啟用流式傳輸,請將帶有值Truestream參數添加到API調用中。例如:

response = client.chat.completions.create(model="gpt-3.5-turbo", messages=[{"role": "user", "content": "mention five words"}], stream=True)
collected_messages = []
for chunk in response:
...   chunk_message = chunk.choices[0].delta.content
...   if chunk_message is not None:
...     collected_messages.append(chunk_message)
print(collected_messages)
Output
['', 'cat', '\n', 'book', '\n', 'computer', '\n', 'sun', '\n', 'water']

在上面的代碼中,chunk_message 變量保存了API返回的每個分塊中的消息內容。在將每個分塊添加到 collected_messages 列表之前,我們會檢查該分塊是否為 None,因為最後一個分塊的內容通常是 None

利用這些參數可以自定義模型的行為,控制生成的回應,以更好地適應您的應用程序或項目。嘗試不同的值以達到所需的結果。

在下一步中,我們將以系統提示的形式為模型提供一些上下文。

步驟3 — 創建系統提示

在這一步中,我們將結合我們所學的所有信息,創建一個為 GPT 模型提供上下文的系統提示,告訴它其目的並指定其規則。

首先,讓我們創建一個 Python 模塊,其中包含一個處理此任務的函數。關閉解釋器,並在您的 Django 項目目錄中創建一個名為 story_generator.py 的新文件。

(env)sammy@ubuntu:$ touch ~/my_blog_app/blog/blogsite/story_generator.py

接下來,您可以將 OpenAI API 密鑰添加到您的環境變量中,這樣您就不必直接將其添加到 Python 文件中:

(env)sammy@ubuntu:$ export OPENAI_KEY="your-api-key"

打開 story_generator.py,在其中創建一個 openai 客戶端並定義一個名為 generate_story 的函數,該函數接受一組詞作為輸入:

~/my_blog_app/blog/blogsite/story_generator.py
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_KEY"])
def generate_story(words):
    # 调用 OpenAI API 生成故事
    response = get_short_story(words)
    # 格式化并返回响应
    return format_response(response)

在这个函数中,我们调用一个单独的函数,get_short_story,来向 OpenAI 发送 API 请求获取故事,然后调用另一个函数,format_response,来格式化 API 的响应。

现在,让我们专注于 get_short_story 函数。将以下内容添加到你的 story_generator.py 文件的末尾:

~/my_blog_app/blog/blogsite/story_generator.py
def get_short_story(words):
    # 构造系统提示
    system_prompt = f"""You are a short story generator.
    Write a short story using the following words: {words}.
    Do not go beyond one paragraph."""
    # 发起 API 调用
    response = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[{
            "role": "user",
            "content": system_prompt
        }],
        temperature=0.8,
        max_tokens=1000
    )

    # 返回 API 响应
    return response

在这个函数中,我们首先设置系统提示,这会告诉模型它需要执行的任务,并指定故事的长度。然后我们将这个系统提示传递给 ChatCompletion API 并返回其响应。

最后,我们可以实现 format_response 函数。将以下内容添加到你的 story_generator.py 文件的末尾:

~/my_blog_app/blog/blogsite/story_generator.py
def format_response(response):
    # 从响应中提取生成的故事
    story = response.choices[0].message.content
    # 移除任何不需要的文本或格式
    story = story.strip()
    # 返回格式化后的故事
    return story

您現在可以通過調用generate_story函數來測試這些功能,將一組詞作為其參數傳遞並打印其響應。將以下內容添加到您的story_generator.py文件底部:

print(generate_story("cat, book, computer, sun, water"))

現在保存並退出文件。運行腳本以查看生成的故事:

(env) sammy@ubuntu:$ python ~/my_blog_app/blog/blogsite/story_generator.py

輸出:

In a cozy corner of a sunlit room, a fluffy cat named Whiskers lounged lazily next to a towering bookshelf. Amongst the rows of books, a curious computer hummed softly. As the sun streamed through the window, casting a warm glow, Whiskers noticed a small water stain on the shelf. Intrigued, the cat pawed at the book closest to the mark. As if guided by fate, the book opened to reveal a hidden compartment containing a glittering diamond necklace. With the secret now unveiled, Whiskers embarked on an unexpected adventure, where the sun, water, and the power of knowledge merged into a thrilling tale of mystery and discovery.

非常有趣!由於我們將從Django視圖調用generate_story函數,因此讓我們刪除帶有print語句的行。從您的story_generator.py文件中刪除突出顯示的行:

print(generate_story("cat, book, computer, sun, water"))

請隨意嘗試使用系統提示進行實驗,並添加更多上下文和規則以改進生成的故事。

繼續下一步,將story_generator模塊集成到您的Django項目中。

步驟4 – 與後端視圖集成:

您必須創建一個Django視圖和URL路由,將story_generator模塊集成到您的Django項目中。在視圖中,您將從請求中提取預期的單詞,調用generate_story函數,並返回響應。

首先,打開您Django應用程式目錄中的文件views.py。導入必要的模塊並添加名為generate_story_from_words的視圖函數:

~/my_blog_app/blog/blogsite/views.py
from django.http import JsonResponse
from .story_generator import generate_story

def generate_story_from_words(request):
    words = request.GET.get('words') # 從請求中提取預期的詞語
    story = generate_story(words) # 使用提取的詞語調用 generate_story 函數
    return JsonResponse({'story': story}) # 將故事作為 JSON 響應返回

接下來,打開 urls.py 文件並添加一個用於 generate_story_from_words 視圖的 URL 模式:

~/my_blog_app/blog/blogsite/urls.py
urlpatterns = [
    # 其他 URL 模式...
    path('generate-story/', views.generate_story_from_words, name='generate-story'),
]

現在,您可以請求 /generate-story/ 端點。例如,要使用 curl 進行測試,您可以將預期的詞語作為查詢參數進行 GET 請求。打開您的終端並運行以下命令:

(env)sammy@ubuntu:$ curl "http://your_domain/generate-story/?words=cat,book,computer,sun,water"

請確保將 "http://your_domain" 替換為您的 Django 項目托管的實際域名。單詞 "cat,book,computer,sun,water" 代表您想要生成故事的預期詞語。您可以將它們更改為任何您喜歡的詞語。

運行命令後,您應該會看到來自服務器的響應,其中將包含生成的故事:

(env)sammy@ubuntu:$ curl "http://your_domain/generate-story/?words="cat,book,computer,sun,water"

輸出:

{"story": "Once upon a time, in a cozy little cottage nestled amidst a dense forest, a curious cat named Whiskers sat by the window, basking in the warm rays of the sun. As Whiskers lazily flicked his tail, his eyes caught sight of a dusty book lying on a nearby shelf. Intrigued, he carefully jumped onto the shelf, causing a cascade of books to tumble down, one opening up to reveal a hidden compartment. Inside, Whiskers discovered an ancient computer, its screen flickering to life as he brushed against the power button. Mesmerized by the glowing screen, Whiskers ventured into a world of virtual landscapes, where he roamed freely, chasing digital fish and pausing to admire breathtaking waterfalls. Lost in this newfound adventure, Whiskers discovered the wonders of both the tangible and virtual worlds, realizing that true exploration knows no bounds."}

結論

完成本教程後,您已經學會如何使用OpenAI API將OpenAI GPT模型整合到您的Django項目中。您已經調用了ChatCompletion API,通過使用溫度和最大標記等參數來自定義模型的行為,並創建了一個系統提示來為模型提供上下文。您還將story_generator模塊整合到了您的Django項目中。現在,您可以通過請求帶有預期單詞作為查詢參數的/generate-story/端點來生成短篇故事。

為了進一步增強您的Django項目,您可以探索OpenAI API的其他功能,並嘗試使用不同的系統提示和參數來生成獨特和創意的故事。

Source:
https://www.digitalocean.com/community/tutorials/how-to-integrate-openai-gpt-models-in-your-django-project