-
Notifications
You must be signed in to change notification settings - Fork 188
feat: support human in the loop for TS #686
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
Changes from 13 commits
Commits
Show all changes
37 commits
Select commit
Hold shift + click to select a range
e4c07f9
feat: support human in the loop for TS
thucpn eba44a3
add example for custom workflow
thucpn 7875178
fix: need to request humanResponseEvent to save missing step to snapshot
thucpn ac5a1ef
refactor: human response data should be any
thucpn 832f5b6
refactor runWorkflow function to support resume stream
thucpn 23fdd51
refactor: hitl
thucpn 7b21682
fix: workflow
thucpn ddccbcf
add summary event
thucpn 45af254
send tool event
thucpn be894df
use requestId from Vercel
thucpn 99ff5b4
Merge branch 'main' into tp/hitl-for-ts
thucpn 2d31294
update chat route.ts
thucpn baf16fc
fix copy utils/*
thucpn 98913ed
refactor: workflow and stream
thucpn d93ee94
Create eight-moons-perform.md
thucpn 38cd475
update typo
thucpn 0e67d8a
make schema simple
thucpn 6851960
fix typo
thucpn 537489a
use messages in startAgentEvent
thucpn a440a34
save to snapshots folder
thucpn 0896824
fix lint
thucpn 7e4c68b
feat: workflowBaseEvent
thucpn 6a5db05
include response event in input event
thucpn 8f107f5
simplify type
thucpn 2c062c9
update readme
thucpn af47dbb
update document
thucpn c5c72f5
fix typecheck
thucpn 9b3c1ad
bump: "@llamaindex/workflow": "~1.1.8"
thucpn 66b8db6
remove any
thucpn 22cd865
use fixed tsx version to fix e2e
thucpn 7ee59c5
fix wrong copy
thucpn 5a16f10
add cli hitl examples as a use case for both Python and TS
thucpn 159d15d
update changeset to release create-llama also
thucpn 10fcf50
fix e2e
thucpn 9175ad9
fix e2e
thucpn d4c822d
hitl frontend chat
thucpn 5b06106
try disable hitl test
thucpn File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| This example demonstrates human in the loop workflow. Export OpenAI API key and start the server in dev mode. | ||
|
|
||
| ```bash | ||
| export OPENAI_API_KEY=<your-openai-api-key> | ||
| npx nodemon --exec tsx index.ts | ||
| ``` |
95 changes: 95 additions & 0 deletions
95
packages/server/examples/hitl/components/cli_human_input.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| import { Button } from "@/components/ui/button"; | ||
| import { Card, CardContent, CardFooter } from "@/components/ui/card"; | ||
| import { JSONValue, useChatUI } from "@llamaindex/chat-ui"; | ||
| import React, { FC, useState } from "react"; | ||
| import { z } from "zod"; | ||
|
|
||
| // This schema is equivalent to the CLICommand model defined in events.py | ||
| const CLIInputEventSchema = z.object({ | ||
| command: z.string(), | ||
| }); | ||
| type CLIInputEvent = z.infer<typeof CLIInputEventSchema>; | ||
|
|
||
| const CLIHumanInput: FC<{ | ||
| events: JSONValue[]; | ||
| }> = ({ events }) => { | ||
| const inputEvent = (events || []) | ||
| .map((ev) => { | ||
| const parseResult = CLIInputEventSchema.safeParse(ev); | ||
| return parseResult.success ? parseResult.data : null; | ||
| }) | ||
| .filter((ev): ev is CLIInputEvent => ev !== null) | ||
| .at(-1); | ||
|
|
||
| const { append } = useChatUI(); | ||
| const [confirmedValue, setConfirmedValue] = useState<boolean | null>(null); | ||
| const [editableCommand, setEditableCommand] = useState<string | undefined>( | ||
| inputEvent?.command, | ||
| ); | ||
|
|
||
| // Update editableCommand if inputEvent changes (e.g. new event comes in) | ||
| React.useEffect(() => { | ||
| setEditableCommand(inputEvent?.command); | ||
| }, [inputEvent?.command]); | ||
|
|
||
| const handleConfirm = () => { | ||
| append({ | ||
| content: "Yes", | ||
| role: "user", | ||
| annotations: [ | ||
| { | ||
| type: "human_response", | ||
| data: { | ||
| execute: true, | ||
| command: editableCommand, // Use editable command | ||
| }, | ||
| }, | ||
| ], | ||
| }); | ||
| setConfirmedValue(true); | ||
| }; | ||
|
|
||
| const handleCancel = () => { | ||
| append({ | ||
| content: "No", | ||
| role: "user", | ||
| annotations: [ | ||
| { | ||
| type: "human_response", | ||
| data: { | ||
| execute: false, | ||
| command: inputEvent?.command, | ||
| }, | ||
| }, | ||
| ], | ||
| }); | ||
| setConfirmedValue(false); | ||
| }; | ||
|
|
||
| return ( | ||
| <Card className="my-4"> | ||
| <CardContent className="pt-6"> | ||
| <p className="text-sm text-gray-700"> | ||
| Do you want to execute the following command? | ||
| </p> | ||
| <input | ||
| disabled | ||
| type="text" | ||
| value={editableCommand || ""} | ||
| onChange={(e) => setEditableCommand(e.target.value)} | ||
| className="my-2 w-full overflow-x-auto rounded border border-gray-300 bg-gray-100 p-3 font-mono text-xs text-gray-800" | ||
| /> | ||
| </CardContent> | ||
| {confirmedValue === null ? ( | ||
| <CardFooter className="flex justify-end gap-2"> | ||
| <> | ||
| <Button onClick={handleConfirm}>Yes</Button> | ||
| <Button onClick={handleCancel}>No</Button> | ||
| </> | ||
| </CardFooter> | ||
| ) : null} | ||
| </Card> | ||
| ); | ||
| }; | ||
|
|
||
| export default CLIHumanInput; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| import { OpenAI } from "@llamaindex/openai"; | ||
| import { LlamaIndexServer } from "@llamaindex/server"; | ||
| import { Settings } from "llamaindex"; | ||
| import { workflowFactory } from "./src/app/workflow"; | ||
|
|
||
| Settings.llm = new OpenAI({ | ||
| model: "gpt-4o-mini", | ||
| }); | ||
|
|
||
| new LlamaIndexServer({ | ||
| workflow: workflowFactory, | ||
| uiConfig: { | ||
| starterQuestions: [ | ||
| "List all files in the current directory", | ||
| "Fetch changes from the remote repository", | ||
| ], | ||
| componentsDir: "components", | ||
| }, | ||
| port: 3000, | ||
| }).start(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| import { execSync } from "child_process"; | ||
| import { tool } from "llamaindex"; | ||
| import { z } from "zod"; | ||
|
|
||
| export const cliExecutor = tool({ | ||
| name: "cli_executor", | ||
| description: "This tool executes a command and returns the output.", | ||
| parameters: z.object({ command: z.string() }), | ||
| execute: async ({ command }) => { | ||
| try { | ||
| const output = execSync(command, { | ||
| encoding: "utf-8", | ||
| }); | ||
| return output; | ||
| } catch (error) { | ||
| console.error(error); | ||
| return "Command failed"; | ||
| } | ||
|
thucpn marked this conversation as resolved.
|
||
| }, | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| import { OpenAI } from "@llamaindex/openai"; | ||
| import { | ||
| humanInputEvent, | ||
| humanInputEventSchema, | ||
| humanResponseEvent, | ||
| toAgentRunEvent, | ||
| writeResponseToStream, | ||
| } from "@llamaindex/server"; | ||
| import { chatWithTools } from "@llamaindex/tools"; | ||
| import { | ||
| createWorkflow, | ||
| getContext, | ||
| startAgentEvent, | ||
| stopAgentEvent, | ||
| withSnapshot, | ||
| workflowEvent, | ||
| } from "@llamaindex/workflow"; | ||
| import { ChatMessage, Settings, ToolCallLLM } from "llamaindex"; | ||
| import { z } from "zod"; | ||
| import { cliExecutor } from "./tools"; | ||
|
|
||
| Settings.llm = new OpenAI({ | ||
| model: "gpt-4o-mini", | ||
| }); | ||
|
|
||
| const cliHumanInputEventSchema = humanInputEventSchema.extend({ | ||
| data: z.object({ | ||
| execute: z.boolean(), | ||
| command: z.string(), | ||
| }), | ||
| }); | ||
|
|
||
| const summaryEvent = workflowEvent<string>(); // simple event to summarize the result | ||
|
|
||
| export const workflowFactory = (body: unknown) => { | ||
| const llm = Settings.llm as ToolCallLLM; | ||
|
|
||
| if (!llm.supportToolCall) { | ||
| throw new Error("LLM is not a ToolCallLLM"); | ||
| } | ||
|
|
||
| const { messages } = body as { messages: ChatMessage[] }; | ||
|
thucpn marked this conversation as resolved.
|
||
|
|
||
| const workflow = withSnapshot(createWorkflow()); | ||
|
|
||
| workflow.handle([startAgentEvent], async () => { | ||
| // in this example, we use chatWithTools to decide should perform a tool call or not | ||
| // if cli executor is called, emit HumanInputEvent to ask user for permission | ||
| const toolCallResponse = await chatWithTools(llm, [cliExecutor], messages); | ||
|
thucpn marked this conversation as resolved.
Outdated
thucpn marked this conversation as resolved.
Outdated
|
||
| const cliExecutorToolCall = toolCallResponse.toolCalls.find( | ||
| (toolCall) => toolCall.name === cliExecutor.metadata.name, | ||
| ); | ||
| const command = cliExecutorToolCall?.input?.command; | ||
| if (command) { | ||
| return humanInputEvent.with({ | ||
|
thucpn marked this conversation as resolved.
Outdated
|
||
| data: { command }, | ||
| type: "cli_human_input", | ||
| }); | ||
| } | ||
|
thucpn marked this conversation as resolved.
|
||
|
|
||
| // if no tool call, just response as normal | ||
| return summaryEvent.with(""); | ||
| }); | ||
|
|
||
| // do actions after getting response from human | ||
| workflow.handle([humanResponseEvent], async ({ data }) => { | ||
|
thucpn marked this conversation as resolved.
Outdated
|
||
| const { sendEvent } = getContext(); | ||
|
|
||
| const parsedData = cliHumanInputEventSchema.safeParse(data); | ||
| if (!parsedData.success) { | ||
| throw new Error("Invalid human input event data"); | ||
| } | ||
| const { command, execute } = parsedData.data.data; | ||
|
|
||
| if (!execute) { | ||
| // stop the workflow if user reject to execute the command | ||
| return summaryEvent.with(`User reject to execute the command ${command}`); | ||
|
thucpn marked this conversation as resolved.
|
||
| } | ||
|
|
||
| sendEvent( | ||
| toAgentRunEvent({ | ||
| agent: "CLI Executor", | ||
| text: `Execute the command "${command}" and return the result`, | ||
| type: "text", | ||
| }), | ||
| ); | ||
|
|
||
| const result = (await cliExecutor.call({ command })) as string; | ||
|
|
||
| return summaryEvent.with( | ||
| `Execute the command ${command} and return the result: ${result}`, | ||
|
thucpn marked this conversation as resolved.
Outdated
|
||
| ); | ||
| }); | ||
|
|
||
| workflow.handle([summaryEvent], async ({ data: summaryResult }) => { | ||
| const { sendEvent } = getContext(); | ||
|
|
||
| const chatHistory = messages; | ||
| if (summaryResult) { | ||
| chatHistory.push({ role: "user", content: summaryResult }); | ||
| } | ||
|
|
||
| const stream = await llm.chat({ | ||
| messages: chatHistory, | ||
| stream: true, | ||
| }); | ||
|
|
||
| const result = await writeResponseToStream(stream, sendEvent); | ||
|
|
||
| return stopAgentEvent.with({ result }); | ||
| }); | ||
|
|
||
| return workflow; | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
|
thucpn marked this conversation as resolved.
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.