-
Couldn't load subscription status.
- Fork 844
Passing Functions as Tools #321
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
Merged
Merged
Changes from 23 commits
Commits
Show all changes
32 commits
Select commit
Hold shift + click to select a range
4383603
WIP tool parsing
ParthSareen afe7db6
Managing multiple type options
ParthSareen 8fee892
Add tool parsing and processing
ParthSareen 0e5a940
Formatting and todos
ParthSareen 1ef75a7
TODOs
ParthSareen 93c7a63
wip
ParthSareen e5dc2b8
add annotations import for old tests
ParthSareen aa20015
Exhaustive type matching
ParthSareen d79538e
Ruff fix
ParthSareen 97aa167
WIP trying tests out
ParthSareen 8ec5123
Trying stuff out
ParthSareen efb775b
Multi-line docstrings and exhaustive tests
ParthSareen 2efa54a
Walrus op for cleanup
ParthSareen 1f089f7
Stringify return type arrays to not break server
ParthSareen fe8d143
WIP
ParthSareen 67321a8
Organization, cleanup, pydantic serialization, update tests
ParthSareen 2cc0b40
Typing fix
ParthSareen e68700c
Python3.8+ compatibility
ParthSareen f452fab
Add str -> str valid json mapping and add test
ParthSareen ca16670
Code cleanup and organization
ParthSareen 7dcb598
Test unhappy parse path
ParthSareen 7c5c294
Code cleanup + organize and add tests for type serialization
ParthSareen 16c868a
Update to have graceful handling and not raise - added tests as well
ParthSareen 718412a
Making good use of pydantic
ParthSareen e7bb55f
Add yields and test
ParthSareen 7396ab6
Simplified parsing and fixed required - added tests
ParthSareen 0d9eec0
Add tool.model_validate
ParthSareen ed3ba8a
Code style updates
ParthSareen a4ec34a
Add better messaging for chat
ParthSareen 6d9c156
Addressing comments + cleanup + optional tool
ParthSareen c5c61a3
Better docstring parsing and some fixes
ParthSareen b0e0409
Bugfix/image encoding (#327)
ParthSareen File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,109 @@ | ||
| import sys | ||
| from typing import Any, List, Mapping, Optional, Sequence, Union, get_origin, get_args | ||
| from collections.abc import Set | ||
| from typing import Dict, Set as TypeSet, TypeVar | ||
|
|
||
| T = TypeVar('T') | ||
| if sys.version_info >= (3, 10): | ||
| from types import UnionType | ||
|
|
||
| def is_union(tp: Any) -> bool: | ||
| return get_origin(tp) in (Union, UnionType) | ||
|
|
||
| else: | ||
| UnionType = Union[T] | ||
|
|
||
| def is_union(tp: Any) -> bool: | ||
| return get_origin(tp) is Union | ||
|
|
||
|
|
||
| # Python doesn't have a type serializer, so we need to map types to JSON types | ||
| TYPE_MAP = { | ||
ParthSareen marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| # Basic types | ||
| int: 'integer', | ||
| 'int': 'integer', | ||
| 'integer': 'integer', | ||
| str: 'string', | ||
| 'str': 'string', | ||
| 'string': 'string', | ||
| float: 'number', | ||
| 'float': 'number', | ||
| 'number': 'number', | ||
| bool: 'boolean', | ||
| 'bool': 'boolean', | ||
| 'boolean': 'boolean', | ||
| type(None): 'null', | ||
| None: 'null', | ||
| 'None': 'null', | ||
| 'null': 'null', | ||
| # Collection types | ||
| list: 'array', | ||
| 'list': 'array', | ||
| List: 'array', | ||
| 'List': 'array', | ||
| Sequence: 'array', | ||
| 'Sequence': 'array', | ||
| tuple: 'array', | ||
| 'tuple': 'array', | ||
| set: 'array', | ||
| 'set': 'array', | ||
| Set: 'array', | ||
| TypeSet: 'array', | ||
| 'Set': 'array', | ||
| 'array': 'array', | ||
| # Mapping types | ||
| dict: 'object', | ||
| 'dict': 'object', | ||
| Dict: 'object', | ||
| 'Dict': 'object', | ||
| Mapping: 'object', | ||
| 'Mapping': 'object', | ||
| 'object': 'object', | ||
| Any: 'string', | ||
| 'Any': 'string', | ||
| } | ||
|
|
||
|
|
||
| def _map_type(python_type: Any) -> str: | ||
| # Handle generic types (List[int], Dict[str, int], etc.) | ||
| origin = get_origin(python_type) | ||
| if origin is not None: | ||
| # Get the base type (List, Dict, etc.) | ||
| base_type = TYPE_MAP.get(origin, None) | ||
| if base_type: | ||
| return base_type | ||
| # If it's a subclass of known abstract base classes, map to appropriate type | ||
| if isinstance(origin, type): | ||
| if issubclass(origin, (list, Sequence, tuple, set, Set)): | ||
| return 'array' | ||
| if issubclass(origin, (dict, Mapping)): | ||
| return 'object' | ||
|
|
||
| # Handle both type objects and type references (older Python versions) | ||
| type_key = python_type | ||
| if isinstance(python_type, type): | ||
| type_key = python_type | ||
| elif isinstance(python_type, str): | ||
| type_key = python_type | ||
|
|
||
| # If type not found in map, try to get the type name | ||
| if type_key not in TYPE_MAP and hasattr(python_type, '__name__'): | ||
| type_key = python_type.__name__ | ||
|
|
||
| if type_key in TYPE_MAP: | ||
| return TYPE_MAP[type_key] | ||
|
|
||
| raise ValueError(f'Could not map Python type {python_type} to a valid JSON type') | ||
|
|
||
|
|
||
| def get_json_type(python_type: Union[type, UnionType, Optional[T]]) -> Union[str, List[str]]: | ||
| # Handle Optional types (Union[type, None] and type | None) | ||
| if is_union(python_type): | ||
| args = get_args(python_type) | ||
| # Filter out None/NoneType from union args | ||
| if non_none_args := [arg for arg in args if arg not in (None, type(None))]: | ||
| if len(non_none_args) == 1: | ||
| return _map_type(non_none_args[0]) | ||
| # For multiple return types (e.g., int | str | None), return stringified array of types -> "['integer', 'string', 'null']" | ||
| return str([_map_type(arg) for arg in non_none_args]).replace(' ', '') | ||
| return _map_type(python_type) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,110 @@ | ||
| from __future__ import annotations | ||
| from typing import Any, Callable, Union, get_args | ||
| from ollama._json_type_map import is_union | ||
| from ollama._types import Tool | ||
| from typing import Dict | ||
|
|
||
|
|
||
| def _parse_docstring(func: Callable, doc_string: Union[str, None]) -> tuple[str, Dict[str, str]]: | ||
| # Extract description from docstring - get all lines before Args: | ||
| if not doc_string: | ||
| return '', {} | ||
|
|
||
| description_lines = [] | ||
| for line in doc_string.split('\n'): | ||
| line = line.strip() | ||
| if line.startswith('Args:'): | ||
| break | ||
| if line: | ||
| description_lines.append(line) | ||
|
|
||
| description = ' '.join(description_lines).strip() | ||
|
|
||
| if 'Args:' not in doc_string: | ||
| return description, {} | ||
|
|
||
| args_section = doc_string.split('Args:')[1] | ||
ParthSareen marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| if 'Returns:' in args_section: | ||
| args_section = args_section.split('Returns:')[0] | ||
|
|
||
| param_descriptions = {} | ||
| current_param = None | ||
| param_desc_lines = [] | ||
| indent_level = None | ||
|
|
||
| for line in args_section.split('\n'): | ||
ParthSareen marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| stripped_line = line.strip() | ||
| if not stripped_line: | ||
| continue | ||
|
|
||
| # Check for new parameter | ||
| for param_name in func.__annotations__: | ||
| if param_name == 'return': | ||
| continue | ||
| if stripped_line.startswith(f'{param_name}:') or stripped_line.startswith(f'{param_name} ') or stripped_line.startswith(f'{param_name}('): | ||
| # Save previous parameter if exists | ||
| if current_param: | ||
| param_descriptions[current_param] = ' '.join(param_desc_lines).strip() | ||
| param_desc_lines = [] | ||
|
|
||
| current_param = param_name | ||
| # Get description after parameter name | ||
| desc_part = stripped_line.split(':', 1)[1].strip() if ':' in stripped_line else '' | ||
| if desc_part: | ||
| param_desc_lines.append(desc_part) | ||
| indent_level = len(line) - len(line.lstrip()) | ||
| break | ||
| else: | ||
| # Handle continuation lines | ||
| if current_param and line.startswith(' ' * (indent_level + 4 if indent_level else 0)): | ||
| param_desc_lines.append(stripped_line) | ||
| elif current_param and stripped_line: | ||
| # Different indentation means new parameter | ||
| param_descriptions[current_param] = ' '.join(param_desc_lines).strip() | ||
| param_desc_lines = [] | ||
| current_param = None | ||
|
|
||
| if current_param: | ||
| param_descriptions[current_param] = ' '.join(param_desc_lines).strip() | ||
|
|
||
| # Verify all parameters have descriptions | ||
| for param_name in func.__annotations__: | ||
| if param_name == 'return': | ||
| continue | ||
| if param_name not in param_descriptions: | ||
| param_descriptions[param_name] = '' | ||
|
|
||
| return description, param_descriptions | ||
|
|
||
|
|
||
| def is_optional_type(python_type: Any) -> bool: | ||
| if is_union(python_type): | ||
| args = get_args(python_type) | ||
| return any(arg in (None, type(None)) for arg in args) | ||
| return False | ||
|
|
||
|
|
||
| def convert_function_to_tool(func: Callable) -> Tool: | ||
| doc_string = func.__doc__ | ||
ParthSareen marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| description, param_descriptions = _parse_docstring(func, doc_string) | ||
|
|
||
| parameters = Tool.Function.Parameters(type='object', properties={}, required=[]) | ||
|
|
||
| for param_name, param_type in func.__annotations__.items(): | ||
| if param_name == 'return': | ||
| continue | ||
|
|
||
| parameters.properties[param_name] = Tool.Function.Parameters.Property(type=param_type, description=param_descriptions.get(param_name, '')) | ||
|
|
||
| if not is_optional_type(param_type): | ||
| parameters.required.append(param_name) | ||
|
|
||
| return Tool( | ||
| function=Tool.Function( | ||
| name=func.__name__, | ||
| description=description, | ||
| parameters=parameters, | ||
| return_type=None, | ||
| ) | ||
| ) | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.