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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import ast
|
2 |
+
import os
|
3 |
+
import random
|
4 |
+
import time
|
5 |
+
from typing import List, Dict, Generator, Tuple
|
6 |
+
|
7 |
+
try:
|
8 |
+
from src.models import get_model_api
|
9 |
+
from src.utils import get_turn_title, get_final_answer, get_xml_tag_value
|
10 |
+
except (ModuleNotFoundError, ImportError):
|
11 |
+
from models import get_model_api
|
12 |
+
from utils import get_turn_title, get_final_answer, get_xml_tag_value
|
13 |
+
|
14 |
+
|
15 |
+
# https://arxiv.org/abs/2401.10020
|
16 |
+
def get_verification_system_prompt(context):
|
17 |
+
verification_system_prompt = f"""You are a critical analyzer and fact-checker. Your task is to carefully examine the given response and provide a thorough critique. Focus on the following aspects:
|
18 |
+
|
19 |
+
<definitions>
|
20 |
+
* Clarity: Is the response clear and unambiguous?
|
21 |
+
* Relevance: Does the response contribute to solving the problem at hand?
|
22 |
+
* Consistency: Does the response align with previously stated information?
|
23 |
+
* Logical Soundness: Is the reasoning in the response valid?
|
24 |
+
* Factual Accuracy: Are any claims in the response accurate (if applicable)?
|
25 |
+
</definitions>
|
26 |
+
|
27 |
+
<scoring_rubric>
|
28 |
+
* Add 1 point if the response is helpful, even if it is incomplete or contains some irrelevant content or may not be entirely logical or accurate.
|
29 |
+
* Add another point if the response is relevant, but may lack clarity or logical soundness.
|
30 |
+
* Award a third point if the response is helpful, regardless of being incomplete or slightly off-topic.
|
31 |
+
* Grant a fourth point if the response is clearly written and is fully comprehensively and helpful, even if there is slight room for improvement in clarity, conciseness or focus.
|
32 |
+
* Bestow a fifth point for a response that is impeccable, without extraneous information, perfectly consistent, exactly logical, and reflects expert knowledge.
|
33 |
+
* Deduct 1 point for a major clarity issue
|
34 |
+
* Deduct 1 point for a major relevance issue
|
35 |
+
* Deduct 1 point for a major consistency issue
|
36 |
+
* Deduct 1 point for a major logical fallacy issue
|
37 |
+
* Deduct 1 point for a major factual accuracy issue
|
38 |
+
</scoring_rubric>
|
39 |
+
These points are additive in nature, so one can get up to 5 points for a perfect response and as low as -5 points for a completely poor response.
|
40 |
+
|
41 |
+
Prior context that led to the text to split:
|
42 |
+
<context>
|
43 |
+
{context}
|
44 |
+
</context>
|
45 |
+
|
46 |
+
After examining the user's instruction and the response:
|
47 |
+
* Provide a brief 100-word analysis addressing these aspects. If you identify any issues or inconsistencies, explain them clearly. You MUST provide a critique in <critique> </critique> XML tags.
|
48 |
+
* Conclude with a purely numerical cumulative score. You MUST provide a score inside <score </score> XML tags (e.g., <score>3</score> for 3 points).
|
49 |
+
"""
|
50 |
+
return verification_system_prompt
|
51 |
+
|
52 |
+
|
53 |
+
def sentence_splitting_system_prompt(context) -> str:
|
54 |
+
return f"""You are a sentence splitter.
|
55 |
+
Your task is to split the given text into sentences.
|
56 |
+
* Ensure that each sentence is properly formatted and correctly separated.
|
57 |
+
* Use proper punctuation and capitalization.
|
58 |
+
* If a sentence is ambiguous or unclear, use your best judgment to split it into two or more sentences.
|
59 |
+
* If a sentence is already correctly formatted, do not make any changes.
|
60 |
+
* You may also need to correct any spelling or grammatical errors in the text.
|
61 |
+
* Remove any unnecessary line breaks.
|
62 |
+
* Omit needless sentences and words that are not directly relevant to the context, i.e. avoid conversation fillers or discourse markers.
|
63 |
+
|
64 |
+
Prior context that led to the text to split:
|
65 |
+
<context>
|
66 |
+
{context}
|
67 |
+
</context>
|
68 |
+
|
69 |
+
For your response, each output sentence should be separated by a single newline character.
|
70 |
+
Your sentences should be all contained within <sentences> </sentences> XML tags.
|
71 |
+
"""
|
72 |
+
|
73 |
+
|
74 |
+
def split_into_sentences(text: str, context: str, get_model_func, model, secrets, verbose=False) -> List[str]:
|
75 |
+
return [text]
|
76 |
+
|
77 |
+
|
78 |
+
def split_into_sentences_001(text: str, context: str, get_model_func, model, secrets, verbose=False) -> List[str]:
|
79 |
+
sentences = ''
|
80 |
+
for chunk in get_model_func(model, text, system=sentence_splitting_system_prompt(context),
|
81 |
+
temperature=0, max_tokens=4096,
|
82 |
+
secrets=secrets, verbose=verbose):
|
83 |
+
if 'text' in chunk and chunk['text']:
|
84 |
+
sentences += chunk['text']
|
85 |
+
sentences = get_xml_tag_value(sentences, 'sentences')
|
86 |
+
if sentences:
|
87 |
+
sentences = sentences[0]
|
88 |
+
return sentences.split('\n')
|
89 |
+
|
90 |
+
|
91 |
+
def manage_conversation(model: str,
|
92 |
+
system: str,
|
93 |
+
initial_prompt: str,
|
94 |
+
next_prompts: List[str],
|
95 |
+
final_prompt: str = "",
|
96 |
+
num_turns: int = 25,
|
97 |
+
num_turns_final_mod: int = 9,
|
98 |
+
cli_mode: bool = False,
|
99 |
+
temperature: float = 0.3,
|
100 |
+
max_tokens: int = 4096,
|
101 |
+
seed: int = 1234,
|
102 |
+
secrets: Dict = {},
|
103 |
+
verbose: bool = False,
|
104 |
+
) -> Generator[Dict, None, list]:
|
105 |
+
if seed == 0:
|
106 |
+
seed = random.randint(0, 1000000)
|
107 |
+
random.seed(seed)
|
108 |
+
get_model_func = get_model_api(model)
|
109 |
+
chat_history = []
|
110 |
+
|
111 |
+
turn_count = 0
|
112 |
+
total_thinking_time = 0
|
113 |
+
response_text = ''
|
114 |
+
|
115 |
+
# Initial prompt
|
116 |
+
yield {"role": "user", "content": initial_prompt, "chat_history": chat_history, "initial": True}
|
117 |
+
|
118 |
+
while True:
|
119 |
+
thinking_time = time.time()
|
120 |
+
|
121 |
+
# Determine the current prompt and system
|
122 |
+
if turn_count == 0:
|
123 |
+
current_prompt = initial_prompt
|
124 |
+
elif turn_count % num_turns_final_mod == 0 and final_prompt:
|
125 |
+
current_prompt = final_prompt
|
126 |
+
else:
|
127 |
+
# default if nothing to verify
|
128 |
+
current_prompt = next_prompts[0]
|
129 |
+
|
130 |
+
# Verification step
|
131 |
+
context = chat_history[-2]['content'] if len(chat_history) >= 2 else initial_prompt
|
132 |
+
if context:
|
133 |
+
sentences = split_into_sentences(response_text, context, get_model_func, model, secrets, verbose=verbose)
|
134 |
+
verification_context = "\n".join([msg["content"] for msg in chat_history[-1:] if isinstance(msg["content"], str)])
|
135 |
+
verification_responses = []
|
136 |
+
|
137 |
+
for sentence in sentences:
|
138 |
+
sentence = sentence.strip()
|
139 |
+
if not sentence:
|
140 |
+
continue
|
141 |
+
|
142 |
+
sentence_verification = ''
|
143 |
+
for chunk in get_model_func(model, sentence,
|
144 |
+
system=get_verification_system_prompt(verification_context),
|
145 |
+
temperature=temperature, max_tokens=max_tokens,
|
146 |
+
secrets=secrets, verbose=verbose):
|
147 |
+
if 'text' in chunk and chunk['text']:
|
148 |
+
sentence_verification += chunk['text']
|
149 |
+
else:
|
150 |
+
yield {"role": "usage", "content": chunk}
|
151 |
+
|
152 |
+
valid_score = get_xml_tag_value(sentence_verification, 'score')
|
153 |
+
if valid_score:
|
154 |
+
valid_score = valid_score[0]
|
155 |
+
try:
|
156 |
+
valid_score = ast.literal_eval(valid_score)
|
157 |
+
except Exception as e:
|
158 |
+
print(f"Error parsing score: {valid_score} Error: {e}")
|
159 |
+
# if invalid validation, skip
|
160 |
+
valid_score = 0
|
161 |
+
|
162 |
+
critique = get_xml_tag_value(sentence_verification, 'critique')
|
163 |
+
if critique:
|
164 |
+
critique = critique[0]
|
165 |
+
|
166 |
+
# valid_score_threshold = 0
|
167 |
+
valid_score_threshold = 5
|
168 |
+
if valid_score < valid_score_threshold:
|
169 |
+
verification_responses.append(f"Critique for sentence: '{sentence}'\n{critique}\n")
|
170 |
+
|
171 |
+
current_prompt = "\n".join(verification_responses)
|
172 |
+
if not current_prompt:
|
173 |
+
# current_prompt = next_prompts[turn_count % len(next_prompts)]
|
174 |
+
current_prompt = next_prompts[0]
|
175 |
+
|
176 |
+
# Main LLM call, always responding to verification responses
|
177 |
+
response_text = ''
|
178 |
+
for chunk in get_model_func(model, current_prompt, system=system, chat_history=chat_history,
|
179 |
+
temperature=temperature, max_tokens=max_tokens,
|
180 |
+
secrets=secrets, verbose=verbose):
|
181 |
+
if 'text' in chunk and chunk['text']:
|
182 |
+
response_text += chunk['text']
|
183 |
+
yield {"role": "assistant",
|
184 |
+
"content": chunk['text'],
|
185 |
+
"streaming": True,
|
186 |
+
"chat_history": chat_history,
|
187 |
+
"final": False,
|
188 |
+
"turn_title": False}
|
189 |
+
else:
|
190 |
+
yield {"role": "usage", "content": chunk}
|
191 |
+
|
192 |
+
thinking_time = time.time() - thinking_time
|
193 |
+
total_thinking_time += thinking_time
|
194 |
+
|
195 |
+
if turn_count == 0:
|
196 |
+
turn_title = get_turn_title(response_text)
|
197 |
+
yield {"role": "assistant", "content": turn_title, "turn_title": True, 'thinking_time': thinking_time,
|
198 |
+
'total_thinking_time': total_thinking_time}
|
199 |
+
|
200 |
+
chat_history.append({"role": "user", "content": current_prompt})
|
201 |
+
|
202 |
+
# Check for final answer
|
203 |
+
final_value = get_final_answer(response_text, cli_mode=cli_mode)
|
204 |
+
if final_value:
|
205 |
+
chat_history.append({"role": "assistant", "content": final_value})
|
206 |
+
yield {"role": "assistant", "content": final_value, "streaming": True, "chat_history": chat_history,
|
207 |
+
"final": True}
|
208 |
+
break
|
209 |
+
|
210 |
+
turn_count += 1
|
211 |
+
|
212 |
+
if turn_count % num_turns == 0:
|
213 |
+
if cli_mode:
|
214 |
+
user_continue = input("\nContinue? (y/n): ").lower() == 'y'
|
215 |
+
if not user_continue:
|
216 |
+
break
|
217 |
+
else:
|
218 |
+
yield {"role": "action", "content": "continue?", "chat_history": chat_history}
|
219 |
+
|
220 |
+
# reduce output down to only necessary step
|
221 |
+
thinking = get_xml_tag_value(response_text, 'thinking')
|
222 |
+
if thinking:
|
223 |
+
thinking = thinking[0]
|
224 |
+
else:
|
225 |
+
thinking = ''
|
226 |
+
step_text = get_xml_tag_value(response_text, 'step')
|
227 |
+
if step_text:
|
228 |
+
step_text = step_text[0]
|
229 |
+
else:
|
230 |
+
step_text = ''
|
231 |
+
response_text_tmp = f"{thinking}\n{step_text}".strip()
|
232 |
+
chat_history.append({"role": "assistant", "content": response_text_tmp if response_text_tmp else response_text})
|
233 |
+
response_text = response_text_tmp
|
234 |
+
|
235 |
+
time.sleep(0.001)
|
236 |
+
|
237 |
+
|
238 |
+
def get_defaults() -> Tuple:
|
239 |
+
on_hf_spaces = os.getenv("HF_SPACES", '0') == '1'
|
240 |
+
if on_hf_spaces:
|
241 |
+
initial_prompt = "How many r's are in strawberry?"
|
242 |
+
expected_answer = "3"
|
243 |
+
else:
|
244 |
+
|
245 |
+
initial_prompt = """Can you crack the code?
|
246 |
+
9 2 8 5 (One number is correct but in the wrong position)
|
247 |
+
1 9 3 7 (Two numbers are correct but in the wrong positions)
|
248 |
+
5 2 0 1 (one number is correct and in the right position)
|
249 |
+
6 5 0 7 (nothing is correct)
|
250 |
+
8 5 2 4 (two numbers are correct but in the wrong positions)"""
|
251 |
+
|
252 |
+
expected_answer = "3841"
|
253 |
+
|
254 |
+
system_prompt = """Let us play a game of "take only the most minuscule step toward the solution."
|
255 |
+
<thinking_game>
|
256 |
+
* The assistant's text output must be only the very next possible step.
|
257 |
+
* Use your text output as a scratch pad in addition to a literal output of some next step.
|
258 |
+
* Every time you make a major shift in thinking, output your high-level current thinking in <thinking> </thinking> XML tags.
|
259 |
+
* You should present your response in a way that iterates on that scratch pad space with surrounding textual context.
|
260 |
+
* You win the game if you are able to take the smallest text steps possible while still (on average) heading towards the solution.
|
261 |
+
* Backtracking is allowed, and generating python code is allowed (but will not be executed, but can be used to think), just on average over many text output turns you must head towards the answer.
|
262 |
+
* You must think using first principles, and ensure you identify inconsistencies, errors, etc.
|
263 |
+
* Periodically, you should review your previous reasoning steps and check for errors or inconsistencies. If you find any, correct them.
|
264 |
+
* You MUST always end with a very brief natural language title (it should just describe the analysis, do not give step numbers) of what you did inside <turn_title> </turn_title> XML tags. Only a single title is allowed.
|
265 |
+
* Do not provide the final answer unless the user specifically requests it using the final prompt.
|
266 |
+
* If you have reduced the possible solutions to a small set, try to carefully verify each one before giving your final answer as all of them.
|
267 |
+
* Try to find a useful representation of the problem and that is human interpretable, e.g. a table, list, or map.
|
268 |
+
</thinking_game>
|
269 |
+
Remember to compensate for your flaws:
|
270 |
+
<system_flaws>
|
271 |
+
* Flaw 1: Bad at counting due to tokenization issues. Expand word with spaces between first and then only count that expanded version.
|
272 |
+
* Flaw 2: Grade school or advanced math. Solve such problems very carefully step-by-step.
|
273 |
+
* Flaw 3: Strict positional information understanding, e.g. tic-tac-toe grid. Use techniques to ensure you are correctly interpreting positional information highly accurately.
|
274 |
+
</system_flaws>
|
275 |
+
Final points:
|
276 |
+
* You MUST place a brief justification of your step as thoughts <thinking> </thinking> XML tags.
|
277 |
+
* You MUST place your most minuscule step towards the solution in <step> </step> XML tags.
|
278 |
+
* Any other general thoughts can be placed outside the thinking and step XML tags.
|
279 |
+
"""
|
280 |
+
|
281 |
+
next_prompts = [
|
282 |
+
"Continue your effort to answer the original query. What's your next step?",
|
283 |
+
"What aspect of the problem haven't we considered yet?",
|
284 |
+
"Can you identify any patterns or relationships in the given information?",
|
285 |
+
"How would you verify your current reasoning?",
|
286 |
+
"What's the weakest part of your current approach? How can we strengthen it?",
|
287 |
+
"If you were to explain your current thinking to a novice, what would you say?",
|
288 |
+
"What alternative perspectives could we consider?",
|
289 |
+
"How does your current approach align with the constraints of the problem?",
|
290 |
+
"What assumptions are we making? Are they all necessary?",
|
291 |
+
"If we were to start over with our current knowledge, how would our approach differ?",
|
292 |
+
]
|
293 |
+
|
294 |
+
final_prompt = """Verification checklist:
|
295 |
+
1) Do you have very high confidence in a final answer?
|
296 |
+
2) Have you fully verified your answer with all the time and resources you have?
|
297 |
+
3) If you have very high confidence AND you have fully verified your answer with all resources possible, then put the final answer in <final_answer> </final_answer> XML tags, otherwise please continue to vigorously work on the user's original query.
|
298 |
+
"""
|
299 |
+
|
300 |
+
num_turns = int(os.getenv('NUM_TURNS', '10')) # Number of turns before pausing for continuation
|
301 |
+
num_turns_final_mod = num_turns - 1 # Not required, just an OK value. Could be randomized.
|
302 |
+
|
303 |
+
show_next = False
|
304 |
+
show_cot = False
|
305 |
+
verbose = False
|
306 |
+
|
307 |
+
# model = "claude-3-5-sonnet-20240620"
|
308 |
+
model = "anthropic:claude-3-haiku-20240307"
|
309 |
+
|
310 |
+
temperature = 0.3
|
311 |
+
max_tokens = 4096
|
312 |
+
|
313 |
+
return (model, system_prompt,
|
314 |
+
initial_prompt,
|
315 |
+
expected_answer,
|
316 |
+
next_prompts,
|
317 |
+
num_turns, show_next, final_prompt,
|
318 |
+
temperature, max_tokens,
|
319 |
+
num_turns_final_mod,
|
320 |
+
show_cot,
|
321 |
+
verbose)
|
322 |
+
|
323 |
+
|
324 |
+
if __name__ == '__main__':
|
325 |
+
from src.cli import go_cli
|
326 |
+
|
327 |
+
go_cli()
|