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: Enhance OAuth configuration and improve example scripts #162

Merged
merged 1 commit into from
Jan 15, 2025

Conversation

chyroc
Copy link
Collaborator

@chyroc chyroc commented Jan 14, 2025

Summary by CodeRabbit

  • New Features

    • Added load_oauth_app_from_config function to simplify OAuth app configuration.
    • Enhanced API base URL and token retrieval mechanisms across example scripts.
    • Improved logging configuration for example scripts.
  • Refactor

    • Removed examples/utils/__init__.py and integrated its functions directly into example scripts.
  • Documentation

    • Improved environment variable handling for API configuration.

@chyroc chyroc added the chore Project maintenance work not related to features and bug fixes label Jan 14, 2025
Copy link

coderabbitai bot commented Jan 14, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

This pull request introduces a new function load_oauth_app_from_config in the authentication module, which provides a flexible way to create OAuth application instances based on configuration. The changes span multiple files, including the module's initialization, authentication module, and several example scripts. The modifications primarily focus on improving API base URL and token retrieval mechanisms, adding logging capabilities, and enhancing the overall flexibility of OAuth application creation.

Changes

File Change Summary
cozepy/__init__.py Added load_oauth_app_from_config to __all__ list
cozepy/auth/__init__.py Added load_oauth_app_from_config function to create OAuth apps dynamically
examples/utils/__init__.py Removed utility functions for API base and token retrieval
examples/chat_stream.py Added get_coze_api_base(), get_coze_api_token(), and setup_examples_logger() functions
examples/websockets_audio_speech.py Added get_coze_api_base(), get_coze_api_token(), and setup_examples_logger() functions
examples/websockets_audio_transcriptions.py Added get_coze_api_base(), get_coze_api_token(), and setup_examples_logger() functions
examples/websockets_chat.py Added get_coze_api_base(), get_coze_api_token(), and setup_examples_logger() functions
examples/websockets_chat_realtime_gui.py Added setup_examples_logger() function and adjusted imports

Possibly related PRs

Poem

🐰 OAuth's dance, a rabbit's delight,
Config in paw, tokens take flight!
From PKCE to JWT's embrace,
A dynamic app with coding grace.
Hop, hop, configuration's might! 🔐


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a430938 and d37c7f3.

📒 Files selected for processing (8)
  • cozepy/__init__.py (2 hunks)
  • cozepy/auth/__init__.py (2 hunks)
  • examples/chat_stream.py (1 hunks)
  • examples/utils/__init__.py (0 hunks)
  • examples/websockets_audio_speech.py (1 hunks)
  • examples/websockets_audio_transcriptions.py (1 hunks)
  • examples/websockets_chat.py (2 hunks)
  • examples/websockets_chat_realtime_gui.py (3 hunks)

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 14, 2025

Codecov Report

Attention: Patch coverage is 15.00000% with 17 lines in your changes missing coverage. Please review.

Project coverage is 89.87%. Comparing base (8ce09e4) to head (d37c7f3).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
cozepy/auth/__init__.py 15.00% 17 Missing ⚠️
@@            Coverage Diff             @@
##             main     #162      +/-   ##
==========================================
- Coverage   90.13%   89.87%   -0.27%     
==========================================
  Files          63       63              
  Lines        5748     5767      +19     
==========================================
+ Hits         5181     5183       +2     
- Misses        567      584      +17     
Files with missing lines Coverage Δ
cozepy/__init__.py 100.00% <ø> (ø)
cozepy/auth/__init__.py 87.78% <15.00%> (-5.03%) ⬇️

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: 1

🔭 Outside diff range comments (1)
examples/chat_stream.py (1)

Line range hint 12-57: Move utility functions to a shared module to avoid duplication.

These utility functions (get_coze_api_base(), get_coze_api_token(), and setup_examples_logger()) are duplicated across all example files. Consider moving them to a shared module (e.g., examples/utils.py) to:

  • Eliminate code duplication
  • Centralize configuration management
  • Make maintenance easier
  • Ensure consistent behavior across examples

Here's a suggested approach:

  1. Create a shared utilities module:
# examples/utils.py
import logging
import os
from typing import Optional

from cozepy import COZE_CN_BASE_URL, DeviceOAuthApp, setup_logging

# Move the common client ID to a constant
COZE_CLIENT_ID = "57294420732781205987760324720643.app.coze"

def get_coze_api_base() -> str:
    # ... (existing implementation)

def get_coze_api_token(workspace_id: Optional[str] = None) -> str:
    # ... (existing implementation using COZE_CLIENT_ID)

