Repository navigation
✨ agents: write AiiDA code from retrieved examples, and check it #63
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -166,3 +166,101 @@ def tool_output_text(messages: list[Any]) -> str: | |||||||||||||||||||||||||||||||||||||
| content = part.content | ||||||||||||||||||||||||||||||||||||||
| chunks.append(content if isinstance(content, str) else repr(content)) | ||||||||||||||||||||||||||||||||||||||
| return "\n".join(chunks) | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| # --------------------------------------------------------------------------- | ||||||||||||||||||||||||||||||||||||||
| # Code | ||||||||||||||||||||||||||||||||||||||
| # | ||||||||||||||||||||||||||||||||||||||
| # The quantity checks above ask whether a number in an answer came from a tool. | ||||||||||||||||||||||||||||||||||||||
| # A generated snippet raises the same question about names: an AiiDA class or | ||||||||||||||||||||||||||||||||||||||
| # function that exists in no retrieved example is the code equivalent of an | ||||||||||||||||||||||||||||||||||||||
| # invented cutoff, and it is worse, because the user finds out by running it. | ||||||||||||||||||||||||||||||||||||||
| # | ||||||||||||||||||||||||||||||||||||||
| # Two checks, deliberately narrow. Anything broader produces false positives, | ||||||||||||||||||||||||||||||||||||||
| # and this module's whole premise is that a warning nobody believes protects | ||||||||||||||||||||||||||||||||||||||
| # nothing -- a check that fires on `qb.append` because lists also have | ||||||||||||||||||||||||||||||||||||||
| # `append` would train people to ignore the one that matters. | ||||||||||||||||||||||||||||||||||||||
| # --------------------------------------------------------------------------- | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| #: A fenced block the answer presents as Python. | ||||||||||||||||||||||||||||||||||||||
| _PY_BLOCK = re.compile( | ||||||||||||||||||||||||||||||||||||||
| r"```(?:python|py|pycon)?\s*\n(?P<code>.*?)```", re.DOTALL | re.IGNORECASE | ||||||||||||||||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| def python_blocks(answer: str) -> list[str]: | ||||||||||||||||||||||||||||||||||||||
| """Every fenced code block in ``answer`` that is offered as Python. | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| An unlabelled fence counts: models routinely omit the language, and a | ||||||||||||||||||||||||||||||||||||||
| snippet the user will paste into ``verdi shell`` is Python whether or not | ||||||||||||||||||||||||||||||||||||||
| it said so. | ||||||||||||||||||||||||||||||||||||||
| """ | ||||||||||||||||||||||||||||||||||||||
| return [m.group("code") for m in _PY_BLOCK.finditer(answer)] | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| def syntax_errors(answer: str) -> list[str]: | ||||||||||||||||||||||||||||||||||||||
| """Blocks in ``answer`` that are not parseable Python, with the reason. | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| Cheap, deterministic, and zero false positives on real code: if CPython | ||||||||||||||||||||||||||||||||||||||
| cannot parse it, no user can run it. Worth checking separately from the | ||||||||||||||||||||||||||||||||||||||
| symbol check because it catches the failure that wastes the most of a | ||||||||||||||||||||||||||||||||||||||
| user's time for the least excuse. | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| Console transcripts are skipped --- a block of ``verdi`` commands or | ||||||||||||||||||||||||||||||||||||||
| ``>>>`` prompts is not meant to parse as a module. | ||||||||||||||||||||||||||||||||||||||
| """ | ||||||||||||||||||||||||||||||||||||||
| import ast | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| problems = [] | ||||||||||||||||||||||||||||||||||||||
| for block in python_blocks(answer): | ||||||||||||||||||||||||||||||||||||||
| stripped = block.strip() | ||||||||||||||||||||||||||||||||||||||
| if not stripped or stripped.startswith((">>>", "$", "verdi ")): | ||||||||||||||||||||||||||||||||||||||
| continue | ||||||||||||||||||||||||||||||||||||||
|
Comment on lines
+215
to
+218
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win Skip transcript markers on every line. A Proposed fix for block in python_blocks(answer):
stripped = block.strip()
- if not stripped or stripped.startswith((">>>", "$", "verdi ")):
+ lines = [line.lstrip() for line in stripped.splitlines()]
+ if not stripped or any(
+ line.startswith((">>>", "$", "verdi ")) for line in lines
+ ):
continue📝 Committable suggestion
Suggested change
🤖 Prompt for AI Agents |
||||||||||||||||||||||||||||||||||||||
| try: | ||||||||||||||||||||||||||||||||||||||
| ast.parse(stripped) | ||||||||||||||||||||||||||||||||||||||
| except SyntaxError as exc: | ||||||||||||||||||||||||||||||||||||||
| problems.append(f"{exc.msg} (line {exc.lineno})") | ||||||||||||||||||||||||||||||||||||||
| return problems | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| def _imported_aiida_names(code: str) -> set[str]: | ||||||||||||||||||||||||||||||||||||||
| """Names the snippet imports from AiiDA, e.g. ``QueryBuilder``. | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| Only imports, and only from an ``aiida`` module. This is the narrowest | ||||||||||||||||||||||||||||||||||||||
| check that still catches the failure worth catching: a hallucinated class | ||||||||||||||||||||||||||||||||||||||
| or helper is almost always *imported*, and an import naming something that | ||||||||||||||||||||||||||||||||||||||
| does not exist fails at the very first line. Attribute and method names are | ||||||||||||||||||||||||||||||||||||||
| deliberately not checked --- ``.append``, ``.get``, ``.all`` belong to | ||||||||||||||||||||||||||||||||||||||
| builtins as often as to AiiDA, and flagging them would drown the signal. | ||||||||||||||||||||||||||||||||||||||
| """ | ||||||||||||||||||||||||||||||||||||||
| import ast | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| names: set[str] = set() | ||||||||||||||||||||||||||||||||||||||
| try: | ||||||||||||||||||||||||||||||||||||||
| tree = ast.parse(code) | ||||||||||||||||||||||||||||||||||||||
| except SyntaxError: | ||||||||||||||||||||||||||||||||||||||
| return names # reported by syntax_errors, not here | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| for node in ast.walk(tree): | ||||||||||||||||||||||||||||||||||||||
| if isinstance(node, ast.ImportFrom): | ||||||||||||||||||||||||||||||||||||||
| module = node.module or "" | ||||||||||||||||||||||||||||||||||||||
| if module == "aiida" or module.startswith("aiida."): | ||||||||||||||||||||||||||||||||||||||
| names.update(alias.name for alias in node.names) | ||||||||||||||||||||||||||||||||||||||
| return names | ||||||||||||||||||||||||||||||||||||||
|
Comment on lines
+244
to
+249
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win Check direct AiiDA imports.
Proposed fix for node in ast.walk(tree):
if isinstance(node, ast.ImportFrom):
module = node.module or ""
if module == "aiida" or module.startswith("aiida."):
names.update(alias.name for alias in node.names)
+ elif isinstance(node, ast.Import):
+ names.update(
+ alias.name
+ for alias in node.names
+ if alias.name == "aiida" or alias.name.startswith("aiida.")
+ )📝 Committable suggestion
Suggested change
🤖 Prompt for AI Agents |
||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| def ungrounded_symbols(answer: str, evidence: str) -> set[str]: | ||||||||||||||||||||||||||||||||||||||
| """AiiDA names imported in ``answer``'s code that no tool output mentions. | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| Args: | ||||||||||||||||||||||||||||||||||||||
| answer: The reply shown to the user, code blocks included. | ||||||||||||||||||||||||||||||||||||||
| evidence: Everything the tools returned during the run. | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| Returns: | ||||||||||||||||||||||||||||||||||||||
| Imported AiiDA names absent from every tool return. Empty means each | ||||||||||||||||||||||||||||||||||||||
| one appeared in something the agent actually retrieved. | ||||||||||||||||||||||||||||||||||||||
| """ | ||||||||||||||||||||||||||||||||||||||
| imported: set[str] = set() | ||||||||||||||||||||||||||||||||||||||
| for block in python_blocks(answer): | ||||||||||||||||||||||||||||||||||||||
| imported |= _imported_aiida_names(block) | ||||||||||||||||||||||||||||||||||||||
| return {name for name in imported if name not in evidence} | ||||||||||||||||||||||||||||||||||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -39,6 +39,7 @@ | |
| "get_node_outputs", | ||
| "search_structures", | ||
| "search_aiida_docs", | ||
| "search_aiida_code", | ||
| } | ||
|
|
||
|
|
||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Make the tool-selection rules mutually exclusive.
“How-to guidance” includes code-writing requests. Rule 5 can therefore direct the agent to
search_aiida_docsinstead of the requiredsearch_aiida_code. Exclude requests for Python code from Rule 5.Proposed fix
📝 Committable suggestion
🤖 Prompt for AI Agents