Skip to content

Test and Update Agents Module #122

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

Draft
wants to merge 114 commits into
base: develop
Choose a base branch
from

Conversation

codegen-sh[bot]
Copy link

@codegen-sh codegen-sh bot commented May 17, 2025

Overview

This PR implements comprehensive tests and documentation updates for the Agents module in the Codegen SDK, addressing the requirements in issue ZAM-409.

Changes

Added Tests

  • Created unit tests for all components of the Agents module:
    • test_agent.py: Enhanced existing tests for the Agent class
    • test_chat_agent.py: New tests for the ChatAgent class
    • test_code_agent.py: New tests for the CodeAgent class
    • test_data.py: New tests for the message data classes
    • test_loggers.py: New tests for the ExternalLogger protocol
    • test_tracer.py: New tests for the MessageStreamTracer class
    • test_utils.py: New tests for the AgentConfig TypedDict
    • test_constants.py: New tests for the constants
    • test_agents_module.py: Integration tests for the module as a whole
    • test_agent.py (langchain extension): Tests for the langchain agent extension

Documentation Updates

  • Enhanced module-level documentation in __init__.py with usage examples
  • Updated README.md with comprehensive documentation:
    • Added detailed usage examples for all agent types
    • Added API reference for all classes and methods
    • Added examples for message tracing and logging
    • Added information about environment variables and error handling

Code Improvements

  • Fixed type hints and docstrings throughout the codebase
  • Improved error handling in the Agent class
  • Enhanced the module exports to include ChatAgent and CodeAgent

Testing

All tests pass successfully, providing good coverage of the Agents module functionality.

Related Issues

Closes ZAM-409


💻 View my workAbout Codegen

Summary by Sourcery

Implement comprehensive test coverage for the Agents module, enhance documentation with detailed usage and API references, fix type hints and error handling, and expose new agent classes in the main module exports.

New Features:

  • Expose ChatAgent and CodeAgent via module exports

Bug Fixes:

  • Correct Agent.refresh integer conversion and default org_id fallback
  • Improve error handling in the Agent class

Enhancements:

  • Add type hints and docstring improvements across the codebase

Build:

  • Add Yarn packageManager entry in package.json

Documentation:

  • Update README and module documentation with usage examples, API reference, environment variable info, tracing, and logging guidelines

Tests:

  • Introduce comprehensive unit and integration tests for Agent, ChatAgent, CodeAgent, data classes, tracer, loggers, utils, constants, and langchain extension

clee-codegen and others added 30 commits February 26, 2025 23:54
# Motivation

The **Codegen on OSS** package provides a pipeline that:

- **Collects repository URLs** from different sources (e.g., CSV files
or GitHub searches).
- **Parses repositories** using the codegen tool.
- **Profiles performance** and logs metrics for each parsing run.
- **Logs errors** to help pinpoint parsing failures or performance
bottlenecks.

<!-- Why is this change necessary? -->

# Content

