seawolf2357 commited on
Commit
a8032bb
1 Parent(s): a6549b1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -15
app.py CHANGED
@@ -43,22 +43,36 @@ async def respond(
43
  "stream": True
44
  }
45
 
46
- async with aiohttp.ClientSession() as session:
47
- async with session.post("https://api-inference.huggingface.co/v1/chat/completions", headers=headers, json=payload) as response:
48
- try:
 
49
  async for chunk in response.content:
50
  if chunk:
51
- chunk_data = chunk.decode('utf-8')
52
- response_json = json.loads(chunk_data)
53
- if "choices" in response_json:
54
- content = response_json["choices"][0]["message"]["content"]
55
- yield content
56
- except json.JSONDecodeError:
57
- pass
58
- except StopAsyncIteration:
59
- pass
60
- finally:
61
- pass # 스트림 종료 시 아무것도 하지 않음
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
  theme = "Nymbo/Nymbo_Theme"
64
 
@@ -70,7 +84,7 @@ footer {
70
 
71
  demo = gr.ChatInterface(
72
  css=css,
73
- fn=respond,
74
  theme=theme,
75
  additional_inputs=[
76
  gr.Textbox(value="AI Assistant Role", label="System message"),
 
43
  "stream": True
44
  }
45
 
46
+ try:
47
+ async with aiohttp.ClientSession() as session:
48
+ async with session.post("https://api-inference.huggingface.co/v1/chat/completions", headers=headers, json=payload) as response:
49
+ response_text = ""
50
  async for chunk in response.content:
51
  if chunk:
52
+ try:
53
+ chunk_data = chunk.decode('utf-8')
54
+ response_json = json.loads(chunk_data)
55
+ if "choices" in response_json:
56
+ content = response_json["choices"][0]["message"]["content"]
57
+ response_text += content
58
+ yield response_text
59
+ except json.JSONDecodeError:
60
+ continue
61
+
62
+ if not response_text:
63
+ yield "I apologize, but I couldn't generate a response. Please try again."
64
+ except Exception as e:
65
+ yield f"An error occurred: {str(e)}"
66
+
67
+ memory[-1] = (message, response_text)
68
+
69
+ async def chat(message, history, system_message, max_tokens, temperature, top_p):
70
+ response = ""
71
+ async for chunk in respond(message, history, system_message, max_tokens, temperature, top_p):
72
+ response = chunk
73
+ yield response
74
+
75
+
76
 
77
  theme = "Nymbo/Nymbo_Theme"
78
 
 
84
 
85
  demo = gr.ChatInterface(
86
  css=css,
87
+ fn=chat,
88
  theme=theme,
89
  additional_inputs=[
90
  gr.Textbox(value="AI Assistant Role", label="System message"),