Check to make sure that a function used by Letta returned a valid response. Truncates to return_char_limit if necessary. Responses need to be strings (or None) that fall under a certain text count limit.
(function_response_string: any, return_char_limit: int, strict: bool = False, truncate: bool = True)
| 841 | |
| 842 | |
| 843 | def validate_function_response(function_response_string: any, return_char_limit: int, strict: bool = False, truncate: bool = True) -> str: |
| 844 | """Check to make sure that a function used by Letta returned a valid response. Truncates to return_char_limit if necessary. |
| 845 | |
| 846 | Responses need to be strings (or None) that fall under a certain text count limit. |
| 847 | """ |
| 848 | if not isinstance(function_response_string, str): |
| 849 | # Soft correction for a few basic types |
| 850 | |
| 851 | if function_response_string is None: |
| 852 | # function_response_string = "Empty (no function output)" |
| 853 | function_response_string = "None" # backcompat |
| 854 | |
| 855 | elif isinstance(function_response_string, dict): |
| 856 | if strict: |
| 857 | # TODO add better error message |
| 858 | raise ValueError(function_response_string) |
| 859 | |
| 860 | # Allow dict through since it will be cast to json.dumps() |
| 861 | try: |
| 862 | # TODO find a better way to do this that won't result in double escapes |
| 863 | function_response_string = json_dumps(function_response_string) |
| 864 | except: |
| 865 | raise ValueError(function_response_string) |
| 866 | |
| 867 | else: |
| 868 | if strict: |
| 869 | # TODO add better error message |
| 870 | raise ValueError(function_response_string) |
| 871 | |
| 872 | # Try to convert to a string, but throw a warning to alert the user |
| 873 | try: |
| 874 | function_response_string = str(function_response_string) |
| 875 | except: |
| 876 | raise ValueError(function_response_string) |
| 877 | |
| 878 | # Now check the length and make sure it doesn't go over the limit |
| 879 | # TODO we should change this to a max token limit that's variable based on tokens remaining (or context-window) |
| 880 | if truncate and len(function_response_string) > return_char_limit: |
| 881 | print( |
| 882 | f"{CLI_WARNING_PREFIX}function return was over limit ({len(function_response_string)} > {return_char_limit}) and was truncated" |
| 883 | ) |
| 884 | function_response_string = f"{function_response_string[:return_char_limit]}... [NOTE: function output was truncated since it exceeded the character limit ({len(function_response_string)} > {return_char_limit})]" |
| 885 | |
| 886 | return function_response_string |
| 887 | |
| 888 | |
| 889 | def list_agent_config_files(sort="last_modified"): |
no test coverage detected