Romain Fayoux
commited on
Commit
·
37fb9b0
1
Parent(s):
cdf543a
Correct parsing of final answer
Browse files- langchain_agent.py +22 -3
langchain_agent.py
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 1 |
import os
|
|
|
|
| 2 |
from dotenv import load_dotenv
|
| 3 |
from langchain.agents import create_agent
|
| 4 |
from langgraph.checkpoint.memory import InMemorySaver
|
|
@@ -8,6 +9,7 @@ from langchain.agents.middleware import (
|
|
| 8 |
ToolCallLimitMiddleware,
|
| 9 |
)
|
| 10 |
from langchain.messages import HumanMessage, AIMessage
|
|
|
|
| 11 |
|
| 12 |
load_dotenv()
|
| 13 |
|
|
@@ -39,6 +41,23 @@ If you are asked for a comma separated list, apply the above rules depending of
|
|
| 39 |
{"messages": [HumanMessage(content=question)]},
|
| 40 |
{"configurable": {"thread_id": "1"}, "recursion_limit": 50},
|
| 41 |
)
|
| 42 |
-
answer = response["messages"][-1].text
|
| 43 |
-
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
+
import re
|
| 3 |
from dotenv import load_dotenv
|
| 4 |
from langchain.agents import create_agent
|
| 5 |
from langgraph.checkpoint.memory import InMemorySaver
|
|
|
|
| 9 |
ToolCallLimitMiddleware,
|
| 10 |
)
|
| 11 |
from langchain.messages import HumanMessage, AIMessage
|
| 12 |
+
from smolagents.local_python_executor import fix_final_answer_code
|
| 13 |
|
| 14 |
load_dotenv()
|
| 15 |
|
|
|
|
| 41 |
{"messages": [HumanMessage(content=question)]},
|
| 42 |
{"configurable": {"thread_id": "1"}, "recursion_limit": 50},
|
| 43 |
)
|
| 44 |
+
answer = response["messages"][-1].text
|
| 45 |
+
final_answer = self.extract_final_answer(answer)
|
| 46 |
+
print(f"Agent returning answer: {final_answer}")
|
| 47 |
+
return final_answer
|
| 48 |
+
|
| 49 |
+
def extract_final_answer(self, text):
|
| 50 |
+
"""
|
| 51 |
+
Extracts the text following 'FINAL ANSWER:' using regex.
|
| 52 |
+
"""
|
| 53 |
+
# re.DOTALL allows '.' to match newline characters
|
| 54 |
+
pattern = re.compile(r"FINAL ANSWER:\s*(.*)", re.DOTALL)
|
| 55 |
+
|
| 56 |
+
match = pattern.search(text)
|
| 57 |
+
|
| 58 |
+
if match:
|
| 59 |
+
# .group(1) retrieves the content of the first capturing group
|
| 60 |
+
# .strip() removes leading/trailing whitespace
|
| 61 |
+
return match.group(1).strip()
|
| 62 |
+
else:
|
| 63 |
+
return "No final answer provided, here is the complete text : " + text
|