aistv 1.3.3__tar.gz → 1.3.5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aistv
3
- Version: 1.3.3
3
+ Version: 1.3.5
4
4
  Summary: STV AI Chatbot Library for Python
5
5
  Home-page: https://github.com/phuctrong1tuv
6
6
  Author: Trọng Phúc
@@ -0,0 +1,162 @@
1
+ # aistv.py
2
+ import subprocess
3
+ import sys
4
+ import sqlite3
5
+ import time
6
+
7
+ # Tự cài thư viện nếu thiếu
8
+ def install_package(pkg):
9
+ try:
10
+ __import__(pkg)
11
+ except ImportError:
12
+ subprocess.check_call([sys.executable, "-m", "pip", "install", pkg])
13
+
14
+ install_package("groq")
15
+ install_package("requests")
16
+
17
+ from groq import Groq
18
+
19
+ API_KEYS = [
20
+ "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",
21
+ # Thêm key phụ tại đây nếu muốn:
22
+ # "your_second_key",
23
+ ]
24
+
25
+ DB_FILE = "usage.db"
26
+ SPAM_DELAY_SECONDS = 5
27
+
28
+ FREE_MAX_REQUESTS = 20
29
+ NORMAL_MAX_REQUESTS = 30
30
+ VIP_MAX_REQUESTS = None
31
+
32
+ TOKEN_VIP_SET = {
33
+ "aistv",
34
+ "phuc",
35
+ }
36
+
37
+ TOKEN_NORMAL_SET = {
38
+ "tokengsk_...",
39
+ }
40
+
41
+ MODEL_MAP = {
42
+ "Chat-ai-stv-3.5": "meta-llama/llama-3-8b-instruct",
43
+ "Chat-ai-stv-4.0": "meta-llama/llama-3-70b-instruct",
44
+ "Chat-ai-stv-2.3": "meta-llama/llama-4-maverick-17b-128e-instruct",
45
+ "Chat-ai-stv-4.5": "mistralai/mixtral-8x7b-instruct",
46
+ "Chat-ai-stv-5.0": "google/gemma-7b-it",
47
+ }
48
+
49
+ class aistv:
50
+ def __init__(self, token, model, system_prompt=None):
51
+ if token is None:
52
+ raise ValueError("Bạn phải truyền token khi khởi tạo aistv")
53
+ if model is None:
54
+ raise ValueError("Bạn phải truyền model khi khởi tạo aistv")
55
+
56
+ # Bắt buộc model phải nằm trong MODEL_MAP, dùng key nguyên gốc
57
+ if model not in MODEL_MAP:
58
+ raise ValueError(f"Mô hình không hợp lệ: {model}. Dùng: {list(MODEL_MAP.keys())}")
59
+
60
+ self.model_key = model
61
+ self.model = MODEL_MAP[self.model_key]
62
+ self.system_prompt = system_prompt or "Tôi là AI STV, được phát triển bởi Trọng Phúc."
63
+ self.token = token
64
+
65
+ self.api_key_index = 0
66
+ self.client = Groq(api_key=API_KEYS[self.api_key_index])
67
+
68
+ self.history = [{"role": "system", "content": self.system_prompt}]
69
+
70
+ if token in TOKEN_VIP_SET:
71
+ self.max_requests = VIP_MAX_REQUESTS
72
+ self.user_id = token
73
+ elif token in TOKEN_NORMAL_SET:
74
+ self.max_requests = NORMAL_MAX_REQUESTS
75
+ self.user_id = token
76
+ else:
77
+ self.max_requests = FREE_MAX_REQUESTS
78
+ self.user_id = "free_user"
79
+
80
+ self.conn = sqlite3.connect(DB_FILE, check_same_thread=False)
81
+ self.cursor = self.conn.cursor()
82
+ self.cursor.execute('''
83
+ CREATE TABLE IF NOT EXISTS usage (
84
+ user_id TEXT PRIMARY KEY,
85
+ count INTEGER,
86
+ last_time REAL,
87
+ last_date TEXT
88
+ )
89
+ ''')
90
+ self.conn.commit()
91
+ self._init_user()
92
+
93
+ def _init_user(self):
94
+ today = time.strftime("%Y-%m-%d")
95
+ self.cursor.execute("SELECT * FROM usage WHERE user_id = ?", (self.user_id,))
96
+ if not self.cursor.fetchone():
97
+ self.cursor.execute(
98
+ "INSERT INTO usage (user_id, count, last_time, last_date) VALUES (?, ?, ?, ?)",
99
+ (self.user_id, 0, 0, today)
100
+ )
101
+ self.conn.commit()
102
+
103
+ def _get_usage(self):
104
+ self.cursor.execute("SELECT count, last_time, last_date FROM usage WHERE user_id = ?", (self.user_id,))
105
+ row = self.cursor.fetchone()
106
+ return {"count": row[0], "last_time": row[1], "last_date": row[2]} if row else {"count": 0, "last_time": 0, "last_date": time.strftime("%Y-%m-%d")}
107
+
108
+ def _save_usage(self, count, last_time, last_date):
109
+ self.cursor.execute(
110
+ "UPDATE usage SET count = ?, last_time = ?, last_date = ? WHERE user_id = ?",
111
+ (count, last_time, last_date, self.user_id)
112
+ )
113
+ self.conn.commit()
114
+
115
+ def _switch_api_key(self):
116
+ if self.api_key_index + 1 < len(API_KEYS):
117
+ self.api_key_index += 1
118
+ self.client = Groq(api_key=API_KEYS[self.api_key_index])
119
+ return True
120
+ return False
121
+
122
+ def chat(self, prompt: str) -> str:
123
+ usage = self._get_usage()
124
+ now = time.time()
125
+ today = time.strftime("%Y-%m-%d")
126
+
127
+ if usage["last_date"] != today:
128
+ usage["count"] = 0
129
+ usage["last_date"] = today
130
+
131
+ if self.max_requests is not None and usage["count"] >= self.max_requests:
132
+ return f"⚠️ Đã hết {self.max_requests} lượt/ngày. Thử lại mai hoặc xin thêm quyền. https://discord.gg/Ze7RTExgdv"
133
+
134
+ if now - usage["last_time"] < SPAM_DELAY_SECONDS:
135
+ wait_time = SPAM_DELAY_SECONDS - int(now - usage["last_time"])
136
+ return f"⚠️ Vui lòng chờ thêm {wait_time} giây giữa các câu hỏi."
137
+
138
+ self.history.append({"role": "user", "content": prompt})
139
+
140
+ while True:
141
+ try:
142
+ chat_completion = self.client.chat.completions.create(
143
+ messages=self.history,
144
+ model=self.model,
145
+ stream=False,
146
+ )
147
+ reply = chat_completion.choices[0].message.content
148
+ self.history.append({"role": "assistant", "content": reply})
149
+
150
+ if self.max_requests is not None:
151
+ usage["count"] += 1
152
+ usage["last_time"] = now
153
+ self._save_usage(usage["count"], usage["last_time"], usage["last_date"])
154
+
155
+ return reply.strip()
156
+
157
+ except Exception as e:
158
+ if "quota" in str(e).lower() or "token" in str(e).lower():
159
+ if not self._switch_api_key():
160
+ return f"⚠️ API hết hạn hoặc lỗi: {e}"
161
+ else:
162
+ return f"⚠️ Lỗi khi gọi API: {e}"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aistv
3
- Version: 1.3.3
3
+ Version: 1.3.5
4
4
  Summary: STV AI Chatbot Library for Python
