Skip to content
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

make subscription methods more consistent with __contains__ #336

Merged
merged 5 commits into from
Nov 26, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 38 additions & 2 deletions ollama/_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,32 @@

class SubscriptableBaseModel(BaseModel):
def __getitem__(self, key: str) -> Any:
return getattr(self, key)
"""
>>> msg = Message(role='user')
>>> msg['role']
'user'
>>> msg = Message(role='user')
>>> msg['nonexistent']
Traceback (most recent call last):
KeyError: 'nonexistent'
"""
if key in self:
return getattr(self, key)

raise KeyError(key)

def __setitem__(self, key: str, value: Any) -> None:
"""
>>> msg = Message(role='user')
>>> msg['role'] = 'assistant'
>>> msg['role']
'assistant'
>>> tool_call = Message.ToolCall(function=Message.ToolCall.Function(name='foo', arguments={}))
>>> msg = Message(role='user', content='hello')
>>> msg['tool_calls'] = [tool_call]
>>> msg['tool_calls'][0]['function']['name']
'foo'
"""
jmorganca marked this conversation as resolved.
Show resolved Hide resolved
setattr(self, key, value)

def __contains__(self, key: str) -> bool:
Expand Down Expand Up @@ -61,7 +84,20 @@ def __contains__(self, key: str) -> bool:
return False

def get(self, key: str, default: Any = None) -> Any:
return getattr(self, key, default)
"""
>>> msg = Message(role='user')
jmorganca marked this conversation as resolved.
Show resolved Hide resolved
>>> msg.get('role')
'user'
>>> msg = Message(role='user')
>>> msg.get('nonexistent')
>>> msg = Message(role='user')
>>> msg.get('nonexistent', 'default')
'default'
jmorganca marked this conversation as resolved.
Show resolved Hide resolved
>>> msg = Message(role='user', tool_calls=[ Message.ToolCall(function=Message.ToolCall.Function(name='foo', arguments={}))])
>>> msg.get('tool_calls')[0]['function']['name']
'foo'
"""
return self[key] if key in self else default


class Options(SubscriptableBaseModel):
Expand Down