| 29 | |
| 30 | def run_llm_math_chain_factory(llm_math_chain): |
| 31 | async def run_llm_math_chain(question, context=None): |
| 32 | if context is None: |
| 33 | prompt = question |
| 34 | else: |
| 35 | if len(context) == 1: |
| 36 | context_str = f"Context:\n{context[0]}" |
| 37 | else: |
| 38 | context_strs = [] |
| 39 | for i, c in enumerate(context): |
| 40 | context_strs.append(f"Context {i}:\n{c}") |
| 41 | context_str = "\n\n".join(context_strs) |
| 42 | prompt = ( |
| 43 | "Answer the Question based on the Context. When you write down a expression, it MUST ONLY consists of numbers and operators. " |
| 44 | "Here are some guidelines that you will be PANALIZED if you don't follow:\n\n" |
| 45 | " - When you are asked for differences, you consider the absolute value of the difference. Difference of two numbers is always positive." |
| 46 | "For instance, the difference between 1 and 2 is 1, not -1.\n" |
| 47 | " - When you are applying operations (e.g. difference, summation, ratio, etc.) between multiple values in the Context, you must unify the units of those numbers. " |
| 48 | "For instance, you cannot add 1 meter to 1 foot.\n" |
| 49 | " - You must pick the values in the same units if all the values are available in the same units.\n" |
| 50 | " - If not, you must convert them to the same units before applying the operation.\n" |
| 51 | " - You MUST strictly follow the unit (e.g. meter, kilometer, million, etc.) you were asked.\n" |
| 52 | " - If the Context has the numbers in same units as the question, you can directly use them.\n" |
| 53 | " - If the Context has the numbers in different units than the question, you must convert them to the units asked in the question." |
| 54 | "For example, if the question asks for the distance between two cities in kilometers, but the Context has the distance in miles, " |
| 55 | "you must convert the distance to kilometers.\n" |
| 56 | " - If you are asked about a particular number in millions, billions, or any other unit, the number should be written without specifying the unit. " |
| 57 | "For example, if you are asked for 100 millions, it should be written as 100, not 100 million or 100,000,000.\n" |
| 58 | ' - Never introduce a variable. For instance "gazelle_max_speed * 1.4" is not allowed. Pick up a correct number from the given context.\n' |
| 59 | "\n" |
| 60 | f"{context_str}\n\n" |
| 61 | f"Question: {question}\n\n" |
| 62 | ) |
| 63 | response = llm_math_chain.run(prompt) |
| 64 | response = response.split("Answer:")[1].strip() |
| 65 | try: |
| 66 | response = float(response) |
| 67 | # round to 3 decimal places |
| 68 | response = round(response, 3) |
| 69 | response = str(response) |
| 70 | except: |
| 71 | pass |
| 72 | return response |
| 73 | |
| 74 | return run_llm_math_chain |
| 75 | |