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

feat: Add v1/users/me API endpoint to retrieve current authorized user info #177

Merged
merged 1 commit into from
Jan 23, 2025

Conversation

chyroc
Copy link
Collaborator

@chyroc chyroc commented Jan 23, 2025

Summary by CodeRabbit

Release Notes

  • New Features

    • Added user retrieval functionality to the Coze API client
    • Introduced support for fetching current user information in both synchronous and asynchronous modes
  • Documentation

    • Added example script demonstrating user information retrieval
    • Included logging and authentication mechanisms for API interaction
  • Tests

    • Implemented comprehensive test suite for user-related methods
    • Added synchronous and asynchronous test cases for user retrieval

@chyroc chyroc added the feature label Jan 23, 2025
Copy link

coderabbitai bot commented Jan 23, 2025

Walkthrough

This pull request introduces user-related functionality to the Coze API library. It adds a new users module with synchronous and asynchronous clients for retrieving user information. The changes include creating a User class, implementing UsersClient and AsyncUsersClient with a me() method to fetch the current user's details, and updating the main Coze and AsyncCoze classes to support these new user-related operations. An example script and corresponding test suite are also provided to demonstrate and validate the new functionality.

Changes

File Changes
cozepy/__init__.py - Added import for User from .users module
- Updated __all__ list to include "User"
cozepy/coze.py - Added _users private attribute to Coze and AsyncCoze classes
- Added users property to both classes for lazy initialization of user clients
cozepy/users/__init__.py - Introduced User class with user attributes
- Created UsersClient and AsyncUsersClient classes
- Implemented me() method for both synchronous and asynchronous user retrieval
examples/users_me.py - Added utility functions for API base URL and token retrieval
- Created example script demonstrating user information retrieval
tests/test_users.py - Added test suite for synchronous and asynchronous user retrieval
- Implemented mock responses for testing me() method

Sequence Diagram

sequenceDiagram
    participant Client as Coze Client
    participant UsersClient as Users Client
    participant API as Coze API

    Client->>UsersClient: users.me()
    UsersClient->>API: GET /v1/users/me
    API-->>UsersClient: Return User Information
    UsersClient-->>Client: Return User Object
Loading

Possibly related PRs

Poem

🐰 A Rabbit's Ode to User Discovery

In Coze's realm, a new path unfurls,
Where user secrets gently swirl
With me() method, swift and bright,
Retrieving data, pure delight!
A bunny's code, both sync and free 🌟

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

codecov bot commented Jan 23, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 90.01%. Comparing base (2c3d507) to head (42375d3).
Report is 1 commits behind head on main.

@@            Coverage Diff             @@
##             main     #177      +/-   ##
==========================================
+ Coverage   89.89%   90.01%   +0.12%     
==========================================
  Files          63       65       +2     
  Lines        5768     5840      +72     
==========================================
+ Hits         5185     5257      +72     
  Misses        583      583              
Files with missing lines Coverage Δ
cozepy/__init__.py 100.00% <100.00%> (ø)
cozepy/coze.py 97.76% <100.00%> (+0.18%) ⬆️
cozepy/users/__init__.py 100.00% <100.00%> (ø)
tests/test_users.py 100.00% <100.00%> (ø)

@chyroc chyroc merged commit a3bf691 into main Jan 23, 2025
14 of 15 checks passed
@chyroc chyroc deleted the users-me branch January 23, 2025 14:33
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (6)
cozepy/users/__init__.py (3)

9-13: Consider adding field validations.

The User model could benefit from field validations to ensure data integrity:

  • user_id: Format validation (e.g., UUID, specific pattern)
  • avatar_url: URL format validation
 class User(CozeModel):
-    user_id: str
-    user_name: str
-    nick_name: str
-    avatar_url: str
+    user_id: str = Field(pattern=r'^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$')
+    user_name: str = Field(min_length=1)
+    nick_name: str = Field(min_length=1)
+    avatar_url: str = Field(pattern=r'^https?://.+')

22-25: Add docstring to document the method behavior and exceptions.

The me method should document its behavior, parameters, return type, and possible exceptions.

     def me(self, **kwargs) -> User:
+        """Retrieve the current authorized user's information.
+
+        Args:
+            **kwargs: Additional request parameters.
+                     Supported keys:
+                     - headers (Optional[dict]): Additional request headers.
+
+        Returns:
+            User: The current user's information.
+
+        Raises:
+            CozeAPIError: If the API request fails.
+            ValueError: If the response cannot be parsed.
+        """
         url = f"{self._base_url}/v1/users/me"
         headers: Optional[dict] = kwargs.get("headers")
         return self._requester.request("get", url, False, User, headers=headers)

