Berguna untuk menentukan apakah response dikirim dalam bentuk chunk atau tidak. Tipe parameter stream adalah boolean, secara default false. Jika diset true, maka tokens akan dikirim sebagai data-only server-sent events, stream akan diakhiri dengan message data: [DONE].
Pada modul-modul sebelumnya kita mendapatkan response data utuh secara keseluruhan. Pada modul ini kita akan coba mendapatkan response data dalam bentuk potongan.
import openai from dotenv import dotenv_values config = dotenv_values(".env") openai.api_key = config["OPENAI_KEY"] prompt = "write me a poem about traveling alone" for data in openai.Completion.create( model = "text-davinci-003", prompt = prompt, max_tokens= 300, stream = True ): print(data.choices[0].text, end="", flush=True)
Pada code diatas, potongan response akan disimpan dalam variable data yang kemudian kita tampilkan menggunakan perintah print. Jika Anda jalankan demo code diatas, dapat dilihat, response akan di tampilkan ke screen bertahap, sesuai response stream yang diterima.
Berikut contoh response yang dihasilkan.
Hit the open road.
To wander, explore, and roam.
I'm off on an adventure,
All alone, with no entourage.
I leave my worries far behind,
Instant freedom of a kind.
The choices are mine own,
The wild, the unknown.
No one to tell where I'm heading;
the possibilities unending.
Airplane, train, or cruise ship,
Venture out and start to dip.
Stay in hostels or hotels,
Discover stories to tell.
Meeting friendly faces,
Away from all familiar places.
Through cities, towns, and countrysides,
So many stories to find.
My heart full of joy and life,
As I travel alone and strive.
Salah satu penggunaan stream jika ekspektasi ukuran data response yang besar.