Skip to content

Commit b5181cf

Browse files
committed
fix: add missing crop helper to data file helper lib
Closes #4011 Change-Id: I41bae6727d4004b453f818b048bc5e9079467af1
1 parent 31cc5a1 commit b5181cf

2 files changed

Lines changed: 24 additions & 0 deletions

File tree

src/google/adk/flows/llm_flows/_code_execution.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,14 @@ class DataFileUtil:
7777
_DATA_FILE_HELPER_LIB = '''
7878
import pandas as pd
7979
80+
def crop(s: str, max_chars: int = 64) -> str:
81+
"""Crops a string to max_chars characters."""
82+
if len(s) <= max_chars:
83+
return s
84+
if max_chars >= 3:
85+
return s[:max_chars - 3] + '...'
86+
return s[:max_chars]
87+
8088
def explore_df(df: pd.DataFrame) -> None:
8189
"""Prints some information about a pandas DataFrame."""
8290

tests/unittests/flows/llm_flows/test_code_execution.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
from google.adk.code_executors.base_code_executor import BaseCodeExecutor
2424
from google.adk.code_executors.built_in_code_executor import BuiltInCodeExecutor
2525
from google.adk.code_executors.code_execution_utils import CodeExecutionResult
26+
from google.adk.flows.llm_flows._code_execution import _DATA_FILE_HELPER_LIB
2627
from google.adk.flows.llm_flows._code_execution import response_processor
2728
from google.adk.models.llm_response import LlmResponse
2829
from google.genai import types
@@ -150,3 +151,18 @@ async def test_logs_executed_code(mock_logger):
150151
mock_logger.debug.assert_called_once_with(
151152
'Executed code:\n```\n%s\n```', 'print("hello")'
152153
)
154+
155+
156+
def test_data_file_helper_lib_defines_crop():
157+
"""`explore_df` in the injected helper lib calls `crop`, which must exist."""
158+
pd = pytest.importorskip('pandas')
159+
namespace = {}
160+
exec(_DATA_FILE_HELPER_LIB, namespace) # pylint: disable=exec-used
161+
162+
crop = namespace['crop']
163+
assert crop('short') == 'short'
164+
assert crop('x' * 100, max_chars=10) == 'x' * 7 + '...'
165+
assert crop('abcdef', max_chars=2) == 'ab'
166+
167+
# Regression for #4011: explore_df raised NameError when crop was undefined.
168+
namespace['explore_df'](pd.DataFrame({'a': [1, 2], 'b': ['x', 'y']}))

0 commit comments

Comments
 (0)