seawolf2357 commited on
Commit
8954f0b
β€’
1 Parent(s): 1831164

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -37
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
- self.bg_task = self.loop.create_task(self.log_live_message()) # 둜그 μž‘μ—…μ„ μœ„ν•œ λ°±κ·ΈλΌμš΄λ“œ νƒœμŠ€ν¬ μ‹œμž‘
 
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
- # 동기 ν•¨μˆ˜λ₯Ό λΉ„λ™κΈ°λ‘œ μ²˜λ¦¬ν•˜κΈ° μœ„ν•œ 래퍼 μ‚¬μš©, stream=True둜 λ³€κ²½
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'))