-
Notifications
You must be signed in to change notification settings - Fork 2.3k
feat: Add LlamaIndexWorkflowAdapter #6278
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
Open
leehuwuj
wants to merge
4
commits into
vercel:main
Choose a base branch
from
leehuwuj:lee/add-workflow-stream
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
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,5 @@ | ||
--- | ||
'ai': patch | ||
--- | ||
|
||
Add LlamaIndexWorkflow adapter |
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
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
106 changes: 106 additions & 0 deletions
106
packages/ai/streams/llamaindex-workflow-adapter.test.ts
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,106 @@ | ||
import { | ||
convertReadableStreamToArray, | ||
convertArrayToAsyncIterable, | ||
convertResponseStreamToArray, | ||
} from '@ai-sdk/provider-utils/test'; | ||
import { | ||
toDataStreamResponse, | ||
toDataStream, | ||
} from './llamaindex-workflow-adapter'; | ||
|
||
describe('toWorkflowDataStream', () => { | ||
it('should convert AsyncIterable<WorkflowEventData>', async () => { | ||
const inputStream = convertArrayToAsyncIterable([ | ||
{ data: { delta: 'Hello' } }, | ||
{ data: { foo: 'bar' } }, | ||
{ data: { delta: 'World' } }, | ||
]); | ||
|
||
assert.deepStrictEqual( | ||
await convertReadableStreamToArray(toDataStream(inputStream)), | ||
['0:"Hello"\n', '8:[{"foo":"bar"}]\n', '0:"World"\n'], | ||
); | ||
}); | ||
|
||
it('should support callbacks', async () => { | ||
const inputStream = convertArrayToAsyncIterable([ | ||
{ data: { delta: 'Hello' } }, | ||
{ data: { delta: 'World' } }, | ||
]); | ||
|
||
const callbacks = { | ||
onText: vi.fn(), | ||
}; | ||
|
||
const dataStream = toDataStream(inputStream, callbacks); | ||
|
||
await convertReadableStreamToArray(dataStream); | ||
|
||
expect(callbacks.onText).toHaveBeenCalledTimes(2); | ||
expect(callbacks.onText).toHaveBeenNthCalledWith( | ||
1, | ||
'Hello', | ||
expect.anything(), | ||
); | ||
expect(callbacks.onText).toHaveBeenNthCalledWith( | ||
2, | ||
'World', | ||
expect.anything(), | ||
); | ||
}); | ||
}); | ||
|
||
describe('toDataStreamResponse', () => { | ||
it('should convert AsyncIterable<WorkflowEventData> to a Response', async () => { | ||
const inputStream = convertArrayToAsyncIterable([ | ||
{ data: { delta: 'Hello' } }, | ||
{ data: { delta: 'World' } }, | ||
]); | ||
|
||
const response = toDataStreamResponse(inputStream); | ||
|
||
assert.strictEqual(response.status, 200); | ||
assert.deepStrictEqual(Object.fromEntries(response.headers.entries()), { | ||
'content-type': 'text/plain; charset=utf-8', | ||
'x-vercel-ai-data-stream': 'v1', | ||
}); | ||
|
||
assert.deepStrictEqual(await convertResponseStreamToArray(response), [ | ||
'0:"Hello"\n', | ||
'0:"World"\n', | ||
]); | ||
}); | ||
|
||
it('should support callbacks', async () => { | ||
const inputStream = convertArrayToAsyncIterable([ | ||
{ data: { delta: 'Hello' } }, | ||
{ data: { delta: 'World' } }, | ||
]); | ||
|
||
const callbacks = { | ||
onText: vi.fn(), | ||
}; | ||
|
||
const response = toDataStreamResponse(inputStream, { | ||
callbacks, | ||
}); | ||
|
||
assert.strictEqual(response.status, 200); | ||
assert.deepStrictEqual(Object.fromEntries(response.headers.entries()), { | ||
'content-type': 'text/plain; charset=utf-8', | ||
'x-vercel-ai-data-stream': 'v1', | ||
}); | ||
|
||
assert.deepStrictEqual(await convertResponseStreamToArray(response), [ | ||
'0:"Hello"\n', | ||
'0:"World"\n', | ||
]); | ||
|
||
expect(callbacks.onText).toHaveBeenCalledTimes(2); | ||
expect(callbacks.onText).toHaveBeenNthCalledWith( | ||
1, | ||
'Hello', | ||
expect.anything(), | ||
); | ||
}); | ||
}); |
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,106 @@ | ||
import { formatDataStreamPart, JSONValue } from '@ai-sdk/ui-utils'; | ||
import { DataStreamWriter } from '../core/data-stream/data-stream-writer'; | ||
import { createDataStream } from '../core'; | ||
import { prepareResponseHeaders } from '../core/util/prepare-response-headers'; | ||
|
||
type WorkflowEventData<T> = { | ||
data: T; | ||
}; | ||
|
||
interface StreamCallbacks { | ||
/** `onStart`: Called once when the stream is initialized. */ | ||
onStart?: (dataStreamWriter: DataStreamWriter) => Promise<void> | void; | ||
|
||
/** `onFinal`: Called once when the stream is closed with the final completion message. */ | ||
onFinal?: ( | ||
completion: string, | ||
dataStreamWriter: DataStreamWriter, | ||
) => Promise<void> | void; | ||
|
||
/** `onToken`: Called for each tokenized message. */ | ||
onToken?: ( | ||
token: string, | ||
dataStreamWriter: DataStreamWriter, | ||
) => Promise<void> | void; | ||
|
||
/** `onText`: Called for each text chunk. */ | ||
onText?: ( | ||
text: string, | ||
dataStreamWriter: DataStreamWriter, | ||
) => Promise<void> | void; | ||
} | ||
|
||
export function toDataStream<TEventData>( | ||
stream: AsyncIterable<WorkflowEventData<unknown>>, | ||
callbacks?: StreamCallbacks, | ||
) { | ||
let completionText = ''; | ||
let hasStarted = false; | ||
|
||
return createDataStream({ | ||
execute: async (dataStreamWriter: DataStreamWriter) => { | ||
if (!hasStarted && callbacks?.onStart) { | ||
await callbacks.onStart(dataStreamWriter); | ||
hasStarted = true; | ||
} | ||
|
||
for await (const event of stream) { | ||
const data = event.data; | ||
|
||
if (isTextStream(data)) { | ||
const content = data.delta; | ||
if (content) { | ||
completionText += content; | ||
dataStreamWriter.write(formatDataStreamPart('text', content)); | ||
|
||
if (callbacks?.onText) { | ||
await callbacks.onText(content, dataStreamWriter); | ||
} | ||
} | ||
} else { | ||
dataStreamWriter.writeMessageAnnotation(data as JSONValue); | ||
} | ||
} | ||
|
||
if (callbacks?.onFinal) { | ||
await callbacks.onFinal(completionText, dataStreamWriter); | ||
} | ||
}, | ||
onError: (error: unknown) => { | ||
return error instanceof Error | ||
? error.message | ||
: 'An unknown error occurred during stream finalization'; | ||
}, | ||
}); | ||
} | ||
|
||
export function toDataStreamResponse<TEventData>( | ||
stream: AsyncIterable<WorkflowEventData<TEventData>>, | ||
options: { | ||
init?: ResponseInit; | ||
callbacks?: StreamCallbacks; | ||
} = {}, | ||
) { | ||
const { init, callbacks } = options; | ||
const dataStream = toDataStream(stream, callbacks).pipeThrough( | ||
new TextEncoderStream(), | ||
); | ||
|
||
return new Response(dataStream, { | ||
status: init?.status ?? 200, | ||
statusText: init?.statusText, | ||
headers: prepareResponseHeaders(init?.headers, { | ||
contentType: 'text/plain; charset=utf-8', | ||
dataStreamVersion: 'v1', | ||
}), | ||
}); | ||
} | ||
|
||
function isTextStream(data: unknown): data is { delta: string } { | ||
return ( | ||
typeof data === 'object' && | ||
data !== null && | ||
'delta' in data && | ||
typeof (data as any).delta === 'string' | ||
); | ||
} |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@lgrammel we passed DataStreamWriter to let the callback code modify the datastream - might be generally useful for the existing stream callbacks