Skip to content

Conversation

@avirajsingh7
Copy link
Collaborator

@avirajsingh7 avirajsingh7 commented Aug 20, 2025

Summary

Target issue: #339
This PR updates the assistant table and related logic to support externally provided assistant_id values instead of always generating them internally.

Glific requires the ability to assign assistant_id values based on IDs returned from OpenAI for backward compatibility. This change ensures their workflow is supported without breaking existing logic.

Also ,enforced uniqueness of assistant_id within a project using a composite unique constraint (project_id, assistant_id).

Checklist

Before submitting a pull request, please ensure that you mark these task.

  • Ran fastapi run --reload app/main.py or docker compose up in the repository root and test.
  • If you've fixed a bug or added code that is tested and has test cases.

Notes

Please add here if any other information is required for the reviewer.

Summary by CodeRabbit

  • New Features
    • You can now optionally provide a custom assistant ID when creating an assistant; if omitted, one is auto-generated.
    • Assistant IDs are now enforced as unique per project, allowing the same ID to be reused across different projects.
    • Clear 409 Conflict error is returned when attempting to create an assistant with a duplicate ID within the same project, improving feedback for conflicting IDs.

@coderabbitai
Copy link

coderabbitai bot commented Aug 20, 2025

Walkthrough

Adds a migration to enforce composite uniqueness (project_id, assistant_id), updates models to match, modifies assistant creation to generate/check assistant_id and handle duplicates with 409, and introduces tests covering successful explicit IDs and duplicate ID conflicts.

Changes

Cohort / File(s) Summary
Database Migration: Composite Uniqueness
backend/app/alembic/versions/38f0e8c8dc92_alter_unique_constraint_assistant_table.py
Drops unique index on assistant_id, adds non-unique index, and creates unique constraint on (project_id, assistant_id); downgrade reverses.
Model Schema Updates
backend/app/models/assistants.py
Moves uniqueness to table-level UniqueConstraint(project_id, assistant_id); assistant_id column no longer unique; AssistantCreate now accepts optional assistant_id with length constraints.
CRUD Logic: ID generation and conflict handling
backend/app/crud/assistants.py
Ensures assistant_id exists (generate UUID if missing), pre-checks existence per project, raises HTTP 409 on duplicate; persists via model_dump(exclude_unset=True).
Tests for new behaviors
backend/app/tests/crud/test_assistants.py
Adds tests for creating with explicit assistant_id and for duplicate assistant_id conflict (expects 409).

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Client
  participant API as API (create_assistant)
  participant CRUD as CRUD Layer
  participant DB as Database

  Client->>API: POST /assistants (project_id, payload)
  API->>CRUD: create_assistant(project_id, data)
  Note right of CRUD: Ensure assistant_id: provided or UUID
  CRUD->>DB: SELECT assistant WHERE project_id & assistant_id
  alt Exists (duplicate)
    DB-->>CRUD: Found
    CRUD-->>API: Raise HTTP 409 Conflict
    API-->>Client: 409 Duplicate assistant_id in project
  else Not found
    DB-->>CRUD: None
    CRUD->>DB: INSERT assistant (project_id, assistant_id, ...)
    DB-->>CRUD: Row inserted
    CRUD-->>API: Assistant object
    API-->>Client: 201 Created (assistant)
  end
  Note over DB: Enforced by unique constraint (project_id, assistant_id)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

I hop through fields of schema change,
New keys in pairs—how neatly arranged!
If twins collide, I thump: 409!
Fresh IDs sprout like clover fine.
Migrations burrow, tests take flight—
Another garden set just right. 🐇✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/assistant_id_in_create

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

@codecov
Copy link

codecov bot commented Aug 20, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

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 (4)
backend/app/models/assistants.py (2)

4-6: Import UniqueConstraint from SQLAlchemy for better compatibility

Depending on your SQLModel version, sqlmodel.UniqueConstraint may not be exported. Importing it from SQLAlchemy is safer and consistent with the other SQLAlchemy imports in this module.

Apply this diff:

-from sqlalchemy import Column, String, Text
+from sqlalchemy import Column, String, Text, UniqueConstraint
-from sqlmodel import Field, Relationship, SQLModel, UniqueConstraint
+from sqlmodel import Field, Relationship, SQLModel

52-57: Normalize/validate client-provided assistant_id to avoid near-duplicates

Accepting an external assistant_id is great. To prevent subtle duplicates (e.g., trailing spaces), add a validator to trim whitespace and reject empty strings post-trim. Optionally, constrain the charset if you want to disallow spaces or special chars.

Example (outside the selected lines), using Pydantic v2 field validator:

from pydantic import field_validator

