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