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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/python3
|
| 2 |
+
import requests
|
| 3 |
+
import json
|
| 4 |
+
import sys
|
| 5 |
+
import psycopg2
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
from sentence_transformers import SentenceTransformer
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
MAX_WORDS=1024
|
| 11 |
+
|
| 12 |
+
model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 13 |
+
|
| 14 |
+
def last_n_words(text: str, n: int) -> str:
|
| 15 |
+
words = text.split()
|
| 16 |
+
return " ".join(words[-n:])
|
| 17 |
+
|
| 18 |
+
def get_chat_completion(content: str, port: int) -> str:
|
| 19 |
+
url = f"http://localhost:{port}/v1/chat/completions"
|
| 20 |
+
headers = {"Content-Type": "application/json"}
|
| 21 |
+
data = {
|
| 22 |
+
"model": "Default",
|
| 23 |
+
"messages": [{"role": "user", "content": content}],
|
| 24 |
+
"max_tokens": 2048,
|
| 25 |
+
"temperature": 0.28
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
response = requests.post(url, headers=headers, data=json.dumps(data))
|
| 29 |
+
|
| 30 |
+
if response.status_code == 200:
|
| 31 |
+
response_json = response.json()
|
| 32 |
+
return response_json.get("choices", [{}])[0].get("message", {}).get("content", "No response content")
|
| 33 |
+
else:
|
| 34 |
+
return f"Request failed with status code {response.status_code}"
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
# database connection
|
| 40 |
+
def get_db_connection():
|
| 41 |
+
try:
|
| 42 |
+
connection = psycopg2.connect(
|
| 43 |
+
dbname="d_conversations",
|
| 44 |
+
user="postgres",
|
| 45 |
+
password="********",
|
| 46 |
+
host="pg-db",
|
| 47 |
+
port="5432"
|
| 48 |
+
)
|
| 49 |
+
return connection
|
| 50 |
+
except Exception as e:
|
| 51 |
+
print(f"Error in connection to database: {e}")
|
| 52 |
+
return None
|
| 53 |
+
|
| 54 |
+
def save_message(db_connection, message, chatbot_id, model_id):
|
| 55 |
+
# save a message in conversation table
|
| 56 |
+
|
| 57 |
+
embeds = model.encode(message).tolist()
|
| 58 |
+
|
| 59 |
+
try:
|
| 60 |
+
with db_connection.cursor() as cursor:
|
| 61 |
+
query = """
|
| 62 |
+
INSERT INTO conversation (id, chatbot_id, message, create_dt, model_id, embeds)
|
| 63 |
+
VALUES (nextval('conversation_seq'), %s, %s, %s, %s, %s)
|
| 64 |
+
RETURNING id;
|
| 65 |
+
"""
|
| 66 |
+
create_dt = datetime.utcnow()
|
| 67 |
+
cursor.execute(query, (chatbot_id, message, create_dt, model_id, embeds))
|
| 68 |
+
conversation_id = cursor.fetchone()[0]
|
| 69 |
+
db_connection.commit()
|
| 70 |
+
return conversation_id
|
| 71 |
+
except Exception as e:
|
| 72 |
+
db_connection.rollback()
|
| 73 |
+
print(f"Error while inserting: {e}")
|
| 74 |
+
return None
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def get_last_n_messages(db_connection, n):
|
| 78 |
+
"""
|
| 79 |
+
Retrieves the last n messages from the conversation table and formats them as a chat log.
|
| 80 |
+
|
| 81 |
+
:param db_connection: Database connection object
|
| 82 |
+
:return: Formatted string with the last n messages
|
| 83 |
+
"""
|
| 84 |
+
try:
|
| 85 |
+
with db_connection.cursor() as cursor:
|
| 86 |
+
query = """
|
| 87 |
+
SELECT cb.name, c.message
|
| 88 |
+
FROM conversation c, chatbot cb WHERE c.chatbot_id=cb.id
|
| 89 |
+
ORDER BY c.id DESC
|
| 90 |
+
LIMIT %s;
|
| 91 |
+
"""
|
| 92 |
+
cursor.execute(query, (n,))
|
| 93 |
+
rows = cursor.fetchall()
|
| 94 |
+
|
| 95 |
+
if len(rows)==3:
|
| 96 |
+
formatted_messages = f"<{rows[2][0]}> - {rows[2][1]}\n\n<{rows[1][0]}> - {rows[1][1]}\n\n<{rows[0][0]}> - {rows[0][1]}"
|
| 97 |
+
|
| 98 |
+
if len(rows)==2:
|
| 99 |
+
formatted_messages = f"<{rows[1][0]}> - {rows[1][1]}\n\n<{rows[0][0]}> - {rows[0][1]}"
|
| 100 |
+
|
| 101 |
+
if len(rows)==1:
|
| 102 |
+
formatted_messages = f"<{rows[0][0]}> - {rows[0][1]}"
|
| 103 |
+
|
| 104 |
+
if len(rows)==0:
|
| 105 |
+
formatted_messages = "\n"
|
| 106 |
+
|
| 107 |
+
return formatted_messages
|
| 108 |
+
except Exception as e:
|
| 109 |
+
print(f"Error while retrieving messages: {e}")
|
| 110 |
+
return None
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def get_chatbot_model_port(db_connection, chatbot_id):
|
| 116 |
+
"""
|
| 117 |
+
Retrieves model_id and port from the chatbot table for a given chatbot ID.
|
| 118 |
+
|
| 119 |
+
:param db_connection: Database connection object
|
| 120 |
+
:param chatbot_id: ID of the chatbot
|
| 121 |
+
:return: Tuple (model_id, port) or None if not found
|
| 122 |
+
"""
|
| 123 |
+
try:
|
| 124 |
+
with db_connection.cursor() as cursor:
|
| 125 |
+
query = "SELECT model_id, port FROM chatbot WHERE id = %s;"
|
| 126 |
+
cursor.execute(query, (chatbot_id,))
|
| 127 |
+
result = cursor.fetchone()
|
| 128 |
+
|
| 129 |
+
if result:
|
| 130 |
+
return result # (model_id, port)
|
| 131 |
+
else:
|
| 132 |
+
print(f"No chatbot found with ID {chatbot_id}")
|
| 133 |
+
return None
|
| 134 |
+
except Exception as e:
|
| 135 |
+
print(f"Error retrieving chatbot info: {e}")
|
| 136 |
+
return None
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
# Example usage
|
| 141 |
+
if len(sys.argv) < 2:
|
| 142 |
+
print("Usage: python3 conversations.py '<your question here>'")
|
| 143 |
+
sys.exit(1)
|
| 144 |
+
|
| 145 |
+
conn = get_db_connection()
|
| 146 |
+
if conn is None:
|
| 147 |
+
print("Connection to database failed")
|
| 148 |
+
exit(1)
|
| 149 |
+
|
| 150 |
+
user_input = sys.argv[1]
|
| 151 |
+
save_message(conn, user_input, 1, 0)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
chatbot_a = 4
|
| 155 |
+
chatbot_b = 7
|
| 156 |
+
current_chatbot = chatbot_a
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
try:
|
| 160 |
+
while True:
|
| 161 |
+
# Recovers last message from conversation
|
| 162 |
+
last_messages = get_last_n_messages(conn, 1)
|
| 163 |
+
|
| 164 |
+
print("last messages: "+last_messages)
|
| 165 |
+
# Change chatbot
|
| 166 |
+
current_chatbot = chatbot_a if current_chatbot == chatbot_b else chatbot_b
|
| 167 |
+
|
| 168 |
+
print(f"asking chatbot {current_chatbot}")
|
| 169 |
+
# Retrieve model and port of current chatbot
|
| 170 |
+
model_port_info = get_chatbot_model_port(conn, current_chatbot)
|
| 171 |
+
if not model_port_info:
|
| 172 |
+
print(f"Could not retrieve info from {current_chatbot}")
|
| 173 |
+
break
|
| 174 |
+
|
| 175 |
+
model_id, port = model_port_info
|
| 176 |
+
print("retrieved model and port")
|
| 177 |
+
|
| 178 |
+
# Retrieves answer
|
| 179 |
+
if (current_chatbot == chatbot_a):
|
| 180 |
+
print("ask for question")
|
| 181 |
+
last_messages = last_messages + "\n\nSuggest one very short factual follow-up question that has not been answered yet or cannot be found inspired by the previous conversation and excerpts.\n"
|
| 182 |
+
response = get_chat_completion(last_n_words(last_messages, MAX_WORDS), port)
|
| 183 |
+
|
| 184 |
+
# Saves answer in database
|
| 185 |
+
save_message(conn, response, current_chatbot, model_id)
|
| 186 |
+
|
| 187 |
+
# Print last answer
|
| 188 |
+
print("answer was:")
|
| 189 |
+
print(get_last_n_messages(conn,1))
|
| 190 |
+
|
| 191 |
+
except KeyboardInterrupt:
|
| 192 |
+
print("\nConversation interrupted by human.")
|
| 193 |
+
finally:
|
| 194 |
+
conn.close()
|
conversations_db.sql
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
gpt4all-relay.sh
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
ssh -g -L 4891:localhost:4891 -f -N dm@gpt4all
|
| 3 |
+
ssh -g -L 4892:localhost:4891 -f -N dm@chatbot1
|
| 4 |
+
ssh -g -L 4893:localhost:4891 -f -N dm@chatbot2
|
| 5 |
+
ssh -g -L 4894:localhost:4891 -f -N dm@area51
|