<!-- Please include a summary of the change -->
see
[codegen-on-oss/README.md](https://github.com/codegen-sh/codegen-sdk/blob/acfe3dc07b65670af33b977fa1e7bc8627fd714e/codegen-on-oss/README.md)

# Testing

<!-- How was the change tested? -->
`uv run modal run modal_run.py`
No unit tests yet 😿 

# Please check the following before marking your PR as ready for review

- [ ] I have added tests for my changes
- [x] I have updated the documentation or added new documentation as
needed
Original commit by Tawsif Kamal: Revert "Revert "Adding Schema for Tool Outputs"" (codegen-sh#894)

Reverts codegen-sh#892

---------

Co-authored-by: Rushil Patel <rpatel@codegen.com>
Co-authored-by: rushilpatel0 <171610820+rushilpatel0@users.noreply.github.com>
Original commit by Ellen Agarwal: fix: Workaround for relace not adding newlines (codegen-sh#907)
Copy link

sourcery-ai bot commented May 17, 2025

Reviewer's Guide

This PR introduces a full suite of unit and integration tests for every component of the Agents module (including langchain extensions), enriches module and README documentation with comprehensive usage examples and API references, and updates release configuration metadata.

Sequence Diagram for Basic Agent Interaction (Agent.run)

sequenceDiagram
    actor User
    participant A as Agent
    participant API as CodegenAPI
    participant AT as AgentTask

    User->>A: __init__(token="your_api_token", org_id=123)
    User->>A: run(prompt="Which github repos can you currently access?")
    A->>API: POST /agent_run (payload: prompt)
    API-->>A: JobDetails { id: "job_xyz", status: "queued" }
    A->>AT: __init__(id="job_xyz", status="queued", agent_ref=A)
    A-->>User: agent_task (AgentTask instance)
    User->>AT: refresh()
    AT->>API: GET /job_status (id="job_xyz")
    API-->>AT: JobDetails { id: "job_xyz", status: "completed", result: "Accessible repos..." }
    note right of AT: Updates internal status and result
    User->>AT: result (accesses updated result)
Loading

Sequence Diagram for CodeAgent Interaction (CodeAgent.run)

sequenceDiagram
    actor User
    participant CoA as CodeAgent
    participant CB as Codebase
    participant ACfg as AgentConfig
    participant LLMS as LLMService

    User->>ACfg: __init__(keep_first_messages=2, ...)
    User->>CoA: __init__(codebase=CB, agent_config=ACfg, ...)
    User->>CoA: run(prompt="Create a function to parse JSON", image_urls=["img1.png"])
    CoA->>LLMS: Generate code (prompt, images, config)
    note right of CoA: May use tools, manage state, apply config
    LLMS-->>CoA: Generated code result
    CoA-->>User: "def parse_json(...): ..."

    User->>CoA: get_agent_trace_url()
    CoA-->>User: "https://langsmith.com/.../trace_id"
Loading

Sequence Diagram for Message Tracing with MessageStreamTracer

sequenceDiagram
    actor Developer
    participant MessageSource as Agent/Component
    participant Stream as Message Stream
    participant Tracer as MessageStreamTracer
    participant Logger as CustomLogger

    Developer->>Logger: new CustomLogger()
    Developer->>Tracer: new MessageStreamTracer(logger=Logger)

    Developer->>MessageSource: operation_yielding_messages()
    MessageSource-->>Stream: yield UserMessage("Hello")
    MessageSource-->>Stream: yield AIMessage("Response part 1")

    loop For each message in stream
        Developer->>Tracer: process_stream(Stream)
        Tracer->>Stream: next()
        Stream-->>Tracer: message_chunk (e.g., UserMessage)
        Tracer->>Logger: log(message_chunk)
        Tracer-->>Developer: processed_message_chunk
    end

    Developer->>Tracer: get_traces()
    Tracer-->>Developer: [trace_data_1, trace_data_2]
Loading

Class Diagram for Agent Hierarchy and Core Components

classDiagram
    class Agent {
        +token: str
        +org_id: int
        +base_url: str
        +run(prompt: str) AgentTask
        +get_status() dict
    }
    class AgentTask {
        +id: str
        +org_id: int
        +status: str
        +result: any
        +refresh() None
    }
    class ChatAgent {
        +codebase: Codebase
        +model_provider: str
        +model_name: str
        +memory: bool
        +run(prompt: str, thread_id: str) str
        +chat(prompt: str, thread_id: str) tuple[str, str]
        +get_chat_history(thread_id: str) list
    }
    class CodeAgent {
        +codebase: Codebase
        +model_provider: str
        +model_name: str
        +memory: bool
        +agent_config: AgentConfig
        +logger: ExternalLogger
        +run(prompt: str, image_urls: list[str]) str
        +get_agent_trace_url() str
        +get_tools() list[BaseTool]
        +get_state() dict
    }
    class Codebase {
        <<Dependency>>
        # Path or other initialization params
    }
    class AgentConfig {
        <<Configuration>>
        # Attributes like keep_first_messages, max_messages
    }
    class ExternalLogger {
        <<Interface>>
        # Methods like log()
    }
    class BaseTool {
        <<Dependency>>
        # Name or other attributes
    }

    Agent "1" -- "1" AgentTask : creates/manages
    ChatAgent ..> Codebase : uses
    CodeAgent ..> Codebase : uses
    CodeAgent ..> AgentConfig : uses (optional)
    CodeAgent ..> ExternalLogger : uses (optional)
    CodeAgent ..> BaseTool : uses (optional)
Loading

Class Diagram for Agent Configuration (AgentConfig)

classDiagram
    class AgentConfig {
        <<TypedDict>>
        +keep_first_messages: int
        +max_messages: int
    }
    note for AgentConfig "Configuration for CodeAgent behavior, such as message summarization rules."
Loading

Class Diagram for Message Tracing and Logging Utilities

classDiagram
    class MessageStreamTracer {
        +logger: ExternalLogger
        +process_stream(message_stream: Iterable) Iterable
        +get_traces() list
    }
    class ExternalLogger {
        <<Interface>>
        +log(data: Any) None
    }
    class CustomLogger {
        +logs: list
        +log(data: Any) None
    }
    class UserMessage {
        +content: str
        # Potentially other attributes like 'type'
    }
    class AIMessage {
        # Similar to UserMessage, represents AI response part
        +content: str
    }
    MessageStreamTracer o-- "1" ExternalLogger : uses
    CustomLogger ..|> ExternalLogger : implements
    MessageStreamTracer ..> UserMessage : processes
    MessageStreamTracer ..> AIMessage : processes
Loading

File-Level Changes

Change Details Files
Comprehensive tests added across the Agents module
  • New unit tests for Agent, ChatAgent, CodeAgent, utils, constants, loggers, tracer, and data classes
  • Integration tests for the Agents module end-to-end workflows
  • Tests for the langchain extension supporting custom tools and configurations
tests/unit/codegen/extensions/langchain/test_agent.py
tests/unit/codegen/agents/test_agent.py
tests/unit/codegen/agents/test_simple_agent.py
tests/unit/codegen/agents/test_code_agent.py
tests/unit/codegen/agents/test_tracer.py
tests/unit/codegen/agents/test_data.py
tests/unit/codegen/agents/test_chat_agent.py
tests/unit/codegen/agents/test_agents_module.py
tests/unit/codegen/agents/test_loggers.py
tests/unit/codegen/agents/test_utils.py
tests/unit/codegen/agents/test_constants.py
Documentation and module exports enhanced
  • Expanded module-level docstrings with usage examples in init.py
  • Updated README.md with detailed agent types, usage patterns, API reference, environment variables, and error handling
  • Exposed ChatAgent and CodeAgent in module exports
src/codegen/agents/__init__.py
src/codegen/agents/README.md
Release configuration updated
  • Reformatted semantic-release branches array
  • Added packageManager field for Yarn metadata
package.json

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

korbit-ai bot commented May 17, 2025

By default, I don't review pull requests opened by bots. If you would like me to review this pull request anyway, you can request a review via the /korbit-review command in a comment.

Copy link

coderabbitai bot commented May 17, 2025

Important

Review skipped

Bot user detected.

To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Join our Discord community for assistance with any issues or questions.

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 sequence diagram to generate a sequence diagram of the changes in this PR.
  • @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
Author

codegen-sh bot commented May 17, 2025

I see a check failed - I'm on it! 🫡

💻 View my work

Copy link
Author

codegen-sh bot commented May 17, 2025

✅ Fixed the failing mypy checks in this commit.

The issues were related to type annotations in the agents module:

  1. In agent.py:

    • Added proper Optional type annotations for parameters
    • Fixed type annotation for self.current_job
    • Updated return type hints to use Optional instead of union types
  2. In code_agent.py:

    • Added comprehensive type imports (Any, Dict, Generator, etc.)
    • Fixed initialization of optional parameters (tags and metadata)
    • Fixed content type handling in the run() method
    • Simplified the get_state() method to avoid StateSnapshot type issues
    • Fixed string conversion for difficulty in metadata

All mypy checks should now pass successfully.

💻 View my work • React 👍 or 👎

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

Successfully merging this pull request may close these issues.

2 participants