Update llm_handler.py
Browse files- llm_handler.py +83 -123
llm_handler.py
CHANGED
@@ -1,125 +1,85 @@
|
|
1 |
-
|
2 |
-
import json
|
3 |
-
|
4 |
-
from
|
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 |
-
# Create msg_context for LLM with Wikipedia info
|
56 |
-
msg_context = {"role": "system", "content": full_prompt_for_llm}
|
57 |
-
|
58 |
-
# Prepare message list for LLM to generate the question
|
59 |
-
msg_list = [msg_context, {"role": "user", "content": f"Generate a question based on the SUBJECT_AREA: {topic_selected}"}]
|
60 |
-
|
61 |
-
# Send to LLM for question generation
|
62 |
-
question, _ = send_to_llm(llm_provider, msg_list)
|
63 |
-
|
64 |
-
# Prepare message list for LLM to generate the answer
|
65 |
-
msg_list_answer = [
|
66 |
-
{"role": "system", "content": system_message_selected},
|
67 |
-
{"role": "user", "content": question}
|
68 |
-
]
|
69 |
-
|
70 |
-
# Send to LLM for answer generation
|
71 |
-
answer, _ = send_to_llm(llm_provider, msg_list_answer)
|
72 |
-
|
73 |
-
# Prepare data for output (excluding usage information)
|
74 |
data = {
|
75 |
-
"
|
76 |
-
"
|
77 |
-
"response": answer
|
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 |
-
# Wait for all futures to complete
|
111 |
-
for future in futures:
|
112 |
-
data = future.result()
|
113 |
-
if data:
|
114 |
-
nn += 1
|
115 |
-
print(data)
|
116 |
-
print(
|
117 |
-
f"Generation {nn} Complete"
|
118 |
-
)
|
119 |
-
else:
|
120 |
-
failed += 1
|
121 |
-
print("=" * 132)
|
122 |
-
|
123 |
-
|
124 |
-
if __name__ == "__main__":
|
125 |
-
main()
|
|
|
1 |
+
import requests
|
2 |
+
import json
|
3 |
+
from openai import OpenAI
|
4 |
+
from params import load_params
|
5 |
+
import logging
|
6 |
+
|
7 |
+
# Configure logging
|
8 |
+
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
|
9 |
+
logger = logging.getLogger(__name__)
|
10 |
+
|
11 |
+
def get_client():
|
12 |
+
params = load_params()
|
13 |
+
if params['PROVIDER'] == 'local-model':
|
14 |
+
return OpenAI(api_key="local-model", base_url=params['BASE_URL'])
|
15 |
+
return None
|
16 |
+
|
17 |
+
def send_to_chatgpt(msg_list):
|
18 |
+
try:
|
19 |
+
client = get_client()
|
20 |
+
if client is None:
|
21 |
+
raise ValueError("Failed to initialize OpenAI client")
|
22 |
+
|
23 |
+
params = load_params()
|
24 |
+
logger.info(f"Sending request to: {params['BASE_URL']}")
|
25 |
+
logger.info(f"Using model: {params['MODEL']}")
|
26 |
+
logger.debug(f"Input messages: {json.dumps(msg_list, indent=2)}")
|
27 |
+
|
28 |
+
completion = client.chat.completions.create(
|
29 |
+
model=params['MODEL'],
|
30 |
+
temperature=params['temperature'],
|
31 |
+
messages=msg_list
|
32 |
+
)
|
33 |
+
chatgpt_response = completion.choices[0].message.content
|
34 |
+
chatgpt_usage = completion.usage
|
35 |
+
logger.debug(f"LLM response: {chatgpt_response}")
|
36 |
+
logger.debug(f"Usage: {chatgpt_usage}")
|
37 |
+
return chatgpt_response, chatgpt_usage
|
38 |
+
except requests.exceptions.RequestException as e:
|
39 |
+
logger.error(f"Request error in send_to_chatgpt: {str(e)}")
|
40 |
+
return f"Error: Connection failed - {str(e)}", None
|
41 |
+
except Exception as e:
|
42 |
+
logger.error(f"Error in send_to_chatgpt: {str(e)}")
|
43 |
+
return f"Error: {str(e)}", None
|
44 |
+
|
45 |
+
def send_to_anything_llm(msg_list):
|
46 |
+
params = load_params()
|
47 |
+
url = f"{params['BASE_URL']}/api/v1/workspace/{params['WORKSPACE']}/chat"
|
48 |
+
headers = {
|
49 |
+
'accept': 'application/json',
|
50 |
+
'Authorization': f"Bearer {params['API_KEY']}",
|
51 |
+
'Content-Type': 'application/json'
|
52 |
+
}
|
53 |
+
message_content = " ".join(msg["content"] for msg in msg_list if "content" in msg)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
54 |
data = {
|
55 |
+
"message": message_content,
|
56 |
+
"mode": "chat"
|
|
|
57 |
}
|
58 |
+
data_json = json.dumps(data)
|
59 |
+
logger.debug(f"Sending to AnythingLLM: {data_json}")
|
60 |
+
try:
|
61 |
+
response = requests.post(url, headers=headers, data=data_json)
|
62 |
+
response.raise_for_status()
|
63 |
+
response_data = response.json()
|
64 |
+
chatgpt_response = response_data.get("textResponse")
|
65 |
+
chatgpt_usage = response_data.get("usage", {})
|
66 |
+
logger.debug(f"AnythingLLM response: {chatgpt_response}")
|
67 |
+
logger.debug(f"AnythingLLM usage: {chatgpt_usage}")
|
68 |
+
return chatgpt_response, chatgpt_usage
|
69 |
+
except requests.RequestException as e:
|
70 |
+
logger.error(f"Error in send_to_anything_llm: {str(e)}")
|
71 |
+
return f"Error: {str(e)}", None
|
72 |
+
|
73 |
+
def send_to_llm(msg_list):
|
74 |
+
params = load_params()
|
75 |
+
logger.info(f"Using provider: {params['PROVIDER']}")
|
76 |
+
if params['PROVIDER'] == "local-model":
|
77 |
+
return send_to_chatgpt(msg_list)
|
78 |
+
elif params['PROVIDER'] == "anything-llm":
|
79 |
+
return send_to_anything_llm(msg_list)
|
80 |
+
else:
|
81 |
+
raise ValueError(f"Unknown provider: {params['PROVIDER']}")
|
82 |
+
|
83 |
+
def send_to_llm_wrapper(msg_list):
|
84 |
+
logger.info("Sending message to LLM")
|
85 |
+
return send_to_llm(msg_list)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|