def setup_examples_logger():
    # ... (existing implementation)
  1. Update the example files to import from utils:
from examples.utils import get_coze_api_base, get_coze_api_token, setup_examples_logger
🧹 Nitpick comments (3)
examples/websockets_audio_transcriptions.py (1)

Line range hint 89-101: Consider moving the helper function to shared utilities.

The wrap_coze_speech_to_iterator helper function could be useful across different examples. Consider moving it to the shared utilities module along with the other common functions.

examples/websockets_chat.py (1)

Line range hint 108-122: Enhance documentation for the fake plugin implementation.

The fake_run_local_plugin function could benefit from better documentation explaining:

  • The purpose of the fake implementation
  • Expected real-world usage
  • Format of the expected outputs

Add docstring to clarify the implementation:

 def fake_run_local_plugin():
+    """
+    Simulates a local plugin execution for demonstration purposes.
+    In a real implementation, this would:
+    1. Execute actual plugin logic
+    2. Process the tool call arguments
+    3. Return properly formatted outputs
+    """
     # this is just fake outputs
     return event.data.required_action.submit_tool_outputs.tool_calls[0].function.arguments
examples/websockets_chat_realtime_gui.py (1)

36-40: Consider enhancing the logging configuration.

The function provides basic logging setup but could be improved:

  1. Add docstring to explain the function's purpose and environment variable usage.
  2. Consider adding a default log level when COZE_LOG is not set.
  3. Add error handling for invalid log level names.

Apply this diff to enhance the logging configuration:

 def setup_examples_logger():
+    """Configure logging based on COZE_LOG environment variable.
+    
+    The log level can be set using COZE_LOG environment variable (e.g., DEBUG, INFO, WARNING, ERROR).
+    If not set or invalid, defaults to INFO level.
+    """
     coze_log = os.getenv("COZE_LOG")
+    default_level = logging.INFO
     if coze_log:
-        setup_logging(logging.getLevelNamesMapping().get(coze_log.upper(), logging.INFO))
+        try:
+            level = logging.getLevelNamesMapping()[coze_log.upper()]
+            setup_logging(level)
+        except KeyError:
+            setup_logging(default_level)
+    else:
+        setup_logging(default_level)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8ce09e4 and a430938.

📒 Files selected for processing (8)
  • cozepy/__init__.py (2 hunks)
  • cozepy/auth/__init__.py (2 hunks)
  • examples/chat_stream.py (1 hunks)
  • examples/utils/__init__.py (0 hunks)
  • examples/websockets_audio_speech.py (1 hunks)
  • examples/websockets_audio_transcriptions.py (1 hunks)
  • examples/websockets_chat.py (2 hunks)
  • examples/websockets_chat_realtime_gui.py (3 hunks)
💤 Files with no reviewable changes (1)
  • examples/utils/init.py
🧰 Additional context used
🪛 GitHub Check: codecov/patch
cozepy/auth/__init__.py

[warning] 664-667: cozepy/auth/init.py#L664-L667
Added lines #L664 - L667 were not covered by tests


[warning] 669-679: cozepy/auth/init.py#L669-L679
Added lines #L669 - L679 were not covered by tests


[warning] 681-681: cozepy/auth/init.py#L681
Added line #L681 was not covered by tests

🔇 Additional comments (4)
examples/chat_stream.py (1)

4-4: Add tests for the chat stream functionality.

The TODO comment indicates missing tests. Consider adding tests to verify:

  • Proper handling of chat events
  • Error scenarios
  • Stream completion

Would you like me to help create a test suite for this functionality?

examples/websockets_audio_speech.py (1)

Line range hint 55-120: Well-structured async implementation!

The WebSocket audio speech implementation demonstrates good practices:

  • Proper async/await usage
  • Comprehensive error handling
  • Clear event handling structure
cozepy/__init__.py (1)

21-21: LGTM!

The changes correctly expose the new load_oauth_app_from_config function in the module's public API.

Also applies to: 163-163

examples/websockets_chat_realtime_gui.py (1)

22-22: LGTM!

The imports are correctly updated to use the main package exports.

Also applies to: 25-25

@chyroc chyroc changed the title refactor: Merge examples into a single file feat: Enhance OAuth configuration and improve example scripts Jan 15, 2025
@chyroc chyroc merged commit 2218a8c into main Jan 15, 2025
10 of 12 checks passed
@chyroc chyroc deleted the update-examples branch January 15, 2025 06:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
chore Project maintenance work not related to features and bug fixes
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant