Skip to content

Commit e6e256c

Browse files
committed
feat: Added return description to OpenAI function object's description.
Refs: #11
1 parent 013dbb1 commit e6e256c

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

func_ai/utils/py_function_parser.py

+16-1
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,20 @@ def extract_params(doc_str: str) -> dict[str, str]:
4343
return params
4444

4545

46+
def extract_return_description(docstring):
47+
"""
48+
Extract the return description from a Python docstring.
49+
50+
:param docstring: The docstring to extract the return description from.
51+
:return: The return description, or empty string if no return description is found.
52+
"""
53+
match = re.search(r':return: (.*)', docstring)
54+
if match:
55+
return " " + match.group(1)
56+
else:
57+
return ""
58+
59+
4660
def func_to_json(func) -> dict[str, any]:
4761
"""
4862
Convert a function to a json schema
@@ -68,6 +82,7 @@ def func_to_json(func) -> dict[str, any]:
6882
func_doc = inspect.getdoc(_func)
6983
# parse the docstring to get the description
7084
func_description = ''.join([line for line in func_doc.split("\n") if not line.strip().startswith(':')])
85+
func_description += extract_return_description(func_doc)
7186
# parse the docstring to get the descriptions for each parameter in dict format
7287
param_details = extract_params(func_doc) if func_doc else {}
7388
# attach parameter types to params and exclude fixed args
@@ -87,7 +102,7 @@ def func_to_json(func) -> dict[str, any]:
87102
argspec.args[i] not in inspect.getfullargspec(_func).defaults and argspec.args[
88103
i] not in fixed_args.keys()]
89104
# then return everything in dict
90-
#TODO: Move this to OpenAIFunctionWrapper
105+
# TODO: Move this to OpenAIFunctionWrapper
91106
return {
92107
"name": func_name,
93108
"description": func_description,

tests/test_parser.py

+16
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,15 @@ def func_with_optional_params_double_space_doc(a: str, b: str = "b"):
5454
return 1
5555

5656

57+
def function_with_return_description() -> str:
58+
"""
59+
This function has a return description
60+
61+
:return: This is the return description explaining what it returns
62+
"""
63+
return ""
64+
65+
5766
def test_func_to_json_func_with_no_params():
5867
"""
5968
This function tests func_to_json with a function that has no parameters
@@ -265,3 +274,10 @@ def test_func_to_json_func_with_optional_params_double_space_doc():
265274
}
266275
}
267276
assert _json_fun["required"] == ["a"]
277+
278+
279+
def test_func_with_return():
280+
_json_fun = func_to_json(function_with_return_description)
281+
assert _json_fun["name"] == "function_with_return_description"
282+
print(_json_fun["description"])
283+
assert "This is the return description explaining what it returns" in _json_fun["description"]

0 commit comments

Comments
 (0)