Skip to content

Commit

Permalink
ci: replace Black with Ruff for code formatting
Browse files Browse the repository at this point in the history
- Replace Black with Ruff in development dependencies
- Update CI configuration in ci.yaml to use Ruff
- Reformat codebase using Ruff
- Automating code formatting on pre-commit using ruff
  • Loading branch information
chyroc committed Sep 26, 2024
1 parent 3e417e2 commit 09d2a05
Show file tree
Hide file tree
Showing 19 changed files with 340 additions and 126 deletions.
3 changes: 2 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ jobs:
poetry install
- name: Build
run: |
poetry run black . --check
poetry run ruff check cozepy
poetry run format --check
poetry build
- name: Run tests
run: poetry run pytest
Expand Down
12 changes: 12 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
# Ruff version.
rev: v0.6.7
hooks:
# Run the linter.
- id: ruff
types_or: [ python, pyi ]
args: [ --fix ]
# Run the formatter.
- id: ruff-format
types_or: [ python, pyi ]
5 changes: 5 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
## Pre Commit

```shell
pre-commit install
```
10 changes: 9 additions & 1 deletion cozepy/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
from .auth import OAuthToken, DeviceAuthCode, ApplicationOAuth, Auth, TokenAuth, JWTAuth
from .bots import BotPromptInfo, BotOnboardingInfo, BotModelInfo, BotPluginAPIInfo, BotPluginInfo, Bot, SimpleBot
from .bots import (
BotPromptInfo,
BotOnboardingInfo,
BotModelInfo,
BotPluginAPIInfo,
BotPluginInfo,
Bot,
SimpleBot,
)
from .chat import (
MessageRole,
MessageType,
Expand Down
25 changes: 20 additions & 5 deletions cozepy/auth/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,9 @@ class ApplicationOAuth(object):
App OAuth process to support obtaining token and refreshing token.
"""

def __init__(self, client_id: str, client_secret: str = "", base_url: str = COZE_COM_BASE_URL):
def __init__(
self, client_id: str, client_secret: str = "", base_url: str = COZE_COM_BASE_URL
):
self._client_id = client_id
self._client_secret = client_secret
self._base_url = base_url
Expand All @@ -60,16 +62,22 @@ def jwt_auth(self, private_key: str, kid: str, ttl: int) -> OAuthToken:
"""
Get the token by jwt with jwt auth flow.
"""
jwt_token = self._gen_jwt(self._api_endpoint, private_key, self._client_id, kid, 3600)
jwt_token = self._gen_jwt(
self._api_endpoint, private_key, self._client_id, kid, 3600
)
url = f"{self._base_url}/api/permission/oauth2/token"
headers = {"Authorization": f"Bearer {jwt_token}"}
body = {
"duration_seconds": ttl,
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
}
return self._requester.request("post", url, OAuthToken, headers=headers, body=body)
return self._requester.request(
"post", url, OAuthToken, headers=headers, body=body
)

def _gen_jwt(self, api_endpoint: str, private_key: str, client_id: str, kid: str, ttl: int):
def _gen_jwt(
self, api_endpoint: str, private_key: str, client_id: str, kid: str, ttl: int
):
now = int(time.time())
header = {"alg": "RS256", "typ": "JWT", "kid": kid}
payload = {
Expand Down Expand Up @@ -144,7 +152,14 @@ class JWTAuth(Auth):
The JWT auth flow.
"""

def __init__(self, client_id: str, private_key: str, kid: str, ttl: int = 7200, base_url: str = COZE_COM_BASE_URL):
def __init__(
self,
client_id: str,
private_key: str,
kid: str,
ttl: int = 7200,
base_url: str = COZE_COM_BASE_URL,
):
assert isinstance(client_id, str)
assert isinstance(private_key, str)
assert isinstance(kid, str)
Expand Down
16 changes: 12 additions & 4 deletions cozepy/bots/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,9 @@ def create(
"description": description,
"icon_file_id": icon_file_id,
"prompt_info": prompt_info.model_dump() if prompt_info else None,
"onboarding_info": onboarding_info.model_dump() if onboarding_info else None,
"onboarding_info": onboarding_info.model_dump()
if onboarding_info
else None,
}

return self._requester.request("post", url, Bot, body=body)
Expand Down Expand Up @@ -163,7 +165,9 @@ def update(
"description": description,
"icon_file_id": icon_file_id,
"prompt_info": prompt_info.model_dump() if prompt_info else None,
"onboarding_info": onboarding_info.model_dump() if onboarding_info else None,
"onboarding_info": onboarding_info.model_dump()
if onboarding_info
else None,
}

return self._requester.request("post", url, None, body=body)
Expand Down Expand Up @@ -203,7 +207,9 @@ def retrieve(self, *, bot_id: str) -> Bot:

return self._requester.request("get", url, Bot, params=params)

def list(self, *, space_id: str, page_num: int = 1, page_size: int = 20) -> NumberPaged[SimpleBot]:
def list(
self, *, space_id: str, page_num: int = 1, page_size: int = 20
) -> NumberPaged[SimpleBot]:
"""
Get the bots published as API service.
查看指定空间发布到 Bot as API 渠道的 Bot 列表。
Expand All @@ -227,7 +233,9 @@ def list(self, *, space_id: str, page_num: int = 1, page_size: int = 20) -> Numb
"page_size": page_size,
"page_index": page_num,
}
data = self._requester.request("get", url, self._PrivateListPublishedBotsV1Data, params=params)
data = self._requester.request(
"get", url, self._PrivateListPublishedBotsV1Data, params=params
)
return NumberPaged(
items=data.space_bots,
page_num=page_num,
Expand Down
25 changes: 19 additions & 6 deletions cozepy/chat/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,9 @@ class Message(CozeModel):
updated_at: int = None

@staticmethod
def user_text_message(content: str, meta_data: Optional[Dict[str, str]] = None) -> "Message":
def user_text_message(
content: str, meta_data: Optional[Dict[str, str]] = None
) -> "Message":
return Message(
role=MessageRole.user,
type=MessageType.question,
Expand All @@ -117,7 +119,9 @@ def user_text_message(content: str, meta_data: Optional[Dict[str, str]] = None)
)

@staticmethod
def assistant_text_message(content: str, meta_data: Optional[Dict[str, str]] = None) -> "Message":
def assistant_text_message(
content: str, meta_data: Optional[Dict[str, str]] = None
) -> "Message":
return Message(
role=MessageRole.assistant,
type=MessageType.answer,
Expand Down Expand Up @@ -259,8 +263,13 @@ def __next__(self) -> ChatEvent:
raise StopIteration
elif event == ChatEventType.error:
raise Exception(f"error event: {line}")
elif event in [ChatEventType.conversation_message_delta, ChatEventType.conversation_message_completed]:
return ChatEvent(event=event, message=Message.model_validate(json.loads(data)))
elif event in [
ChatEventType.conversation_message_delta,
ChatEventType.conversation_message_completed,
]:
return ChatEvent(
event=event, message=Message.model_validate(json.loads(data))
)
elif event in [
ChatEventType.conversation_chat_created,
ChatEventType.conversation_chat_in_progress,
Expand Down Expand Up @@ -378,7 +387,9 @@ def _create(
body = {
"bot_id": bot_id,
"user_id": user_id,
"additional_messages": [i.model_dump() for i in additional_messages] if additional_messages else [],
"additional_messages": [i.model_dump() for i in additional_messages]
if additional_messages
else [],
"stream": stream,
"custom_variables": custom_variables,
"auto_save_history": auto_save_history,
Expand All @@ -388,7 +399,9 @@ def _create(
if not stream:
return self._requester.request("post", url, Chat, body=body, stream=stream)

return ChatChatIterator(self._requester.request("post", url, Chat, body=body, stream=stream))
return ChatChatIterator(
self._requester.request("post", url, Chat, body=body, stream=stream)
)

def retrieve(
self,
Expand Down
4 changes: 3 additions & 1 deletion cozepy/conversations/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ def __init__(self, base_url: str, auth: Auth, requester: Requester):
self._requester = requester
self._messages = None

def create(self, *, messages: List[Message] = None, meta_data: Dict[str, str] = None) -> Conversation:
def create(
self, *, messages: List[Message] = None, meta_data: Dict[str, str] = None
) -> Conversation:
"""
Create a conversation.
Conversation is an interaction between a bot and a user, including one or more messages.
Expand Down
8 changes: 6 additions & 2 deletions cozepy/conversations/message/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,9 @@ def list(
"limit": limit,
}

res = self._requester.request("post", url, self._PrivateListMessageResp, params=params, body=body)
res = self._requester.request(
"post", url, self._PrivateListMessageResp, params=params, body=body
)
return LastIDPaged(res.items, res.first_id, res.last_id, res.has_more)

def retrieve(
Expand Down Expand Up @@ -150,7 +152,9 @@ def update(
"meta_data": meta_data,
}

return self._requester.request("post", url, Message, params=params, body=body, data_field="message")
return self._requester.request(
"post", url, Message, params=params, body=body, data_field="message"
)

def delete(
self,
Expand Down
12 changes: 9 additions & 3 deletions cozepy/coze.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,15 +44,19 @@ def workspaces(self) -> "WorkspacesClient":
if not self._workspaces:
from .workspaces import WorkspacesClient

self._workspaces = WorkspacesClient(self._base_url, self._auth, self._requester)
self._workspaces = WorkspacesClient(
self._base_url, self._auth, self._requester
)
return self._workspaces

@property
def conversations(self) -> "ConversationsClient":
if not self._conversations:
from .conversations import ConversationsClient

self._conversations = ConversationsClient(self._base_url, self._auth, self._requester)
self._conversations = ConversationsClient(
self._base_url, self._auth, self._requester
)
return self._conversations

@property
Expand All @@ -76,5 +80,7 @@ def workflows(self) -> "WorkflowsClient":
if not self._workflows:
from .workflows import WorkflowsClient

self._workflows = WorkflowsClient(self._base_url, self._auth, self._requester)
self._workflows = WorkflowsClient(
self._base_url, self._auth, self._requester
)
return self._workflows
20 changes: 14 additions & 6 deletions cozepy/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ class TokenPaged(PagedBase[T]):
return is next_page_token + has_more.
"""

def __init__(self, items: List[T], next_page_token: str = "", has_more: bool = None):
def __init__(
self, items: List[T], next_page_token: str = "", has_more: bool = None
):
has_more = has_more if has_more is not None else next_page_token != ""
super().__init__(items, has_more)
self.next_page_token = next_page_token
Expand All @@ -38,21 +40,27 @@ def __repr__(self):


class NumberPaged(PagedBase[T]):
def __init__(self, items: List[T], page_num: int, page_size: int, total: int = None):
def __init__(
self, items: List[T], page_num: int, page_size: int, total: int = None
):
has_more = len(items) >= page_size
super().__init__(items, has_more)
self.page_num = page_num
self.page_size = page_size
self.total = total

def __repr__(self):
return (
f"NumberPaged(items={self.items}, page_num={self.page_num}, page_size={self.page_size}, total={self.total})"
)
return f"NumberPaged(items={self.items}, page_num={self.page_num}, page_size={self.page_size}, total={self.total})"


class LastIDPaged(PagedBase[T]):
def __init__(self, items: List[T], first_id: str = "", last_id: str = "", has_more: bool = None):
def __init__(
self,
items: List[T],
first_id: str = "",
last_id: str = "",
has_more: bool = None,
):
has_more = has_more if has_more is not None else last_id != ""
super().__init__(items, has_more)
self.first_id = first_id
Expand Down
23 changes: 20 additions & 3 deletions cozepy/request.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,13 @@
from typing import TYPE_CHECKING, Tuple, Optional, Union, List, get_origin, get_args, Iterator
from typing import (
TYPE_CHECKING,
Tuple,
Optional,
Union,
List,
get_origin,
get_args,
Iterator,
)

import requests
from requests import Response
Expand Down Expand Up @@ -47,7 +56,15 @@ def request(
headers = {}
if self._auth:
self._auth.authentication(headers)
r = requests.request(method, url, params=params, headers=headers, json=body, files=files, stream=stream)
r = requests.request(
method,
url,
params=params,
headers=headers,
json=body,
files=files,
stream=stream,
)
if stream:
return r.iter_lines()

Expand Down Expand Up @@ -79,7 +96,7 @@ def __parse_requests_code_msg(
) -> Tuple[Optional[int], str, Optional[T]]:
try:
json = r.json()
except:
except: # noqa: E722
r.raise_for_status()
return

Expand Down
Loading

0 comments on commit 09d2a05

Please sign in to comment.