stardust-eques SASAKI28 commited on
Commit
8177664
·
verified ·
1 Parent(s): 5e69796

Create app_streaming (#1)

Browse files

- Create app_streaming (b5f8948369ead9d2faf1347e09c5b5acaa82e3ce)


Co-authored-by: Sasaki Shunsuke <SASAKI28@users.noreply.huggingface.co>

Files changed (1) hide show
  1. app_streaming +71 -0
app_streaming ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import uuid
3
+ from vllm import AsyncLLMEngine, AsyncEngineArgs, SamplingParams
4
+ import gradio as gr
5
+
6
+ # モジュールレベルで一度だけイベントループを作成
7
+ _loop = asyncio.new_event_loop()
8
+ asyncio.set_event_loop(_loop)
9
+
10
+ # 非同期エンジンの初期化
11
+ en_args = AsyncEngineArgs(
12
+ model="EQUES/JPharmatron-7B",
13
+ enforce_eager=True
14
+ )
15
+ model = AsyncLLMEngine.from_engine_args(en_args)
16
+
17
+ # 非同期でトークン生成をストリーミングするジェネレータ
18
+ async def astream_generate(prompt: str):
19
+ previous_text = ""
20
+ async for request_output in model.generate(
21
+ prompt,
22
+ SamplingParams(temperature=0.0, max_tokens=512),
23
+ request_id=str(uuid.uuid4())
24
+ ):
25
+ full_text = request_output.outputs[0].text
26
+ new_chunk = full_text[len(previous_text):]
27
+ previous_text = full_text
28
+ yield new_chunk
29
+
30
+ # Gradio 用の応答関数(同期ジェネレータ)
31
+ def respond(user_input, history):
32
+ history = history or []
33
+ # システムプロンプトと過去履歴を組み立て
34
+ base_prompt = "以下は親切で何でも答えてくれるAIアシスタントとの会話です。\n"
35
+ for u, b in history:
36
+ base_prompt += f"ユーザー: {u}\nアシスタント: {b}\n"
37
+ base_prompt += f"ユーザー: {user_input}\nアシスタント:"
38
+
39
+ # ユーザー発話と空応答を履歴に追加
40
+ history.append((user_input, ""))
41
+
42
+ # 単一のイベントループを使ってストリーミング
43
+ agen = astream_generate(base_prompt)
44
+ try:
45
+ while True:
46
+ chunk = _loop.run_until_complete(agen.__anext__())
47
+ # 最新の履歴にトークンを追加
48
+ history[-1] = (user_input, history[-1][1] + chunk)
49
+ yield history, history
50
+ except StopAsyncIteration:
51
+ return
52
+
53
+ # Gradio UI 定義
54
+ with gr.Blocks() as demo:
55
+ gr.Markdown("# 💊 製薬に関する質問をしてみてください。")
56
+ gr.Markdown("※ ストリーミングデモ用コードです。")
57
+
58
+ chatbot = gr.Chatbot()
59
+ msg = gr.Textbox(label="あなたのメッセージ")
60
+ clear = gr.Button("チャット履歴をクリア")
61
+ state = gr.State([])
62
+
63
+ msg.submit(respond, [msg, state], [chatbot, state])
64
+ clear.click(lambda: ([], []), None, [chatbot, state])
65
+
66
+ # エントリポイント
67
+ def main():
68
+ demo.launch()
69
+
70
+ if __name__ == "__main__":
71
+ main()