Skip to content

feat: [server] Add Human in the Loop example with FastAPI integration #630

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 5 commits into
base: main
Choose a base branch
from

Conversation

leehuwuj
Copy link
Collaborator

  • Introduced a new example in main.py demonstrating the use of LlamaIndexServer with a human in the loop.
  • Enhanced chat API to support resuming workflows with human responses.
  • Implemented WorkflowService for context management in workflow.py.

- Introduced a new example in `main.py` demonstrating the use of LlamaIndexServer with a human in the loop.
- Added a README.md file to explain the example.
- Enhanced chat API to support resuming workflows with human responses.
- Implemented `WorkflowService` for context management in `workflow.py`.
Copy link

changeset-bot bot commented May 19, 2025

⚠️ No Changeset found

Latest commit: 91e9ae1

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link

coderabbitai bot commented May 19, 2025

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. 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.


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.
    • 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? Create a ticket on our support page 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 docstrings to generate docstrings for this 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.

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.

@@ -129,6 +179,25 @@ async def _text_stream(
elif hasattr(event, "to_response"):
event_response = event.to_response()
yield VercelStreamResponse.convert_data(event_response)
elif isinstance(event, InputRequiredEvent):
run_id = handler.workflow_handler.run_id
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what is this run_id - how is it guaranteed that it's not the same between requests?

Copy link
Collaborator Author

@leehuwuj leehuwuj May 19, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A run_id is generated each time we trigger a workflow run, which is unique for every request.
see: https://github.com/run-llama/llama_index/blob/c09c6ae228e6436a00568ad6b03b582307668b66/llama-index-core/llama_index/core/workflow/workflow.py#L239
So it's ideal for storing the workflow context.

import json
from pathlib import Path

from llama_index.core.workflow import Context, JsonSerializer, Workflow
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

from llama_index.server.services.llamacloud import LlamaCloudFileService


class ResumeRequest(BaseModel):
chat_id: str
response: str
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use might response with a more complex answer (e.g. an image and a text) - in TS we're using MessageContent

Suggested change
response: str
response: MessageContent

logger.error(e)
raise HTTPException(status_code=500, detail=str(e))

@router.post("/resume")
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

to ensure this endpoint is working with the UI, it should have the same contract as chat

how about:

class ChatRequest(BaseModel):
    chat_id: Optional[str] = None
    messages: List[ChatAPIMessage]
    data: Optional[Any] = None
    config: Optional[ChatConfig] = ChatConfig()

    @field_validator("messages")
    def validate_messages(cls, v: List[ChatAPIMessage], info: "ValidationInfo") -> List[ChatAPIMessage]:
        if not v:
            raise ValueError("Messages list cannot be empty.")

        chat_id_value = info.data.get("chat_id")
        if chat_id_value is not None:
            if len(v) != 1:
                raise ValueError(
                    "If chat_id is provided, messages list must contain exactly one message."
                )

        if v[-1].role != MessageRole.USER:
            raise ValueError(
                "Last message must be from user."
            )
        return v

run_id=run_id,
ctx=ctx,
)
yield VercelStreamResponse.convert_data(
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this shouldn't be in the streaming code, just extend to_response of InputRequiredEvent

question = "Where is your place now?"
event = await ctx.wait_for_event(
HumanResponseEvent,
waiter_id=question,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why is the question an id?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just a simple UI to demonstrate FE integration

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok, keep in mind that we can't add workflow specific components to the server package (they must be in the dynamic componentsDir), so this is only for testing


class ChatRequest(BaseModel):
id: str # provided by FE
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is it the same as https://ai-sdk.dev/docs/reference/ai-sdk-ui/use-chat#id ? when does it update? e.g. if the user reloads the UI page?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok, keep in mind that we can't add workflow specific components to the server package (they must be in the dynamic componentsDir), so this is only for testing

Comment on lines +59 to +67
human_response = last_message.human_response
if human_response:
previous_ctx = WorkflowService.load_context(request.id, workflow)
# send a new human response event then resume the workflow with the previous context
previous_ctx.send_event(
HumanResponseEvent(
response=human_response,
)
)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

try to separete persistence concern and HITL - if request.id is sent, we should re-create the workflow

Suggested change
human_response = last_message.human_response
if human_response:
previous_ctx = WorkflowService.load_context(request.id, workflow)
# send a new human response event then resume the workflow with the previous context
previous_ctx.send_event(
HumanResponseEvent(
response=human_response,
)
)
if request.id:
previous_ctx = WorkflowService.load_context(request.id, workflow)
# send a new human response event then resume the workflow with the previous context

then we need to run the workflow with a specific event, either start event as is or the human response event

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