Skip to content

feat: add onStepFinish callback to text generation functions#18

Open
standujar wants to merge 2 commits into1.xfrom
feat/add-missing-onstepfinish
Open

feat: add onStepFinish callback to text generation functions#18
standujar wants to merge 2 commits into1.xfrom
feat/add-missing-onstepfinish

Conversation

@standujar
Copy link
Copy Markdown

@standujar standujar commented Nov 10, 2025

  • Introduced an optional onStepFinish parameter to generateTextWithModel, handleTextSmall, and handleTextLarge functions.
  • Enhanced the text generation process by allowing users to provide a callback that executes after each step, enabling custom handling of step results.

Summary by CodeRabbit

  • New Features
    • Added an optional per-step callback for text generation so users can run custom code after each generation step (useful for progress updates, monitoring, or reactive behavior).
    • When tools are used, the per-step callback runs after internal step processing; callback errors are caught and logged without interrupting generation.

- Introduced an optional onStepFinish parameter to generateTextWithModel, handleTextSmall, and handleTextLarge functions.
- Enhanced the text generation process by allowing users to provide a callback that executes after each step, enabling custom handling of step results.
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Nov 10, 2025

Walkthrough

Added an optional onStepFinish callback to generateTextWithModel, handleTextSmall, and handleTextLarge. The callback is threaded through signatures and invoked (safely wrapped in try/catch) after each internal generation/tool step with the current stepResult.

Changes

Cohort / File(s) Summary
Callback hook addition
src/models/text.ts
Added optional `onStepFinish?: (stepResult: any) => void

Sequence Diagram

sequenceDiagram
    participant User
    participant generateText as generateTextWithModel
    participant handler as handleTextSmall / handleTextLarge
    participant toolLogic as Tool Handling
    participant callback as onStepFinish

    User->>generateText: Call with params + onStepFinish
    generateText->>handler: Forward params (includes onStepFinish)
    handler->>toolLogic: Run tool/internal step
    toolLogic-->>handler: Return stepResult (captured)
    alt onStepFinish provided
        handler->>callback: Invoke with stepResult
        callback-->>handler: Return (sync or awaited)
    end
    handler-->>generateText: Return final string / ToolResponse
    generateText-->>User: Return result
Loading

Estimated Code Review Effort

🎯 2 (Simple) | ⏱️ ~12 minutes

  • Verify parameter added consistently to all three public/internal signatures and forwarded correctly.
  • Confirm callback invoked after internal tool capture and wrapped in try/catch.
  • Check async handling (await vs. non-await) and that errors from the callback don't break main flow.
  • Ensure TypeScript types and exported signatures are updated accordingly.

Poem

🐇 A nibble of code, a soft little nudge,
Each step now reported as results softly trudge,
I hop in the margin and watch every trace,
Callbacks return promises with style and with grace,
Hooray for the steps — the rabbit applauds the pace!

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: adding an onStepFinish callback parameter to text generation functions, which matches the core modification across all three updated functions.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/add-missing-onstepfinish

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

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@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

🧹 Nitpick comments (4)
src/models/text.ts (4)

21-21: Improve type safety for stepResult parameter.

The stepResult: any type reduces type safety. Consider using a proper type from the AI SDK if available, or defining an interface that describes the expected structure of the step result.

-    onStepFinish?: (stepResult: any) => void | Promise<void>;
+    onStepFinish?: (stepResult: StepResult) => void | Promise<void>;

You may need to import or define StepResult based on the AI SDK's type definitions.


74-103: Document the constraint that callback only works with tools.

The onStepFinish callback is only invoked when tools are provided (due to the if (tools) check on line 74). If a user provides onStepFinish without providing tools, the callback will never execute, which could be confusing. Consider adding validation or documentation to clarify this constraint.

Add a warning if onStepFinish is provided without tools:

+  // Warn if onStepFinish is provided without tools
+  if (onStepFinish && !tools) {
+    logger.warn('[OpenRouter] onStepFinish callback provided but will not be invoked because no tools were specified');
+  }
+
  if (tools) {

142-151: Add JSDoc documentation for the new parameter.

The onStepFinish parameter lacks documentation explaining its purpose, when it's invoked, and the structure of the stepResult parameter. Adding JSDoc would improve developer experience.

 /**
  * TEXT_SMALL model handler
+ * @param runtime - The agent runtime
+ * @param params - Generation parameters
+ * @param params.onStepFinish - Optional callback invoked after each generation step (only when tools are used)
  */
 export async function handleTextSmall(

156-165: Add JSDoc documentation for the new parameter.

Similarly, add documentation for the onStepFinish parameter in handleTextLarge to maintain consistency and improve developer experience.

 /**
  * TEXT_LARGE model handler
+ * @param runtime - The agent runtime
+ * @param params - Generation parameters
+ * @param params.onStepFinish - Optional callback invoked after each generation step (only when tools are used)
  */
 export async function handleTextLarge(
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

Cache: Disabled due to data retention organization setting

Knowledge base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 09af50a and 211c015.

📒 Files selected for processing (1)
  • src/models/text.ts (5 hunks)
🔇 Additional comments (1)
src/models/text.ts (1)

24-24: LGTM!

Destructuring the onStepFinish parameter is correctly implemented.

Comment thread src/models/text.ts
Copy link
Copy Markdown

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/models/text.ts (1)

74-106: Fix: onStepFinish callback is only executed when tools are provided, violating principle of least surprise.

The function accepts onStepFinish as an optional parameter (line 21) but only invokes it when tools are provided (line 74). When tools are absent, the callback is silently ignored despite being passed by the user.

This creates an inconsistent API where a parameter is accepted but conditionally disregarded without documentation or type-system enforcement. Either:

  • Extend the callback to work for all generation types, or
  • Document this limitation in the function's JSDoc and potentially enforce it at the type level (e.g., onStepFinish is only valid when tools are defined)
🧹 Nitpick comments (1)
src/models/text.ts (1)

21-21: Consider improving type safety for the stepResult parameter.

The stepResult parameter is typed as any, which reduces type safety. Consider using a more specific type from the AI SDK (e.g., from the ai package's types) to provide better IntelliSense and catch potential errors at compile time.

For example:

-    onStepFinish?: (stepResult: any) => void | Promise<void>;
+    onStepFinish?: (stepResult: StepResult) => void | Promise<void>;

You may need to import the appropriate type from the ai package if it's exported.

Also applies to: 151-151, 165-165

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

Cache: Disabled due to data retention organization setting

Knowledge base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 211c015 and 12b084d.

📒 Files selected for processing (1)
  • src/models/text.ts (5 hunks)
🔇 Additional comments (1)
src/models/text.ts (1)

98-105: Good implementation of error handling for user callback.

The error handling correctly addresses the previous review feedback. The try-catch block ensures that errors in the user-provided callback won't break the text generation flow, and the error logging properly handles both Error instances and other thrown values.

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