I am making a Python LangGraph application in Jupyter Notebook. I have a node that is…
- User
I am making a Python LangGraph application in Jupyter Notebook. I have a node that is giving me problems. Short story short, I created a node that detects if the message is a list and it look them up in in the system files and return them to the next node.
So far so good, the problem I am having is that the node is not working as intended, and I don't understand why. I checked the functions inside and they work perfectly by themselves, but when using them inside the node they don't work. Help me find why and solve this problem please.
This is the text that proves it works:
import ast import asyncio from functools import partial
def check_list(string, *args): try: if isinstance(string, list): return True else: result = ast.literal_eval(string) return isinstance(result, list) except (ValueError, SyntaxError): return False
async def is_python_list(string): loop = asyncio.get_event_loop() partial_check_list = partial(check_list, string) return await loop.run_in_executor(None, partial_check_list)
response = AIMessage("['sql.md', 'delete.md', 'index.md', 'select.md']")
this also works: response = AIMessage(['sql.md', 'delete.md', 'index.md', 'select.md'])
if (await is_python_list(response.content)): context = "OK" else: context = "NO RULES"
print(f"Rules found: {context}") # Rules Found: OK
Now this is the node in question, the state graph and the output on console:
import ast import asyncio import re from concurrent.futures import ThreadPoolExecutor from functools import partial
class RulesFinder: def init(self, config, name="rulesfinder"): self.prompt_template = ChatPromptTemplate.from_template(config['prompts']['rulesfinder']['template']) self.llm = ChatOpenAI( model=config['nodes']['rulesfinder']['model'], openai_api_key=... openai_api_base=... ) self.name = name
def read_file(self, filename, *args): with open(filename, 'r') as f: return f.read() async def async_read_file(self, filename): loop = asyncio.get_event_loop() contents = await loop.run_in_executor(None, self.read_file, filename) return contents async def retrieve_rules(self, directory, response): rules_contents = [] for file_name in response: contents = await self.async_read_file(os.path.join(directory, file_name)) rules_contents.append(contents) return rules_contents def check_list(string, *args): try: if isinstance(string, list): return True else: result = ast.literal_eval(string) return isinstance(result, list) except (ValueError, SyntaxError): return False async def is_python_list(self, string): loop = asyncio.get_event_loop() partial_check_list = partial(self.check_list, string) return await loop.run_in_executor(None, partial_check_list) async def run(self, state): logger.info(f"Ejecutando nodo rulesfinder con estado: {state}") message_content = state["messages"][0].content if state["messages"] else "" index = await self.async_read_file('./rules/index.json') formatted_prompt = self.prompt_template.format_prompt(index=index, message=message_content).to_messages() response = await self.llm.ainvoke(formatted_prompt) logger.info(f"RulesFinder Response: {response}") if (await self.is_python_list(response.content)): context = await self.retrieve_rules('./rules', response.content) else: context = "No Rules" logger.info(f"RulesFinder Rules Found: {context}") # ... return state - Assistant
- User
OK; it went like this now, it didn't output the logger error:
2024-10-21 09:30:43,548 - INFO - RulesFinder Response: content="['commetaries.md', 'cursor.md', 'delete.md', 'label.md', 'identation.md', 'index.md', 'Insert.md', 'sql_intructions.md', 'join.md', 'error_handling.md', 'sql.md', 'select.md', 'sp.md', 'update.md', 'xml.md']" additional_kwargs={'refusal': ''} response_metadata={...}, 'model_name': '...', 'system_fingerprint': '...', 'finish_reason': 'stop', 'logprobs': None} id='...' usage_metadata={...} 2024-10-21 09:30:43,563 - WARNING - Response content is not a valid list. Setting context to 'No Rules'.
- Assistant
- User
I tested the string and it works perfectly outside this, how can I mock this node for testing? I don't want to run all the graph just for this single node.
- Assistant
- User
I don't have it in a module I am using jupyter notebook and the class is defined in a cell
- Assistant
- User
it gave me this error:
RuntimeWarning: coroutine 'RulesFinder.run' was never awaited def init(self, name, parent): RuntimeWarning: Enable tracemalloc to get the object allocation traceback E
ERROR: test_is_python_list (main.TestRulesFinder.test_is_python_list)
Traceback (most recent call last): File ...\ipykernel_18984\3408875045.py", line 19, in test_is_python_list result = loop.run_until_complete(rules_finder.run(state)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "...\Lib\asyncio\base_events.py", line 663, in run_until_complete self._check_running() File "...\Lib\asyncio\base_events.py", line 622, in _check_running raise RuntimeError('This event loop is already running') RuntimeError: This event loop is already running
Ran 1 test in 0.005s
FAILED (errors=1)
- Assistant
- User
Now I am even more puzzled, the tests ran correctly:
RuntimeWarning: coroutine 'RulesFinder.run' was never awaited def init(self, name, parent): RuntimeWarning: Enable tracemalloc to get the object allocation traceback INFO:main:Ejecutando nodo rulesfinder con estado: {'messages': []} INFO:main:RulesFinder Response: INFO:main:Detected a valid list in response content. INFO:main:RulesFinder Rules Found: ['Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock', 'Rule content mock'] .
- Assistant
- User
ok, the only time ".run" are used are within the graph itself:
class State(TypedDict): messages: Annotated[list, add_messages] # ...
graph_builder = StateGraph(State)
...
rulesfinder_node = RulesFinder(hub_config, name="rulesfinder")
...
graph_builder.add_node("rulesfinder", rulesfinder_node.run)
...
graph = graph_builder.compile()
...
test_input = {"messages": [HumanMessage(content="delete on table X..Y when SOMETHING = 10 and ANOTHER = 2")]} result = await graph.ainvoke(test_input) result
- Assistant
- User
OK, so I don't understand why so many executions of the funtion retrieve documents in the mock test. I changed it like this:
async def retrieve_rules(self, directory, response): return [f"Rule content mock {i}" for i, _ in enumerate(response)]
And a logging:
if (await self.is_python_list(response.content)): logger.info(f"Detected a valid list in response content. {response.content}") context = await self.retrieve_rules('./rules', response.content)
and this is the output:
INFO:main:Detected a valid list in response content. ['sql.md', 'delete.md', 'index.md', 'select.md'] INFO:main:RulesFinder Rules Found: ['Rule content mock 0', 'Rule content mock 1', 'Rule content mock 2', 'Rule content mock 3', 'Rule content mock 4', 'Rule content mock 5', 'Rule content mock 6', 'Rule content mock 7', 'Rule content mock 8', 'Rule content mock 9', 'Rule content mock 10', 'Rule content mock 11', 'Rule content mock 12', 'Rule content mock 13', 'Rule content mock 14', 'Rule content mock 15', 'Rule content mock 16', 'Rule content mock 17', 'Rule content mock 18', 'Rule content mock 19', 'Rule content mock 20', 'Rule content mock 21', 'Rule content mock 22', 'Rule content mock 23', 'Rule content mock 24', 'Rule content mock 25', 'Rule content mock 26', 'Rule content mock 27', 'Rule content mock 28', 'Rule content mock 29', 'Rule content mock 30', 'Rule content mock 31', 'Rule content mock 32', 'Rule content mock 33', 'Rule content mock 34', 'Rule content mock 35', 'Rule content mock 36', 'Rule content mock 37', 'Rule content mock 38', 'Rule content mock 39', 'Rule content mock 40', 'Rule content mock 41', 'Rule content mock 42', 'Rule content mock 43', 'Rule content mock 44', 'Rule content mock 45', 'Rule content mock 46', 'Rule content mock 47']
- Assistant
- User
I don't understand what is happening, this is very strange, this is the output (had to change it for print because logger wasn't defined there)
Retrieving rules for response: ['sql.md', 'delete.md', 'index.md', 'select.md'] Generated rules: ['Rule content mock 0', 'Rule content mock 1', 'Rule content mock 2', 'Rule content mock 3', 'Rule content mock 4', 'Rule content mock 5', 'Rule content mock 6', 'Rule content mock 7', 'Rule content mock 8', 'Rule content mock 9', 'Rule content mock 10', 'Rule content mock 11', 'Rule content mock 12', 'Rule content mock 13', 'Rule content mock 14', 'Rule content mock 15', 'Rule content mock 16', 'Rule content mock 17', 'Rule content mock 18', 'Rule content mock 19', 'Rule content mock 20', 'Rule content mock 21', 'Rule content mock 22', 'Rule content mock 23', 'Rule content mock 24', 'Rule content mock 25', 'Rule content mock 26', 'Rule content mock 27', 'Rule content mock 28', 'Rule content mock 29', 'Rule content mock 30', 'Rule content mock 31', 'Rule content mock 32', 'Rule content mock 33', 'Rule content mock 34', 'Rule content mock 35', 'Rule content mock 36', 'Rule content mock 37', 'Rule content mock 38', 'Rule content mock 39', 'Rule content mock 40', 'Rule content mock 41', 'Rule content mock 42', 'Rule content mock 43', 'Rule content mock 44', 'Rule content mock 45', 'Rule content mock 46', 'Rule content mock 47']
- Assistant
- User
OK I think I found what is the problem, I added these two prints and found out why the size is bigger... it is because it is enumerating char instead of strings:
for rule in response: print(rule)
[ ' s q l . m d ' ,
' d e l e t e . m d ' , ... d ' ]
- Assistant
The issue you've identified is a common one when working with strings in Python. It seems that the is being interpreted as a string instead of a list of strings. When you iterate over a string in Python, you actually iterate over each character in that string, which is why you're seeing each character being printed separately.
- User
it works! but it is async? I need my code to be async as a requirement
- Assistant
- User
no, what I meant is if parse_response_content method has to be async or awaited like I did with other check list and other similar methods that I made them async but I don't know if they should be or not async
- Assistant
- User
so if I understand it correctly, the check list and other not I/O should not be declared as async even though they are called in an async function?
- Assistant