class AssistantCreate(SQLModel):
    ...
    @field_validator("assistant_id")
    @classmethod
    def normalize_assistant_id(cls, v: str | None):
        if v is None:
            return v
        v = v.strip()
        if not v:
            raise ValueError("assistant_id cannot be empty or whitespace")
        # Optional: enforce a conservative charset
        # if not re.fullmatch(r"[A-Za-z0-9_\-.:/]+", v):
        #     raise ValueError("assistant_id contains invalid characters")
        return v
backend/app/alembic/versions/38f0e8c8dc92_alter_unique_constraint_assistant_table.py (1)

9-11: Remove unused imports flagged by Ruff

sqlalchemy as sa and sqlmodel.sql.sqltypes are not used in this migration.

Apply this diff:

-from alembic import op
-import sqlalchemy as sa
-import sqlmodel.sql.sqltypes
+from alembic import op
backend/app/tests/crud/test_assistants.py (1)

189-227: LGTM: duplicate assistant_id conflict is enforced with 409

Great coverage of the duplicate path and the exact error shape. Consider adding a complementary test that demonstrates the same assistant_id can be reused across different projects (composite uniqueness semantics), to prevent regressions.

If helpful, I can draft a new test that:

  • Creates Project A and Project B,
  • Creates assistant with assistant_id="same_id" in A,
  • Creates assistant with assistant_id="same_id" in B,
  • Asserts both succeed (no 409).
    Do you want me to scaffold that test given your project factory/setup?
📜 Review details

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

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 1b4de7d and 4fb3bac.

📒 Files selected for processing (4)
  • backend/app/alembic/versions/38f0e8c8dc92_alter_unique_constraint_assistant_table.py (1 hunks)
  • backend/app/crud/assistants.py (1 hunks)
  • backend/app/models/assistants.py (2 hunks)
  • backend/app/tests/crud/test_assistants.py (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (4)
backend/app/tests/crud/test_assistants.py (4)
backend/app/tests/conftest.py (1)
  • db (18-35)
backend/app/tests/utils/utils.py (1)
  • get_project (70-89)
backend/app/models/assistants.py (1)
  • AssistantCreate (47-76)
backend/app/crud/assistants.py (1)
  • create_assistant (167-199)
backend/app/models/assistants.py (4)
backend/app/tests/api/routes/test_assistants.py (1)
  • assistant_id (25-26)
backend/app/alembic/versions/4aa1f48c6321_add_inconistency_fixes.py (1)
  • upgrade (20-49)
backend/app/alembic/versions/8eefcfedc409_create_assistant_table.py (1)
  • upgrade (20-40)
backend/app/seed_data/seed_data.py (1)
  • AssistantData (56-65)
backend/app/alembic/versions/38f0e8c8dc92_alter_unique_constraint_assistant_table.py (2)
backend/app/alembic/versions/4aa1f48c6321_add_inconistency_fixes.py (1)
  • upgrade (20-49)
backend/app/alembic/versions/8eefcfedc409_create_assistant_table.py (1)
  • upgrade (20-40)
backend/app/crud/assistants.py (3)
backend/app/utils.py (1)
  • mask_string (158-167)
backend/app/seed_data/seed_data.py (1)
  • create_assistant (236-276)
backend/app/api/routes/assistants.py (1)
  • create_assistant_route (52-70)
🪛 Ruff (0.12.2)
backend/app/alembic/versions/38f0e8c8dc92_alter_unique_constraint_assistant_table.py

9-9: sqlalchemy imported but unused

Remove unused import: sqlalchemy

(F401)


10-10: sqlmodel.sql.sqltypes imported but unused

Remove unused import: sqlmodel.sql.sqltypes

(F401)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: checks (3.11.7, 6)
🔇 Additional comments (2)
backend/app/models/assistants.py (1)

12-16: Composite uniqueness per project looks correct

Moving uniqueness to a composite constraint on (project_id, assistant_id) aligns with the PR goal and preserves per-project uniqueness. The column-level unique flag removal on assistant_id is consistent with the migration.

backend/app/tests/crud/test_assistants.py (1)

160-187: LGTM: covers explicit assistant_id creation path

This test verifies the new explicit-ID path end-to-end, including persistence of the provided ID. Looks good.

@avirajsingh7 avirajsingh7 merged commit c4e50af into main Aug 21, 2025
3 checks passed
@avirajsingh7 avirajsingh7 deleted the feature/assistant_id_in_create branch August 21, 2025 08:34
kartpop pushed a commit that referenced this pull request Sep 4, 2025
* take assistant id as input in create assistant api
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request ready-for-review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature: Support Custom assistant_id in Create Assistant Endpoint

5 participants