clementrof commited on
Commit
a37f34e
·
verified ·
1 Parent(s): 7267cfb

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +138 -0
app.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import random
3
+ import time
4
+ import pymongo
5
+ import certifi
6
+ import os
7
+ from dotenv import load_dotenv
8
+
9
+
10
+ import argparse
11
+ from dataclasses import dataclass
12
+ from langchain.vectorstores.chroma import Chroma
13
+ from langchain_openai.embeddings import OpenAIEmbeddings
14
+ from langchain_openai.chat_models import ChatOpenAI
15
+ from langchain.prompts import ChatPromptTemplate
16
+
17
+ from deep_translator import GoogleTranslator
18
+
19
+ uri = "mongodb+srv://clementrof:t5fXqwpDQYFpvuCk@cluster0.rl5qhcj.mongodb.net/?retryWrites=true&w=majority"
20
+
21
+ # Create a new client and connect to the server
22
+ client = pymongo.MongoClient(uri, tlsCAFile=certifi.where())
23
+
24
+ # Send a ping to confirm a successful connection
25
+ try:
26
+ client.admin.command('ping')
27
+ print("Pinged your deployment. You successfully connected to MongoDB!")
28
+ except Exception as e:
29
+ print(e)
30
+
31
+ # Access your database
32
+ db = client.get_database('camila')
33
+ records = db.info
34
+
35
+ # Load environment variables from .env
36
+ load_dotenv()
37
+
38
+ # Access the private key
39
+ private_key = os.getenv("OPENAI_API_KEY")
40
+ os.environ["OPENAI_API_KEY"] = "OPENAI_API_KEY"
41
+
42
+ CHROMA_PATH = "ch_chatbot"
43
+
44
+
45
+ ####### F R ################
46
+ PROMPT_TEMPLATE = """
47
+ Réponds à la question en te basant sur le contexte suivant :
48
+
49
+ {context}
50
+
51
+ ---
52
+
53
+ Voici l'historique de cette conversation, utilise l'historique comme une mémoire:
54
+
55
+ {memory}
56
+
57
+ ---
58
+
59
+ Réponds à la question en se basant sur le contexte ci-dessus et parle de la même manière que le contexte. Ne dis pas que tu utilises le contexte pour répondre : {question}
60
+
61
+ """
62
+
63
+
64
+
65
+
66
+
67
+ def message(question,memory):
68
+
69
+ # Prepare the DB.
70
+ embedding_function = OpenAIEmbeddings()
71
+ db = Chroma(persist_directory=CHROMA_PATH,
72
+ embedding_function=embedding_function)
73
+
74
+ # Search the DB.
75
+ results = db.similarity_search_with_relevance_scores(question, k=3)
76
+ if len(results) == 0 or results[0][1] < 0.7:
77
+ print("Unable to find matching results.")
78
+ return
79
+
80
+ context_text = "\n\n---\n\n".join(
81
+ [doc.page_content for doc, _score in results])
82
+ prompt_template = ChatPromptTemplate.from_template(PROMPT_TEMPLATE)
83
+ prompt = prompt_template.format(context=context_text, memory=memory, question=question)
84
+ print(prompt)
85
+
86
+ model = ChatOpenAI()
87
+ response_text = model.invoke(prompt)
88
+ content = response_text.content
89
+ return content
90
+
91
+
92
+
93
+ def Chat_call(question):
94
+ existing_user_doc = records.find_one({'ID': '1'})
95
+
96
+ message_log = []
97
+ messages = existing_user_doc['message']
98
+ if len(messages)>1:
99
+ messages = messages[-1:]
100
+
101
+ message_log.extend(messages)
102
+ # Convert each dictionary into a string representation
103
+ message_strings = [f"{message['role']}: {message['content']}" for message in message_log]
104
+ # Join the strings with newline characters
105
+ memory = '\n'.join(message_strings)
106
+
107
+
108
+
109
+ response = message(question,memory)
110
+
111
+
112
+ records.update_one({'ID': '1'},
113
+ {'$push':{'message': {'role': 'user', 'content': f'{question}'}}})
114
+ records.update_one({'ID': '1'},
115
+ {'$push':{'message': {'role': 'assistant', 'content': f'{response}'}}})
116
+
117
+
118
+ return response
119
+
120
+
121
+
122
+
123
+ with gr.Blocks() as demo:
124
+ chatbot = gr.Chatbot()
125
+ msg = gr.Textbox()
126
+ clear = gr.ClearButton([msg, chatbot])
127
+
128
+ def respond(message, chat_history):
129
+ bot_message = Chat_call(message)
130
+ chat_history.append((message, bot_message))
131
+ return "", chat_history
132
+
133
+ msg.submit(respond, [msg, chatbot], [msg, chatbot])
134
+
135
+ if __name__ == "__main__":
136
+ demo.launch()
137
+
138
+