0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

記事投稿キャンペーン 「AI、機械学習」

Chat Completions APIで会話履歴を踏まえストリーミングで応答を得るAPIリクエスト

Last updated at Posted at 2023-11-04

ライブラリインストール

pip install openai

ソースコード

import openai

response = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Hello! I'm John."},
        {"role": "assistant", "content": "Hello John! How can I assist you today?"},
        {"role": "user", "content": "Do you know my name?"},
    ],
    stream=True
)

#print(response)
for chunk in response:
    choice = chunk["choices"][0]
    if choice["finish_reason"] is None:
        print(choice["delta"]["content"])

レスポンス(少しずつ表示されていく)

Yes
,
 you
 mentioned
 that
 your
 name
 is
 John
.
 How
 can
 I
 assist
 you
,
 John
?

解説

  • messagesのところに会話の履歴を繋げていく
    • roleの意味
      • system
        • LLMの動作についての指示
      • user
        • ユーザー
      • assistant
        • AI(APIのレスポンス)
  • streamパラメータをTrueとするとレスポンスがストリーミングレスポンスになる(少しずつ表示されていく)
    • 受け取り方がfor文での処理になる
    • ストリーミングレスポンスでなければ、print(response)で表示可能
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?