enotkrutoy commited on
Commit
8b1625b
·
verified ·
1 Parent(s): efb0e4f

Create g12.py

Browse files
Files changed (1) hide show
  1. g12.py +126 -0
g12.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import groq
2
+ import time
3
+ import os
4
+ import json
5
+ import logging
6
+
7
+ logging.basicConfig(level=logging.DEBUG)
8
+
9
+ client = groq.Groq()
10
+
11
+ def parse_json_response(raw_response):
12
+ """
13
+ Разбирает строку JSON и проверяет наличие обязательных ключей.
14
+ """
15
+ logging.debug(f"RAW JSON RESPONSE: {raw_response}")
16
+ try:
17
+ parsed_response = json.loads(raw_response)
18
+ except json.JSONDecodeError as e:
19
+ raise ValueError(f"Invalid JSON: {e}, content: {raw_response}")
20
+
21
+ if all(k in parsed_response for k in ("title", "content", "next_action")):
22
+ return parsed_response
23
+ else:
24
+ raise ValueError("JSON missing required keys")
25
+
26
+ def make_api_call(messages, max_tokens, is_final_answer=False, client_obj=None):
27
+ """
28
+ Отправляет API-запрос с заданными сообщениями и возвращает результат.
29
+ При is_final_answer=True возвращает текст финального ответа.
30
+ В противном случае ожидается, что ответ будет в формате JSON с ключами "title", "content", "next_action".
31
+ """
32
+ current_client = client_obj if client_obj is not None else client
33
+
34
+ for attempt in range(3):
35
+ try:
36
+ if is_final_answer:
37
+ response = current_client.chat.completions.create(
38
+ model="llama3-8b-8192",
39
+ messages=messages,
40
+ max_tokens=max_tokens,
41
+ temperature=0.2
42
+ )
43
+ return response.choices[0].message.content
44
+ else:
45
+ response = current_client.chat.completions.create(
46
+ model="llama3-8b-8192",
47
+ messages=messages,
48
+ max_tokens=max_tokens, # Используем переданный параметр max_tokens
49
+ temperature=0.2,
50
+ response_format={"type": "json_object"}
51
+ )
52
+ raw_response = response.choices[0].message.content
53
+ return parse_json_response(raw_response)
54
+ except Exception as e:
55
+ logging.exception("Attempt %d failed", attempt + 1)
56
+ if attempt == 2:
57
+ if is_final_answer:
58
+ return {
59
+ "title": "Error",
60
+ "content": f"Failed to generate final answer after 3 attempts. Error: {str(e)}"
61
+ }
62
+ else:
63
+ return {
64
+ "title": "Error",
65
+ "content": f"Failed to generate step after 3 attempts. Error: {str(e)}",
66
+ "next_action": "final_answer"
67
+ }
68
+ time.sleep(1)
69
+
70
+ def generate_response(prompt, client_obj=None):
71
+ """
72
+ Генерирует ответ, возвращая промежуточные шаги рассуждений и финальный результат.
73
+ Функция является генератором: yield возвращает кортеж (steps, total_thinking_time).
74
+ """
75
+ messages = [
76
+ {"role": "system", "content": """
77
+ Вы – интеллектуальный помощник, который анализирует и объясняет свои рассуждения на русском языке шаг за шагом.
78
+ ### 🔹 Формат ответа
79
+ Ваш ответ должен быть строго в JSON-формате без дополнительного текста или форматирования (например, без ```json```).
80
+ Обязательные ключи:
81
+ - "title" – краткое название шага.
82
+ - "content" – описание действий.
83
+ - "next_action" – "continue" или "final_answer".
84
+ Пример:
85
+ {"title": "Анализ задачи", "content": "Выделение ключевых элементов...", "next_action": "continue"}
86
+ 🔹 Дополнительные требования:
87
+ - Используйте русский язык.
88
+ - Избегайте Unicode-кодировок (например, писать "Привет", а не "\u041f\u0440\u0438...").
89
+ """},
90
+ {"role": "user", "content": prompt},
91
+ {"role": "assistant", "content": "Спасибо! Начинаю анализ..."}
92
+ ]
93
+
94
+ steps = []
95
+ step_count = 1
96
+ total_thinking_time = 0
97
+
98
+ while True:
99
+ start_time = time.time()
100
+ step_data = make_api_call(messages, max_tokens=500, client_obj=client_obj)
101
+ end_time = time.time()
102
+ thinking_time = end_time - start_time
103
+ total_thinking_time += thinking_time
104
+
105
+ steps.append((f"Step {step_count}: {step_data['title']}", step_data['content'], thinking_time))
106
+ messages.append({"role": "assistant", "content": json.dumps(step_data)})
107
+
108
+ if step_data.get('next_action') == 'final_answer' or step_count >= 25:
109
+ break
110
+
111
+ step_count += 1
112
+ yield steps, None # Возвращаем промежуточные шаги без финального времени
113
+
114
+ messages.append({
115
+ "role": "user",
116
+ "content": "Предоставьте окончательный ответ без формата JSON. Сохранить исходное форматирование из подсказки."
117
+ })
118
+
119
+ start_time = time.time()
120
+ final_data = make_api_call(messages, max_tokens=1200, is_final_answer=True, client_obj=client_obj)
121
+ end_time = time.time()
122
+ thinking_time = end_time - start_time
123
+ total_thinking_time += thinking_time
124
+
125
+ steps.append(("Final Answer", final_data, thinking_time))
126
+ yield steps, total_thinking_time