34-37: Add docstring and consider reducing code duplication.

  1. Add docstring to document the method behavior and exceptions.
  2. Consider extracting common code between sync and async clients into a base class or mixin.
     async def me(self, **kwargs) -> User:
+        """Retrieve the current authorized user's information asynchronously.
+
+        Args:
+            **kwargs: Additional request parameters.
+                     Supported keys:
+                     - headers (Optional[dict]): Additional request headers.
+
+        Returns:
+            User: The current user's information.
+
+        Raises:
+            CozeAPIError: If the API request fails.
+            ValueError: If the response cannot be parsed.
+        """
         url = f"{self._base_url}/v1/users/me"
         headers: Optional[dict] = kwargs.get("headers")
         return await self._requester.arequest("get", url, False, User, headers=headers)

Consider creating a base class to reduce duplication:

class BaseUsersClient:
    def __init__(self, base_url: str, auth: Auth, requester: Requester):
        self._base_url = remove_url_trailing_slash(base_url)
        self._auth = auth
        self._requester = requester

    def _get_me_url(self) -> str:
        return f"{self._base_url}/v1/users/me"
tests/test_users.py (3)

9-24: Enhance test coverage with edge cases.

Consider adding test cases for:

  1. Error responses (401, 403, 404, 500)
  2. Malformed responses
  3. Empty or null fields
def mock_retrieve_users_me_error(respx_mock, status_code: int) -> httpx.Response:
    response = httpx.Response(
        status_code,
        json={"error": {"code": "unauthorized", "message": "Invalid token"}},
        headers={logid_key(): random_hex(10)},
    )
    respx_mock.get("/v1/users/me").mock(response)
    return response

27-38: Add more assertions for comprehensive testing.

Consider adding assertions for:

  1. All user fields (user_name, nick_name, avatar_url)
  2. Response headers
  3. Raw response data structure
     def test_sync_users_retrieve_me(self, respx_mock):
         coze = Coze(auth=TokenAuth(token="token"))
 
         mock_user = mock_retrieve_users_me(respx_mock)
 
         user = coze.users.me()
         assert user
         assert user.response.logid == mock_user.response.logid
         assert user.user_id == mock_user.user_id
+        assert user.user_name == mock_user.user_name
+        assert user.nick_name == mock_user.nick_name
+        assert user.avatar_url == mock_user.avatar_url
+        assert user.model_dump() == mock_user.model_dump()
+        assert user.response.status_code == 200

40-51: Add more assertions and consider reducing test code duplication.

  1. Add assertions for all user fields and response data.
  2. Consider using a base test class or fixtures to reduce duplication between sync and async tests.
@pytest.fixture
def expected_assertions():
    def _assert_user(actual_user: User, mock_user: User):
        assert actual_user
        assert actual_user.response.logid == mock_user.response.logid
        assert actual_user.user_id == mock_user.user_id
        assert actual_user.user_name == mock_user.user_name
        assert actual_user.nick_name == mock_user.nick_name
        assert actual_user.avatar_url == mock_user.avatar_url
        assert actual_user.model_dump() == mock_user.model_dump()
        assert actual_user.response.status_code == 200
    return _assert_user
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2c3d507 and 42375d3.

