Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,6 +3,7 @@ import logging
|
|
| 3 |
import os
|
| 4 |
from huggingface_hub import InferenceClient
|
| 5 |
import asyncio
|
|
|
|
| 6 |
|
| 7 |
# 로깅 설정
|
| 8 |
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s:%(levelname)s:%(name)s: %(message)s', handlers=[logging.StreamHandler()])
|
|
@@ -16,7 +17,7 @@ intents.messages = True
|
|
| 16 |
hf_client = InferenceClient("CohereForAI/c4ai-command-r-plus", token=os.getenv("HF_TOKEN"))
|
| 17 |
|
| 18 |
# 특정 채널 ID
|
| 19 |
-
SPECIFIC_CHANNEL_ID = int(os.getenv("DISCORD_CHANNEL_ID"))
|
| 20 |
|
| 21 |
# 대화 히스토리를 저장할 변수
|
| 22 |
conversation_history = []
|
|
@@ -24,44 +25,26 @@ conversation_history = []
|
|
| 24 |
class MyClient(discord.Client):
|
| 25 |
def __init__(self, *args, **kwargs):
|
| 26 |
super().__init__(*args, **kwargs)
|
| 27 |
-
self.is_processing = False
|
| 28 |
|
| 29 |
async def on_ready(self):
|
| 30 |
logging.info(f'{self.user}로 로그인되었습니다!')
|
| 31 |
-
|
|
|
|
| 32 |
|
| 33 |
async def on_message(self, message):
|
| 34 |
if message.author == self.user:
|
| 35 |
-
logging.info('자신의 메시지는 무시합니다.')
|
| 36 |
return
|
| 37 |
-
|
| 38 |
if message.channel.id != SPECIFIC_CHANNEL_ID:
|
| 39 |
-
logging.info(f'메시지가 지정된 채널 {SPECIFIC_CHANNEL_ID}이 아니므로 무시됩니다.')
|
| 40 |
return
|
| 41 |
-
|
| 42 |
if self.is_processing:
|
| 43 |
-
logging.info('현재 메시지를 처리 중입니다. 새로운 요청을 무시합니다.')
|
| 44 |
return
|
| 45 |
-
|
| 46 |
-
logging.debug(f'Receiving message in channel {message.channel.id}: {message.content}')
|
| 47 |
-
|
| 48 |
-
if not message.content.strip(): # 메시지가 빈 문자열인 경우 처리
|
| 49 |
-
logging.warning('Received message with no content.')
|
| 50 |
-
await message.channel.send('질문을 입력해 주세요.')
|
| 51 |
-
return
|
| 52 |
-
|
| 53 |
-
self.is_processing = True # 메시지 처리 시작 플래그 설정
|
| 54 |
-
|
| 55 |
try:
|
| 56 |
response = await generate_response(message.content)
|
| 57 |
await message.channel.send(response)
|
| 58 |
finally:
|
| 59 |
-
self.is_processing = False
|
| 60 |
-
|
| 61 |
-
async def log_live_message(self):
|
| 62 |
-
while True:
|
| 63 |
-
logging.info("Live") # 로그로 "Live" 메시지 출력
|
| 64 |
-
await asyncio.sleep(60) # 1분마다 반복
|
| 65 |
|
| 66 |
async def generate_response(user_input):
|
| 67 |
system_message = "DISCORD에서 사용자들의 질문에 답하는 'AI 채널' 전담 어시스턴트이고 너의 이름은 'AI 방장'이다. 대화를 계속 이어가고, 이전 응답을 참고하십시오."
|
|
@@ -73,32 +56,36 @@ async def generate_response(user_input):
|
|
| 73 |
반드시 한글로 답변하십시오.
|
| 74 |
"""
|
| 75 |
|
| 76 |
-
|
| 77 |
global conversation_history
|
| 78 |
conversation_history.append({"role": "user", "content": user_input})
|
| 79 |
-
logging.debug(f'Conversation history updated: {conversation_history}')
|
| 80 |
-
|
| 81 |
messages = [{"role": "system", "content": f"{system_prefix} {system_message}"}] + conversation_history
|
| 82 |
-
logging.debug(f'Messages to be sent to the model: {messages}')
|
| 83 |
|
| 84 |
-
|
| 85 |
-
loop = asyncio.get_event_loop()
|
| 86 |
-
response = await loop.run_in_executor(None, lambda: hf_client.chat_completion(
|
| 87 |
-
messages, max_tokens=1000, stream=True, temperature=0.7, top_p=0.85))
|
| 88 |
-
|
| 89 |
-
# 스트리밍 응답을 처리하는 로직 추가
|
| 90 |
full_response = []
|
| 91 |
for part in response:
|
| 92 |
-
logging.debug(f'Part received from stream: {part}') # 스트리밍 응답의 각 파트 로깅
|
| 93 |
if part.choices and part.choices[0].delta and part.choices[0].delta.content:
|
| 94 |
full_response.append(part.choices[0].delta.content)
|
| 95 |
|
| 96 |
full_response_text = ''.join(full_response)
|
| 97 |
-
logging.debug(f'Full model response: {full_response_text}')
|
| 98 |
-
|
| 99 |
conversation_history.append({"role": "assistant", "content": full_response_text})
|
| 100 |
return full_response_text
|
| 101 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
# 디스코드 봇 인스턴스 생성 및 실행
|
| 103 |
discord_client = MyClient(intents=intents)
|
| 104 |
discord_client.run(os.getenv('DISCORD_TOKEN'))
|
|
|
|
| 3 |
import os
|
| 4 |
from huggingface_hub import InferenceClient
|
| 5 |
import asyncio
|
| 6 |
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
| 7 |
|
| 8 |
# 로깅 설정
|
| 9 |
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s:%(levelname)s:%(name)s: %(message)s', handlers=[logging.StreamHandler()])
|
|
|
|
| 17 |
hf_client = InferenceClient("CohereForAI/c4ai-command-r-plus", token=os.getenv("HF_TOKEN"))
|
| 18 |
|
| 19 |
# 특정 채널 ID
|
| 20 |
+
SPECIFIC_CHANNEL_ID = int(os.getenv("DISCORD_CHANNEL_ID"))
|
| 21 |
|
| 22 |
# 대화 히스토리를 저장할 변수
|
| 23 |
conversation_history = []
|
|
|
|
| 25 |
class MyClient(discord.Client):
|
| 26 |
def __init__(self, *args, **kwargs):
|
| 27 |
super().__init__(*args, **kwargs)
|
| 28 |
+
self.is_processing = False
|
| 29 |
|
| 30 |
async def on_ready(self):
|
| 31 |
logging.info(f'{self.user}로 로그인되었습니다!')
|
| 32 |
+
# Run the web server as a background task
|
| 33 |
+
asyncio.create_task(run_server())
|
| 34 |
|
| 35 |
async def on_message(self, message):
|
| 36 |
if message.author == self.user:
|
|
|
|
| 37 |
return
|
|
|
|
| 38 |
if message.channel.id != SPECIFIC_CHANNEL_ID:
|
|
|
|
| 39 |
return
|
|
|
|
| 40 |
if self.is_processing:
|
|
|
|
| 41 |
return
|
| 42 |
+
self.is_processing = True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
try:
|
| 44 |
response = await generate_response(message.content)
|
| 45 |
await message.channel.send(response)
|
| 46 |
finally:
|
| 47 |
+
self.is_processing = False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
async def generate_response(user_input):
|
| 50 |
system_message = "DISCORD에서 사용자들의 질문에 답하는 'AI 채널' 전담 어시스턴트이고 너의 이름은 'AI 방장'이다. 대화를 계속 이어가고, 이전 응답을 참고하십시오."
|
|
|
|
| 56 |
반드시 한글로 답변하십시오.
|
| 57 |
"""
|
| 58 |
|
| 59 |
+
|
| 60 |
global conversation_history
|
| 61 |
conversation_history.append({"role": "user", "content": user_input})
|
|
|
|
|
|
|
| 62 |
messages = [{"role": "system", "content": f"{system_prefix} {system_message}"}] + conversation_history
|
|
|
|
| 63 |
|
| 64 |
+
response = await asyncio.get_event_loop().run_in_executor(None, lambda: hf_client.chat_completion(messages, max_tokens=1000))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
full_response = []
|
| 66 |
for part in response:
|
|
|
|
| 67 |
if part.choices and part.choices[0].delta and part.choices[0].delta.content:
|
| 68 |
full_response.append(part.choices[0].delta.content)
|
| 69 |
|
| 70 |
full_response_text = ''.join(full_response)
|
|
|
|
|
|
|
| 71 |
conversation_history.append({"role": "assistant", "content": full_response_text})
|
| 72 |
return full_response_text
|
| 73 |
|
| 74 |
+
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
|
| 75 |
+
def do_GET(self):
|
| 76 |
+
logging.info(f"Received GET request from {self.address_string()}")
|
| 77 |
+
self.send_response(200)
|
| 78 |
+
self.send_header('Content-type', 'text/html')
|
| 79 |
+
self.end_headers()
|
| 80 |
+
self.wfile.write(b"Hello, this is a simple server!")
|
| 81 |
+
|
| 82 |
+
async def run_server():
|
| 83 |
+
server_address = ('', 8000)
|
| 84 |
+
httpd = HTTPServer(server_address, SimpleHTTPRequestHandler)
|
| 85 |
+
logging.info('HTTP Server Running on port 8000...')
|
| 86 |
+
with httpd:
|
| 87 |
+
httpd.serve_forever()
|
| 88 |
+
|
| 89 |
# 디스코드 봇 인스턴스 생성 및 실행
|
| 90 |
discord_client = MyClient(intents=intents)
|
| 91 |
discord_client.run(os.getenv('DISCORD_TOKEN'))
|