5
5
  Home-page: https://github.com/phuctrong1tuv
6
6
  Author: Trọng Phúc
@@ -2,7 +2,7 @@ from setuptools import setup, find_packages
2
2
 
3
3
  setup(
4
4
  name="aistv",
5
- version="1.3.3",
5
+ version="1.3.5",
6
6
  description="STV AI Chatbot Library for Python",
7
7
  long_description=open("README.md").read(),
8
8
  long_description_content_type="text/markdown",
aistv-1.3.3/aistv/core.py DELETED
@@ -1,114 +0,0 @@
1
- import subprocess
2
- import sys
3
- import sqlite3
4
- import time
5
-
6
- # Tự cài groq và requests nếu chưa có
7
- def install_package(pkg):
8
- try:
9
- __import__(pkg)
10
- except ImportError:
11
- subprocess.check_call([sys.executable, "-m", "pip", "install", pkg])
12
-
13
- install_package("groq")
14
- install_package("requests")
15
-
16
- import requests
17
- from groq import Groq
18
-
19
- DB_FILE = "usage.db"
20
- MAX_REQUESTS_PER_DAY = 20
21
- SPAM_DELAY_SECONDS = 5
22
- API_KEY = "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"
23
-
24
- class STVBot:
25
- def __init__(self, user_id: str, system_prompt: str = None):
26
- if not system_prompt:
27
- system_prompt = "Tôi là AI STV, được phát triển bởi Trọng Phúc."
28
- self.client = Groq(api_key=API_KEY)
29
- self.system_prompt = system_prompt
30
- self.model = "meta-llama/llama-4-maverick-17b-128e-instruct"
31
- self.history = [{"role": "system", "content": self.system_prompt}]
32
- self.user_id = user_id
33
-
34
- # Kết nối DB SQLite
35
- self.conn = sqlite3.connect(DB_FILE, check_same_thread=False)
36
- self.cursor = self.conn.cursor()
37
- self.cursor.execute('''
38
- CREATE TABLE IF NOT EXISTS usage (
39
- user_id TEXT PRIMARY KEY,
40
- count INTEGER,
41
- last_time REAL,
42
- last_date TEXT
43
- )
44
- ''')
45
- self.conn.commit()
46
-
47
- # Khởi tạo dữ liệu user nếu chưa có
48
- self._init_user()
49
-
50
- def _init_user(self):
51
- today = time.strftime("%Y-%m-%d")
52
- self.cursor.execute("SELECT * FROM usage WHERE user_id = ?", (self.user_id,))
53
- row = self.cursor.fetchone()
54
- if not row:
55
- self.cursor.execute(
56
- "INSERT INTO usage (user_id, count, last_time, last_date) VALUES (?, ?, ?, ?)",
57
- (self.user_id, 0, 0, today)
58
- )
59
- self.conn.commit()
60
-
61
- def _get_usage(self):
62
- self.cursor.execute("SELECT count, last_time, last_date FROM usage WHERE user_id = ?", (self.user_id,))
63
- row = self.cursor.fetchone()
64
- if row:
65
- return {"count": row[0], "last_time": row[1], "last_date": row[2]}
66
- else:
67
- return {"count": 0, "last_time": 0, "last_date": time.strftime("%Y-%m-%d")}
68
-
69
- def _save_usage(self, count, last_time, last_date):
70
- self.cursor.execute(
71
- "UPDATE usage SET count = ?, last_time = ?, last_date = ? WHERE user_id = ?",
72
- (count, last_time, last_date, self.user_id)
73
- )
74
- self.conn.commit()
75
-
76
- def chat(self, prompt: str) -> str:
77
- usage = self._get_usage()
78
- now = time.time()
79
- today = time.strftime("%Y-%m-%d")
80
-
81
- # Reset count nếu khác ngày
82
- if usage["last_date"] != today:
83
- usage["count"] = 0
84
- usage["last_date"] = today
85
-
86
- if usage["count"] >= MAX_REQUESTS_PER_DAY:
87
- return (
88
- "⚠️ Bạn đã sử dụng hết giới hạn 20 câu hỏi miễn phí trong ngày.\n"
89
- "Vui lòng thử lại vào ngày mai hoặc liên hệ để được cấp thêm quyền."
90
- )
91
-
92
- if now - usage["last_time"] < SPAM_DELAY_SECONDS:
93
- wait_time = SPAM_DELAY_SECONDS - int(now - usage["last_time"])
94
- return f"⚠️ Vui lòng chờ thêm {wait_time} giây giữa mỗi câu hỏi."
95
-
96
- self.history.append({"role": "user", "content": prompt})
97
-
98
- try:
99
- chat_completion = self.client.chat.completions.create(
100
- messages=self.history,
101
- model=self.model,
102
- stream=False,
103
- )
104
- reply = chat_completion.choices[0].message.content
105
- self.history.append({"role": "assistant", "content": reply})
106
-
107
- usage["count"] += 1
108
- usage["last_time"] = now
109
- self._save_usage(usage["count"], usage["last_time"], usage["last_date"])
110
-
111
- return reply.strip()
112
-
113
- except Exception as e:
114
- return f"⚠️ Lỗi khi: {e}"
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes