streaming.py 1.13 KB
Newer Older
1
2
3
4
"""
Usage:
python3 streaming.py
"""
zhyncs's avatar
zhyncs committed
5

Lianmin Zheng's avatar
Lianmin Zheng committed
6
import asyncio
zhyncs's avatar
zhyncs committed
7

Lianmin Zheng's avatar
Lianmin Zheng committed
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import sglang as sgl


@sgl.function
def multi_turn_question(s, question_1, question_2):
    s += sgl.system("You are a helpful assistant.")
    s += sgl.user(question_1)
    s += sgl.assistant(sgl.gen("answer_1", max_tokens=256))
    s += sgl.user(question_2)
    s += sgl.assistant(sgl.gen("answer_2", max_tokens=256))


sgl.set_default_backend(sgl.OpenAI("gpt-3.5-turbo"))


def stream_a_variable():
    state = multi_turn_question.run(
        question_1="What is the capital of the United States?",
        question_2="List two local attractions.",
zhyncs's avatar
zhyncs committed
27
        stream=True,
Lianmin Zheng's avatar
Lianmin Zheng committed
28
29
30
31
    )

    for out in state.text_iter(var_name="answer_2"):
        print(out, end="", flush=True)
Lianmin Zheng's avatar
Lianmin Zheng committed
32
    print("\n")
Lianmin Zheng's avatar
Lianmin Zheng committed
33
34
35
36
37
38


async def async_stream():
    state = multi_turn_question.run(
        question_1="What is the capital of the United States?",
        question_2="List two local attractions.",
zhyncs's avatar
zhyncs committed
39
        stream=True,
Lianmin Zheng's avatar
Lianmin Zheng committed
40
41
42
43
    )

    async for out in state.text_async_iter(var_name="answer_2"):
        print(out, end="", flush=True)
Lianmin Zheng's avatar
Lianmin Zheng committed
44
    print("\n")
Lianmin Zheng's avatar
Lianmin Zheng committed
45
46
47


if __name__ == "__main__":
Lianmin Zheng's avatar
Lianmin Zheng committed
48
    stream_a_variable()
Lianmin Zheng's avatar
Lianmin Zheng committed
49
    asyncio.run(async_stream())