Spaces:
Sleeping
Sleeping
File size: 11,294 Bytes
d57efd6 0767396 d57efd6 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 |
{
"cells": [
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Pinged your deployment. You successfully connected to MongoDB!\n"
]
}
],
"source": [
"from core.chat.chatstore import ChatStore\n",
"from pymongo.mongo_client import MongoClient\n",
"from dotenv import load_dotenv\n",
"import os\n",
"\n",
"load_dotenv()\n",
"# uri = \"mongodb+srv://summariz:[email protected]/?retryWrites=true&w=majority&appName=Cluster0\"\n",
"uri = os.getenv(\"MONGO_URI\")\n",
"client = MongoClient(uri)\n",
"\n",
"try:\n",
" client.admin.command('ping')\n",
" print(\"Pinged your deployment. You successfully connected to MongoDB!\")\n",
"except Exception as e:\n",
" print(e)"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[{'role': 'user', 'content': 'hallo', 'additional_kwargs': {}},\n",
" {'role': 'assistant',\n",
" 'content': 'Halo! Ada yang bisa saya bantu hari ini, dok? π',\n",
" 'metadata': []}]"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"chat_store = ChatStore()\n",
"session_id = \"dfe69118-355b-4276-adc8-0a82e5706f44\"\n",
"chat_history = chat_store.get_messages(session_id)\n",
"chat_history"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"db = client['bot_database'] # Replace with your database name\n",
"collection = db['bot'] # Replace with your collection name"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"result = collection.insert_many(chat_history)"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Data inserted with record ids [ObjectId('67060bd6c8ffb964976540a5'), ObjectId('67060bd6c8ffb964976540a6')]\n"
]
}
],
"source": [
"# Print the IDs of the inserted documents\n",
"print(\"Data inserted with record ids\", result.inserted_ids)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[{'role': 'system',\n",
" 'content': 'halo',\n",
" 'timestamp': datetime.datetime(2024, 10, 10, 11, 18, 10, 779000)},\n",
" {'role': 'assistant',\n",
" 'content': 'Halo! π Ada yang bisa saya bantu hari ini, dok? Jika ada pertanyaan tentang kedokteran atau kesehatan, silakan tanyakan saja!',\n",
" 'metadata': [],\n",
" 'timestamp': datetime.datetime(2024, 10, 10, 11, 18, 10, 779000)}]"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Select your database\n",
"db = client['bot_database'] # Replace with your database name\n",
"\n",
"# Select your collection\n",
"collection = db['6fd735b8-a814-47ce-8427-a7bbe4c14ec6'] # Replace with your collection name\n",
"\n",
"# Retrieve all documents from the collection\n",
"documents = collection.find()\n",
"\n",
"# Convert the cursor to a list and exclude the _id field\n",
"documents_list = [{key: doc[key] for key in doc if key != '_id' and doc[key] is not None} for doc in documents]\n",
"\n",
"# Print the list of documents without the _id field\n",
"documents_list"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Collection 'bot' exists in the database 'bot_database'.\n",
"Doing something because the collection exists.\n"
]
}
],
"source": [
"def check_collection_exists(db_name, collection_name):\n",
" # Connect to the MongoDB server\n",
" db = client[db_name]\n",
"\n",
" # Check if the collection exists\n",
" if collection_name in db.list_collection_names():\n",
" print(f\"Collection '{collection_name}' exists in the database '{db_name}'.\")\n",
" # Perform your desired action here\n",
" do_something()\n",
" else:\n",
" print(f\"Collection '{collection_name}' does not exist in the database '{db_name}'.\")\n",
"\n",
"def do_something():\n",
" # Define the action you want to perform\n",
" print(\"Doing something because the collection exists.\")\n",
"\n",
"# Example usage\n",
"check_collection_exists('bot_database', \"bot\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Test Redis"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The collection 'test' does not exists.\n"
]
}
],
"source": [
" \n",
"import redis\n",
"from dotenv import load_dotenv\n",
"import os\n",
"\n",
"load_dotenv()\n",
"\n",
"redis_client = redis.Redis(\n",
" host=\"redis-10365.c244.us-east-1-2.ec2.redns.redis-cloud.com\",\n",
" port=10365,\n",
" password=os.environ.get(\"REDIS_PASSWORD\"),\n",
")\n",
"\n",
"session_id =\"test\"\n",
" \n",
"if redis_client.exists(session_id):\n",
" print(f\"The collection '{session_id}' exists.\")\n",
"else: \n",
" print(f\"The collection '{session_id}' does not exists.\")\n"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"<starlette.responses.JSONResponse at 0x1e94fe62850>"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from core.chat.chatstore import ChatStore\n",
"\n",
"chat_store = ChatStore()\n",
"\n",
"\n",
"session_id = \"6fd735b8-a814-47ce-8427-a7bbe4c14ec6\"\n",
"\n",
"chat_store.add_chat_history_to_redis(session_id)"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Collection(Database(MongoClient(host=['cluster0-shard-00-00.bw0sr.mongodb.net:27017', 'cluster0-shard-00-02.bw0sr.mongodb.net:27017', 'cluster0-shard-00-01.bw0sr.mongodb.net:27017'], document_class=dict, tz_aware=False, connect=True, retrywrites=True, w='majority', appname='Cluster0', authsource='admin', replicaset='atlas-ukfsmn-shard-0', ssl=True), 'bot_database'), '6fd735b8-a814-47ce-8427-a7bbe4c14ec6')\n",
"[{'role': 'system', 'content': 'halo'}, {'role': 'assistant', 'content': 'Halo! π Ada yang bisa saya bantu hari ini, dok? Jika ada pertanyaan tentang kedokteran atau kesehatan, silakan tanyakan saja!', 'metadata': []}]\n"
]
},
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import json\n",
"import redis\n",
"from service.dto import ChatMessage\n",
"\n",
"redis_client = redis.Redis(\n",
" host=\"redis-10365.c244.us-east-1-2.ec2.redns.redis-cloud.com\",\n",
" port=10365,\n",
" password=os.environ.get(\"REDIS_PASSWORD\"),\n",
")\n",
"\n",
"def message_to_dict(message: ChatMessage) -> dict:\n",
" return message.model_dump()\n",
"\n",
"session_id = \"6fd735b8-a814-47ce-8427-a7bbe4c14ec6\"\n",
"db = client[\"bot_database\"]\n",
"collection = db[session_id]\n",
"\n",
"print(collection)\n",
"\n",
"chat_history = collection.find()\n",
"chat_history_list = [\n",
" {key: message[key] for key in message if key not in ['_id', 'timestamp'] and message[key] is not None}\n",
" for message in chat_history if message is not None\n",
"]\n",
"\n",
"print(chat_history_list)\n",
"\n",
"for message in chat_history_list:\n",
" # Convert MongoDB document to the format you need\n",
" item = json.dumps(message_to_dict(ChatMessage(**message))) # Convert message to dict\n",
" redis_client.rpush(session_id, item)\n",
" \n",
"redis_client.expire(session_id, time=86400)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Pinged your deployment. You successfully connected to MongoDB!\n",
"Saya tidak memiliki informasi spesifik mengenai gejala penyakit jantung dari buku yang tersedia. Namun, secara umum, gejala penyakit jantung dapat mencakup:\n",
"\n",
"1. **Nyeri Dada**: Rasa tidak nyaman atau nyeri di dada, sering kali digambarkan sebagai tekanan atau rasa penuh.\n",
"2. **Sesak Napas**: Kesulitan bernapas, baik saat beraktivitas maupun saat istirahat.\n",
"3. **Kelelahan**: Rasa lelah yang tidak biasa, bahkan setelah aktivitas ringan.\n",
"4. **Palpitasi**: Detak jantung yang cepat atau tidak teratur.\n",
"5. **Pusing atau Pingsan**: Rasa pusing yang bisa berujung pada pingsan.\n",
"\n",
"Jika Anda mengalami gejala-gejala tersebut, sangat penting untuk berkonsultasi dengan dokter atau ahli kesehatan untuk evaluasi lebih lanjut. Semoga informasi ini bermanfaat, dok β¨ Jika ada pertanyaan lain, jangan ragu untuk bertanya ya dok π\n"
]
}
],
"source": [
"from pymongo.mongo_client import MongoClient\n",
"from dotenv import load_dotenv\n",
"import os\n",
"\n",
"load_dotenv()\n",
"# uri = \"mongodb+srv://summariz:[email protected]/?retryWrites=true&w=majority&appName=Cluster0\"\n",
"uri = os.getenv(\"MONGO_URI\")\n",
"client = MongoClient(uri)\n",
"\n",
"try:\n",
" client.admin.command('ping')\n",
" print(\"Pinged your deployment. You successfully connected to MongoDB!\")\n",
"except Exception as e:\n",
" print(e)\n",
" \n",
"session_id = \"06715451-874f-41e8-8734-d4666d640539\"\n",
"\n",
"db = client[\"bot_database\"]\n",
"collection = db[session_id]\n",
"\n",
"# Get the last document by sorting by _id in descending order\n",
"last_document = collection.find().sort(\"_id\", -1).limit(1)\n",
"\n",
"for doc in last_document:\n",
" doc['content']"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "fullstack",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.9"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
|