📒 Files selected for processing (5)
  • cozepy/__init__.py (2 hunks)
  • cozepy/coze.py (5 hunks)
  • cozepy/users/__init__.py (1 hunks)
  • examples/users_me.py (1 hunks)
  • tests/test_users.py (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: test (Python 3.8 on macOS)
  • GitHub Check: test (Python 3.8 on Windows)
🔇 Additional comments (8)
examples/users_me.py (2)

15-23: LGTM!

The function is well-implemented with good documentation and proper fallback handling.


39-42: LGTM!

The function is well-implemented with proper level mapping and fallback handling.

cozepy/__init__.py (1)

94-94: LGTM!

The changes follow the module's established patterns for imports and exports.

Also applies to: 293-294

cozepy/coze.py (5)

18-18: LGTM! Import follows consistent pattern.

The import is correctly placed within the TYPE_CHECKING block and follows the established import style.


46-46: LGTM! Field declaration follows class pattern.

The _users field is correctly declared as Optional[UsersClient] and initialized to None, matching the pattern used for other client fields.


134-140: LGTM! Property implementation follows established pattern.

The users property correctly implements lazy initialization and follows the consistent pattern used throughout the class.


165-165: LGTM! Async field declaration follows class pattern.

The _users field is correctly declared as Optional[AsyncUsersClient] and initialized to None, matching the pattern used for other async client fields.


254-260: LGTM! Async property implementation follows established pattern.

The async users property correctly implements lazy initialization and follows the consistent pattern used throughout the class.

Comment on lines +49 to +53
if __name__ == "__main__":
coze = Coze(auth=TokenAuth(get_coze_api_token()), base_url=get_coze_api_base())

user = coze.users.me(**kwargs)
print(user)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add error handling for the API call.

Wrap the API call in a try-except block to handle potential errors gracefully.

 if __name__ == "__main__":
-    coze = Coze(auth=TokenAuth(get_coze_api_token()), base_url=get_coze_api_base())
+    try:
+        coze = Coze(auth=TokenAuth(get_coze_api_token()), base_url=get_coze_api_base())
 
-    user = coze.users.me(**kwargs)
-    print(user)
+        user = coze.users.me(**kwargs)
+        print(user)
+    except Exception as e:
+        logging.error(f"Failed to retrieve user info: {str(e)}")
+        sys.exit(1)

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +25 to +36
def get_coze_api_token(workspace_id: Optional[str] = None) -> str:
# Get an access_token through personal access token or oauth.
coze_api_token = os.getenv("COZE_API_TOKEN")
if coze_api_token:
return coze_api_token

coze_api_base = get_coze_api_base()

device_oauth_app = DeviceOAuthApp(client_id="57294420732781205987760324720643.app.coze", base_url=coze_api_base)
device_code = device_oauth_app.get_device_code(workspace_id)
print(f"Please Open: {device_code.verification_url} to get the access token")
return device_oauth_app.get_access_token(device_code=device_code.device_code, poll=True).access_token
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve security and error handling.

  1. Move the client_id to environment variables or configuration.
  2. Add error handling for OAuth flow failures.
 def get_coze_api_token(workspace_id: Optional[str] = None) -> str:
     # Get an access_token through personal access token or oauth.
     coze_api_token = os.getenv("COZE_API_TOKEN")
     if coze_api_token:
         return coze_api_token
 
     coze_api_base = get_coze_api_base()
+    client_id = os.getenv("COZE_CLIENT_ID")
+    if not client_id:
+        raise ValueError("COZE_CLIENT_ID environment variable is required")
 
-    device_oauth_app = DeviceOAuthApp(client_id="57294420732781205987760324720643.app.coze", base_url=coze_api_base)
-    device_code = device_oauth_app.get_device_code(workspace_id)
-    print(f"Please Open: {device_code.verification_url} to get the access token")
-    return device_oauth_app.get_access_token(device_code=device_code.device_code, poll=True).access_token
+    try:
+        device_oauth_app = DeviceOAuthApp(client_id=client_id, base_url=coze_api_base)
+        device_code = device_oauth_app.get_device_code(workspace_id)
+        print(f"Please Open: {device_code.verification_url} to get the access token")
+        return device_oauth_app.get_access_token(device_code=device_code.device_code, poll=True).access_token
+    except Exception as e:
+        raise RuntimeError(f"Failed to obtain access token: {str(e)}")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def get_coze_api_token(workspace_id: Optional[str] = None) -> str:
# Get an access_token through personal access token or oauth.
coze_api_token = os.getenv("COZE_API_TOKEN")
if coze_api_token:
return coze_api_token
coze_api_base = get_coze_api_base()
device_oauth_app = DeviceOAuthApp(client_id="57294420732781205987760324720643.app.coze", base_url=coze_api_base)
device_code = device_oauth_app.get_device_code(workspace_id)
print(f"Please Open: {device_code.verification_url} to get the access token")
return device_oauth_app.get_access_token(device_code=device_code.device_code, poll=True).access_token
def get_coze_api_token(workspace_id: Optional[str] = None) -> str:
# Get an access_token through personal access token or oauth.
coze_api_token = os.getenv("COZE_API_TOKEN")
if coze_api_token:
return coze_api_token
coze_api_base = get_coze_api_base()
client_id = os.getenv("COZE_CLIENT_ID")
if not client_id:
raise ValueError("COZE_CLIENT_ID environment variable is required")
try:
device_oauth_app = DeviceOAuthApp(client_id=client_id, base_url=coze_api_base)
device_code = device_oauth_app.get_device_code(workspace_id)
print(f"Please Open: {device_code.verification_url} to get the access token")
return device_oauth_app.get_access_token(device_code=device_code.device_code, poll=True).access_token
except Exception as e:
raise RuntimeError(f"Failed to obtain access token: {str(e)}")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant