8000 feat: add support for propsSchema by michaelmagan · Pull Request #174 · tambo-ai/tambo · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

feat: add support for propsSchema #174

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

Merged
merged 3 commits into from
Mar 22, 2025
Merged

feat: add support for propsSchema #174

merged 3 commits into from
Mar 22, 2025

Conversation

michaelmagan
Copy link
Collaborator
@michaelmagan michaelmagan commented Mar 22, 2025

Summary by CodeRabbit

  • Documentation

    • Updated guidance with new examples and streamlined content focused on component registration and type-safe property definitions.
  • New Features

    • Introduced a new configuration file for code formatting options.
    • Enabled flexible component property definitions using schema-based validation, providing developers with enhanced integration options.
  • Refactor

    • Improved validation logic and error handling during component registration to ensure robust and consistent behavior.

Copy link
coderabbitai bot commented Mar 22, 2025

Walkthrough

The changes introduce a new .prettierrc configuration file for consistent code formatting and update the react-sdk/README.md with new examples for component registration using the Zod library. Additionally, the TamboComponent interface is enhanced with optional properties to support type-safe props, and the TamboRegistryProvider is modified for improved validation, error handling, and JSON Schema conversion. Utility functions in the registry module are refactored and expanded to support these new features.

Changes

File(s) Change Summary
.prettierrc Introduced a configuration file specifying formatting options: printWidth: 80, tabWidth: 2, spaces for tabs, semicolons, double quotes, trailing commas (ES5), bracket spacing, parentheses around sole arrow function parameters, and LF line endings.
react-sdk/README.md Updated documentation with new examples on component registration using Zod schemas and JSON definitions; removed outdated sections on thread management and API references.
react-sdk/src/model/component-metadata.ts Enhanced the TamboComponent interface by adding two optional properties: propsSchema and propsDefinition, with guidance to provide only one.
react-sdk/src/providers/tambo-registry-provider.tsx Updated the TamboRegistryProvider logic, adding validation to ensure either propsSchema or propsDefinition is provided (not both), wrapped JSON Schema conversion (via zodToJsonSchema) in error-handling, and streamlined function formatting.
react-sdk/src/util/registry.ts Added a new helper function convertPropsToJsonSchema to convert a Zod schema to JSON Schema; overall structure slightly altered to accommodate the new function without affecting existing functionality.

Sequence Diagram(s)

sequenceDiagram
    participant C as Component Registration
    participant R as TamboRegistryProvider
    participant H as JSON Schema Converter

    C->>R: Call registerComponent with component options
    alt propsSchema provided
        R->>H: Convert propsSchema to JSON Schema
        H-->>R: Return JSON Schema (or error if conversion fails)
    else propsDefinition provided
        R->>R: Use provided propsDefinition directly
    end
    R-->>C: Register component (or throw error)
Loading

Poem

Hop and skip in lines of code,
A format file lightens the load.
Schemas dance in JSON's glow,
Errors caught before they grow.
As a rabbit, I celebrate these feats—
Coding carrots make all things sweet!
🥕🐇

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
  • @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.

@github-actions github-actions bot added the feat label Mar 22, 2025
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: 0

🧹 Nitpick comments (3)
react-sdk/src/model/component-metadata.ts (1)

72-79: Good enhancement of the TamboComponent interface with prop schema support

Adding support for Zod schemas is a great improvement for type safety. The clear documentation about using either propsSchema OR propsDefinition (but not both) helps prevent misuse.

However, the propsDefinition type is still any, which reduces type safety. Consider defining a more specific type.

-  propsDefinition?: any;
+  propsDefinition?: Record<string, string | object>;
react-sdk/src/providers/tambo-registry-provider.tsx (1)

92-114: Robust validation for props schema and definition

The validation logic ensures that:

  1. Either propsSchema or propsDefinition must be provided
  2. Both cannot be provided simultaneously
  3. Error messages clearly explain the requirements

The try-catch block for schema conversion is good practice, but consider adding a more specific type annotation for the props variable to avoid implicit any.

-      let props = propsDefinition;
+      let props: Record<string, any> = propsDefinition;
react-sdk/src/util/registry.ts (1)

49-53: Consider adding a more robust type check for Zod schemas

The current check for Zod schema uses presence of _def and parse function, which might not be foolproof as these properties could exist on non-Zod objects.

A more robust check could be:

- // Check if props is a Zod schema (we can't directly check the type, so we check for _def)
- if (component.props._def && typeof component.props.parse === 'function') {
+ // Check if props is a Zod schema
+ if (component.props?._def && typeof component.props.parse === 'function' && 
+     typeof component.props.safeParse === 'function') {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 33759ae and 6b5c32f.

📒 Files selected for processing (5)
  • .prettierrc (1 hunks)
  • react-sdk/README.md (4 hunks)
  • react-sdk/src/model/component-metadata.ts (3 hunks)
  • react-sdk/src/providers/tambo-registry-provider.tsx (5 hunks)
  • react-sdk/src/util/registry.ts (5 hunks)
🧰 Additional context used
🧬 Code Definitions (2)
react-sdk/src/providers/tambo-registry-provider.tsx (2)
react-sdk/src/providers/index.ts (3) (3)
  • TamboRegistryProvider (9-9)
  • TamboTool (1-1)
  • TamboRegistryContext (11-11)
react-sdk/src/model/component-metadata.ts (2) (2)
  • ComponentRegistry (28-28)
  • TamboTool (32-40)
react-sdk/src/util/registry.ts (1)
react-sdk/src/model/component-metadata.ts (7) (7)
  • ComponentRegistry (28-28)
  • TamboToolRegistry (30-30)
  • TamboToolAssociations (42-42)
  • RegisteredComponent (23-26)
  • TamboTool (32-40)
  • ComponentContextToolMetadata (14-16)
  • ParameterSpec (6-8)
🔇 Additional comments (21)
.prettierrc (1)

1-11: Excellent standardization of code formatting with Prettier

Adding a Prettier configuration helps maintain consistent code style across the project. The chosen settings align well with modern JavaScript/TypeScript style guidelines:

  • 100 character line length is a good balance between readability and screen space
  • Using single quotes matches the formatting changes in the other files
  • The arrowParens setting creates cleaner arrow functions
  • LF line endings ensure consistency across platforms
react-sdk/src/model/component-metadata.ts (1)

1-4: Import formatting improvements look good

The import statements have been updated to use single quotes, which matches the new Prettier configuration.

react-sdk/src/providers/tambo-registry-provider.tsx (5)

9-11: Import cleanup and new zodToJsonSchema import

Adding the import for zodToJsonSchema is necessary for the new schema conversion functionality.


38-41: Improved function definition formatting

The reformatting of the TamboRegistryProvider function definition makes the code more readable.


48-58: Cleaner callback implementation

The registerTool function has been reformatted for better readability while maintaining the same functionality.


116-131: Props assignment in component registration

The component registration logic now correctly uses the converted props from either the schema or definition.


160-160: Simplified JSX return statement

The return statement has been simplified to a single line, which is more readable.

react-sdk/README.md (6)

39-39: Updated import statement to use single quotes

The import statement now uses single quotes, consistent with the new Prettier configuration.


49-49: Updated MessageThread import to use single quotes

The MessageThread import now uses single quotes, consistent with the Prettier configuration.


77-93: Great example of component registration with Zod schemas

The example clearly demonstrates how to use Zod for type-safe props definition in component registration. This aligns well with the new propsSchema property added to the TamboComponent interface.


95-111: Helpful example of using z.describe() for additional context

This example shows how to provide additional context to the AI using z.describe(), which is a powerful feature for guiding AI-generated components.


113-115: Clear explanation of mutually exclusive prop definition options

The comment clearly explains that developers should use either propsSchema OR propsDefinition, not both, which aligns with the validation in the provider.


117-126: Updated JSON object example with improved formatting

The example for using JSON object for props definition has been updated with improved formatting and clearer types.

react-sdk/src/util/registry.ts (8)

1-3: Consistent import formatting with single quotes

The imports have been updated to use single quotes instead of double quotes, which improves consistency with the codebase style.


25-25: Improved arrow function syntax

The arrow function has been simplified by removing unnecessary parentheses around the single parameter, which follows modern JavaScript best practices.


43-56: Well-implemented helper function for props schema conversion

The new convertPropsToJsonSchema function properly handles the conversion of component props from Zod schema to JSON Schema. The implementation includes appropriate null checks and type verification before performing the conversion.

I particularly like the robust type safety approach with the comment explaining the two-step type assertion. This is careful implementation.


65-65: Improved error message formatting

The error message has been streamlined by removing unnecessary line breaks, making it more concise while maintaining clarity.


73-74: Enhanced string formatting for default context

The string formatting has been improved using template literals, which is more readable and maintainable than string concatenation.


82-82: Added return type for better type safety

Adding explicit return type annotation to the mapTamboToolToContextTool function improves type safety and code readability.


92-92: Added return type for better type safety

The explicit return type annotation on getParametersFromZodFunction improves type safety and documentation.


114-131: Well-structured type mapping for Zod types

The switch statement is well-organized with consistent formatting, mapping Zod types to their corresponding simple type names. The fallback case properly logs a warning when encountering unknown types.

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

🧹 Nitpick comments (4)
react-sdk/src/providers/tambo-registry-provider.tsx (1)

114-126: The try-catch for schema conversion is prudent.
You might consider how to handle the exception for a failing schema conversion more explicitly (e.g., rethrowing or reverting to a known-safe fallback) in case the Zod schema is malformed. Otherwise, this block effectively guards against unexpected runtime errors.

react-sdk/README.md (3)

77-93: Enhanced Component Registration with Zod

This new example clearly demonstrates how to use Zod to provide a type-safe propsSchema during component registration. The snippet is well structured and directly aligns with the PR objective to support propsSchema. Ensure that the actual implementation of registerComponent supports and properly validates this new parameter.


97-111: Clarify Schema Declaration in the Examples

The schema definition using z.describe() is useful for adding prompting details. For clarity and to help users directly copy-paste the code, consider using an explicit declaration keyword (e.g., const) before schema. For example:

- schema = z.object({
+ const schema = z.object({

This small refinement improves clarity, especially for newcomers.


116-126: Clear Alternative Example Using JSON Definition

The alternative example using propsDefinition is clear and provides a good fallback for users who prefer JSON-style definitions over Zod schemas. The accompanying note—"Use either propsSchema OR propsDefinition, not both"—is an important clarification. Ensure this guidance is sufficiently emphasized in the surrounding text so that users do not inadvertently mix the two approaches.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6b5c32f and 28c79d8.

📒 Files selected for processing (5)
  • .prettierrc (1 hunks)
  • react-sdk/README.md (1 hunks)
  • react-sdk/src/model/component-metadata.ts (1 hunks)
  • react-sdk/src/providers/tambo-registry-provider.tsx (3 hunks)
  • react-sdk/src/util/registry.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • react-sdk/src/model/component-metadata.ts
🧰 Additional context used
🧬 Code Definitions (1)
react-sdk/src/util/registry.ts (2)
react-sdk/src/model/component-metadata.ts (1) (1)
  • RegisteredComponent (24-27)
react-sdk/src/index.ts (1) (1)
  • RegisteredComponent (32-32)
🔇 Additional comments (7)
.prettierrc (1)

1-11: Looks good.
These configuration settings provide a clear and consistent formatting style.

react-sdk/src/util/registry.ts (1)

43-58: Consider a more robust check for Zod schemas.
Currently, checking component.props._def and parse is sufficient for most cases; however, because _def is internal, future changes to Zod may break it. Consider using a more direct Zod type-guard (e.g., instanceof z.ZodType) if supported. Otherwise, this is a straightforward and effective approach for converting component props to JSON Schema.

react-sdk/src/providers/tambo-registry-provider.tsx (5)

10-10: New import correctly references zod-to-json-schema.
This import is essential for converting Zod schemas into JSON Schema.


94-95: Destructuring propsSchema and propsDefinition adds clarity.
Having both fields in the parameter list is clearer for integration 953A with the new schema validation logic.


100-105: Ensuring at least one props definition prevents incomplete registrations.
Throwing an error here is a good safeguard that helps avoid unregistered or invalid props scenarios.


107-112: Rejecting multiple props definitions is consistent with a single-source-of-truth approach.
This constraint prevents conflicts arising from two different schema definitions.


138-138: Storing props ensures consistent usage in the component registry.
By assigning either the converted schema or the definition, you unify the final props reference under one field.

@michaelmagan michaelmagan merged commit da0e049 into main Mar 22, 2025
6 checks passed
@michaelmagan michaelmagan deleted the magan/props-schema branch March 22, 2025 20:07
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
0