mirror of
https://github.com/run-llama/LlamaIndexTS.git
synced 2026-07-05 12:05:56 -04:00
Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 109ec63779 | |||
| 82d4b46fe4 | |||
| f8c2d0b8ad | |||
| 6d7bc4ccbb | |||
| 294f502441 |
@@ -7,3 +7,4 @@ dist/
|
||||
.source/
|
||||
# prttier doesn't support mdx3 we are using
|
||||
*.mdx
|
||||
packages/server/server/
|
||||
@@ -57,6 +57,41 @@ const researchAgent = agent({
|
||||
});
|
||||
```
|
||||
|
||||
## MCP tools
|
||||
|
||||
If you have a MCP server running, you can fetch tools from the server and use them in your agents.
|
||||
|
||||
```ts
|
||||
// 1. Import MCP tools adapter
|
||||
import { mcp } from "@llamaindex/tools";
|
||||
import { agent } from "llamaindex";
|
||||
|
||||
// 2. Initialize a MCP client
|
||||
// by npx
|
||||
const server = mcp({
|
||||
command: "npx",
|
||||
args: ["-y", "@modelcontextprotocol/server-filesystem", "."],
|
||||
verbose: true,
|
||||
});
|
||||
// or by SSE
|
||||
const server = mcp({
|
||||
url: "http://localhost:8000/mcp",
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
// 3. Get tools from MCP server
|
||||
const tools = await server.tools();
|
||||
|
||||
// Now you can create an agent with the tools
|
||||
const agent = agent({
|
||||
name: "My Agent",
|
||||
systemPrompt: "You are a helpful assistant that can use the provided tools to answer questions.",
|
||||
llm: openai({ model: "gpt-4o" }),
|
||||
tools: tools,
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
## Function tool
|
||||
|
||||
You can still use the `FunctionTool` class to define a tool.
|
||||
|
||||
@@ -2,149 +2,260 @@
|
||||
title: Workflows
|
||||
---
|
||||
|
||||
A `Workflow` in LlamaIndexTS is an event-driven abstraction used to chain together several events. Workflows are made up of `steps`, with each step responsible for handling certain event types and emitting new events.
|
||||
|
||||
Workflows in LlamaIndexTS work by defining step functions that handle specific event types and emit new events.
|
||||
|
||||
When a step function is added to a workflow, you need to specify the input and optionally the output event types (used for validation). The specification of the input events ensures each step only runs when an accepted event is ready.
|
||||
|
||||
You can create a `Workflow` to do anything! Build an agent, a RAG flow, an extraction flow, or anything else you want.
|
||||
A `Workflow` in LlamaIndex is a lightweight, event-driven abstraction used to chain together several events. Workflows are made up of `handlers`, with each one responsible for processing specific event types and emitting new events.
|
||||
|
||||
Workflows are designed to be flexible and can be used to build agents, RAG flows, extraction flows, or anything else you want to implement.
|
||||
|
||||
```package-install
|
||||
npm i @llamaindex/workflow
|
||||
npm i @llama-flow/core @llamaindex/openai
|
||||
```
|
||||
|
||||
## Getting Started
|
||||
|
||||
As an illustrative example, let's consider a naive workflow where a joke is generated and then critiqued.
|
||||
Let's explore a simple workflow example where a joke is generated and then critiqued and iterated on:
|
||||
|
||||
<include cwd>../../examples/workflow/joke.ts</include>
|
||||
```typescript
|
||||
import { OpenAI } from "@llamaindex/openai";
|
||||
import { createWorkflow, workflowEvent } from "@llama-flow/core";
|
||||
import { withStore } from "@llama-flow/core/middleware/store";
|
||||
|
||||
There's a few moving pieces here, so let's go through this piece by piece.
|
||||
// Create LLM instance
|
||||
const llm = new OpenAI({ model: "gpt-4.1-mini", apiKey: "..."});
|
||||
|
||||
// Define our workflow events
|
||||
const startEvent = workflowEvent<string>(); // Input topic for joke
|
||||
const jokeEvent = workflowEvent<{ joke: string }>(); // Intermediate joke
|
||||
const critiqueEvent = workflowEvent<{ joke: string, critique: string }>(); // Intermediate critique
|
||||
const resultEvent = workflowEvent<{ joke: string, critique: string }>(); // Final joke + critique
|
||||
|
||||
// Create our workflow
|
||||
const jokeFlow = withStore(
|
||||
() => ({
|
||||
numIterations: 0,
|
||||
maxIterations: 3,
|
||||
}),
|
||||
createWorkflow()
|
||||
);
|
||||
|
||||
// Define handlers for each step
|
||||
jokeFlow.handle([startEvent], async (event) => {
|
||||
// Prompt the LLM to write a joke
|
||||
const prompt = `Write your best joke about ${event.data}. Write the joke between <joke> and </joke> tags.`;
|
||||
const response = await llm.complete({ prompt });
|
||||
|
||||
// Parse the joke from the response
|
||||
const joke = response.text.match(/<joke>([\s\S]*?)<\/joke>/)?.[1]?.trim() ?? response.text;
|
||||
return jokeEvent.with({ joke: joke });
|
||||
});
|
||||
|
||||
jokeFlow.handle([jokeEvent], async (event) => {
|
||||
// Prompt the LLM to critique the joke
|
||||
const prompt = `Give a thorough critique of the following joke. If the joke needs improvement, put "IMPROVE" somewhere in the critique: ${event.data.joke}`;
|
||||
const response = await llm.complete({ prompt });
|
||||
|
||||
// If the critique includes "IMPROVE", keep iterating, else, return the result
|
||||
if (response.text.includes("IMPROVE")) {
|
||||
return critiqueEvent.with({ joke: event.data.joke, critique: response.text });
|
||||
}
|
||||
|
||||
return resultEvent.with({ joke: event.data.joke, critique: response.text });
|
||||
});
|
||||
|
||||
jokeFlow.handle([critiqueEvent], async (event) => {
|
||||
// Keep track of the number of iterations
|
||||
const store = jokeFlow.getStore();
|
||||
store.numIterations++;
|
||||
|
||||
// Write a new joke based on the previous joke and critique
|
||||
const prompt = `Write a new joke based on the following critique and the original joke. Write the joke between <joke> and </joke> tags.\n\nJoke: ${event.data.joke}\n\nCritique: ${event.data.critique}`;
|
||||
const response = await llm.complete({ prompt });
|
||||
|
||||
// Parse the joke from the response
|
||||
const joke = response.text.match(/<joke>([\s\S]*?)<\/joke>/)?.[1]?.trim() ?? response.text;
|
||||
|
||||
// If we've done less than the max number of iterations, keep iterating
|
||||
// else, return the result
|
||||
if (store.numIterations < store.maxIterations) {
|
||||
return jokeEvent.with({ joke: joke });
|
||||
}
|
||||
|
||||
return resultEvent.with({ joke: joke, critique: event.data.critique });
|
||||
});
|
||||
|
||||
// Usage
|
||||
async function main() {
|
||||
const { stream, sendEvent } = jokeFlow.createContext();
|
||||
sendEvent(startEvent.with("pirates"));
|
||||
|
||||
let result: { joke: string, critique: string } | undefined;
|
||||
|
||||
for await (const event of stream) {
|
||||
// console.log(event.data); optionally log the event data
|
||||
if (resultEvent.include(event)) {
|
||||
result = event.data;
|
||||
break; // Stop when we get the final result
|
||||
}
|
||||
}
|
||||
|
||||
console.log(result);
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
```
|
||||
|
||||
There are a few moving pieces here, so let's go through this step by step.
|
||||
|
||||
### Defining Workflow Events
|
||||
|
||||
```typescript
|
||||
export class JokeEvent extends WorkflowEvent<{ joke: string }> {}
|
||||
const startEvent = workflowEvent<string>(); // Input topic for joke
|
||||
const jokeEvent = workflowEvent<{ joke: string }>(); // Intermediate joke
|
||||
const critiqueEvent = workflowEvent<{ joke: string, critique: string }>(); // Intermediate critique
|
||||
const resultEvent = workflowEvent<{ joke: string, critique: string }>(); // Final joke + critique
|
||||
```
|
||||
|
||||
Events are user-defined classes that extend `WorkflowEvent` and contain arbitrary data provided as template argument. In this case, our workflow relies on a single user-defined event, the `JokeEvent` with a `joke` attribute of type `string`.
|
||||
Events are defined using the `workflowEvent` function and contain arbitrary data provided as a generic type. In this example, we have four events:
|
||||
- `startEvent`: Takes a string input (the joke topic)
|
||||
- `jokeEvent`: Contains an object with a joke property
|
||||
- `critiqueEvent`: Contains both the joke and its critique, used for the feedback loop
|
||||
- `resultEvent`: Contains the final joke and critique after any iterations
|
||||
|
||||
### Setting up the Workflow Class
|
||||
### Setting up the Workflow with Store Middleware
|
||||
|
||||
```typescript
|
||||
const llm = new OpenAI();
|
||||
...
|
||||
const jokeFlow = new Workflow<unknown, string, string>();
|
||||
```
|
||||
|
||||
Our workflow is implemented by initiating the `Workflow` class with three generic types: the context type (unknown), input type (string), and output type (string). The context type is `unknown`, as we're not using a shared context in this example.
|
||||
|
||||
For simplicity, we created an `OpenAI` llm instance that we're using for inference in our workflow.
|
||||
|
||||
### Workflow Entry Points
|
||||
|
||||
```typescript
|
||||
const generateJoke = async (_: unknown, ev: StartEvent<string>) => {
|
||||
const prompt = `Write your best joke about ${ev.data}.`;
|
||||
const response = await llm.complete({ prompt });
|
||||
return new JokeEvent({ joke: response.text });
|
||||
};
|
||||
```
|
||||
|
||||
Here, we come to the entry-point of our workflow. While events are user-defined, there are two special-case events, the `StartEvent` and the `StopEvent`. These events are predefined, but we can specify the payload type using generic types. We're using `StartEvent<string>` to indicate that we're going to send an input of type string.
|
||||
|
||||
To add this step to the workflow, we use the `addStep` method with an object specifying the input and output event types:
|
||||
|
||||
```typescript
|
||||
jokeFlow.addStep(
|
||||
{
|
||||
inputs: [StartEvent<string>],
|
||||
outputs: [JokeEvent],
|
||||
},
|
||||
generateJoke
|
||||
const jokeFlow = withStore(
|
||||
() => ({
|
||||
numIterations: 0,
|
||||
maxIterations: 3,
|
||||
}),
|
||||
createWorkflow()
|
||||
);
|
||||
```
|
||||
|
||||
### Workflow Exit Points
|
||||
Our workflow is implemented using the `createWorkflow()` function, enhanced with the `withStore` middleware. The store provides shared state across all handlers, which in this case tracks:
|
||||
- `numIterations`: Counts how many iterations of joke improvement we've done
|
||||
- `maxIterations`: Sets a limit to prevent infinite loops
|
||||
|
||||
This store will be accesible within workflows by using the `jokeFlow.getStore()` function.
|
||||
|
||||
### Adding Handlers with Loops
|
||||
|
||||
We have three key handlers in our workflow:
|
||||
|
||||
1. The first handler processes the `startEvent`, generates an initial joke, and emits a `jokeEvent`:
|
||||
|
||||
```typescript
|
||||
const critiqueJoke = async (_: unknown, ev: JokeEvent) => {
|
||||
const prompt = `Give a thorough critique of the following joke: ${ev.data.joke}`;
|
||||
jokeFlow.handle([startEvent], async (event) => {
|
||||
// Prompt the LLM to write a joke
|
||||
const prompt = `Write your best joke about ${event.data}. Write the joke between <joke> and </joke> tags.`;
|
||||
const response = await llm.complete({ prompt });
|
||||
return new StopEvent(response.text);
|
||||
};
|
||||
|
||||
// Parse the joke from the response
|
||||
const joke = response.text.match(/<joke>([\s\S]*?)<\/joke>/)?.[1]?.trim() ?? response.text;
|
||||
return jokeEvent.with({ joke: joke });
|
||||
});
|
||||
```
|
||||
|
||||
Here, we have our second and last step in the workflow. We know it's the last step because the special `StopEvent` is returned. When the workflow encounters a returned `StopEvent`, it immediately stops the workflow and returns the result. Note that we're using the generic type `StopEvent<string>` to indicate that we're returning a string.
|
||||
|
||||
Add this step to the workflow:
|
||||
2. The second handler handles the `jokeEvent`, critiques the joke, and either:
|
||||
- Emits a `critiqueEvent` if the joke needs improvement
|
||||
- Emits a `resultEvent` if the joke is good enough
|
||||
|
||||
```typescript
|
||||
jokeFlow.addStep(
|
||||
{
|
||||
inputs: [JokeEvent],
|
||||
outputs: [StopEvent<string>],
|
||||
},
|
||||
critiqueJoke
|
||||
);
|
||||
jokeFlow.handle([jokeEvent], async (event) => {
|
||||
// Prompt the LLM to critique the joke
|
||||
const prompt = `Give a thorough critique of the following joke. If the joke needs improvement, put "IMPROVE" somewhere in the critique: ${event.data.joke}`;
|
||||
const response = await llm.complete({ prompt });
|
||||
|
||||
// If the critique includes "IMPROVE", keep iterating, else, return the result
|
||||
if (response.text.includes("IMPROVE")) {
|
||||
return critiqueEvent.with({ joke: event.data.joke, critique: response.text });
|
||||
}
|
||||
|
||||
return resultEvent.with({ joke: event.data.joke, critique: response.text });
|
||||
});
|
||||
```
|
||||
|
||||
3. The third handler processes the `critiqueEvent`, generates an improved joke based on the critique, and either:
|
||||
- Loops back to the joke evaluation (if under the iteration limit)
|
||||
- Emits the final `resultEvent` (if iteration limit reached)
|
||||
|
||||
```typescript
|
||||
jokeFlow.handle([critiqueEvent], async (event) => {
|
||||
// Keep track of the number of iterations
|
||||
const store = jokeFlow.getStore();
|
||||
store.numIterations++;
|
||||
|
||||
// Write a new joke based on the previous joke and critique
|
||||
const prompt = `Write a new joke based on the following critique and the original joke. Write the joke between <joke> and </joke> tags.\n\nJoke: ${event.data.joke}\n\nCritique: ${event.data.critique}`;
|
||||
const response = await llm.complete({ prompt });
|
||||
|
||||
// Parse the joke from the response
|
||||
const joke = response.text.match(/<joke>([\s\S]*?)<\/joke>/)?.[1]?.trim() ?? response.text;
|
||||
|
||||
// If we've done less than the max number of iterations, keep iterating
|
||||
// else, return the result
|
||||
if (store.numIterations < store.maxIterations) {
|
||||
return jokeEvent.with({ joke: joke });
|
||||
}
|
||||
|
||||
return resultEvent.with({ joke: joke, critique: event.data.critique });
|
||||
});
|
||||
```
|
||||
|
||||
### Running the Workflow
|
||||
|
||||
```typescript
|
||||
const result = await jokeFlow.run("pirates");
|
||||
console.log(result.data.result);
|
||||
```
|
||||
async function main() {
|
||||
const { stream, sendEvent } = jokeFlow.createContext();
|
||||
sendEvent(startEvent.with("pirates"));
|
||||
|
||||
Lastly, we run the workflow. The `.run()` method is async, so we use await here to wait for the result.
|
||||
let result: { joke: string, critique: string } | undefined;
|
||||
|
||||
## Working with Shared Context/State
|
||||
|
||||
Optionally, you can choose to use a shared context between steps by specifying a context type when creating the workflow. Here's an example where multiple steps access a shared state:
|
||||
|
||||
```typescript
|
||||
import { HandlerContext } from "llamaindex";
|
||||
|
||||
type MyContextData = {
|
||||
query: string;
|
||||
intermediateResults: any[];
|
||||
for await (const event of stream) {
|
||||
// console.log(event.data); optionally log the event data
|
||||
if (resultEvent.include(event)) {
|
||||
result = event.data;
|
||||
break; // Stop when we get the final result
|
||||
}
|
||||
}
|
||||
|
||||
console.log(result);
|
||||
}
|
||||
|
||||
const query = async (context: HandlerContext<MyContextData>, ev: MyEvent) => {
|
||||
// get the query from the context
|
||||
const query = context.data.query;
|
||||
// do something with context and event
|
||||
const val = ...
|
||||
// store in context
|
||||
context.data.intermediateResults.push(val);
|
||||
|
||||
return new StopEvent({ result });
|
||||
};
|
||||
```
|
||||
|
||||
## Waiting for Multiple Events
|
||||
To run the workflow, we:
|
||||
1. Create a workflow context with `createContext()`
|
||||
2. Trigger the initial event with `sendEvent()`
|
||||
3. Listen to the event stream and process events as they arrive
|
||||
4. Use `include()` to check if an event is of a specific type
|
||||
5. Break the loop when we receive our final result
|
||||
|
||||
The context does more than just hold data, it also provides utilities to buffer and wait for multiple events.
|
||||
### Using Stream Utilities
|
||||
|
||||
For example, you might have a step that waits for a query and retrieved nodes before synthesizing a response:
|
||||
Workflows provide utility functions to make working with event streams easier:
|
||||
|
||||
```typescript
|
||||
const synthesize = async (context: Context, ev1: QueryEvent, ev2: RetrieveEvent) => {
|
||||
const subPrompts = [`Answer this query using the context provided: ${ev1.data.query}`, `Context: ${ev2.data.context}`];
|
||||
const prompt = subPrompts.join("\n");
|
||||
const response = await llm.complete({ prompt });
|
||||
return new StopEvent({ result: response.text });
|
||||
};
|
||||
import { collect } from "@llama-flow/core/stream/consumer";
|
||||
import { until } from "@llama-flow/core/stream/until";
|
||||
|
||||
// Create a workflow context and send the initial event
|
||||
const { stream, sendEvent } = jokeFlow.createContext();
|
||||
sendEvent(startEvent.with("pirates"));
|
||||
|
||||
// Collect all events until we get a resultEvent
|
||||
const allEvents = await collect(until(stream, resultEvent));
|
||||
|
||||
// The last event will be the resultEvent
|
||||
const finalEvent = allEvents[allEvents.length - 1];
|
||||
console.log(finalEvent.data); // Output the joke and critique
|
||||
```
|
||||
|
||||
Passing multiple events, we can buffer and wait for ALL expected events to arrive. The receiving step function will only be called once all events have arrived.
|
||||
The stream utilities make it easier to work with the asynchronous event flow. In this example, we use:
|
||||
- `collect`: Aggregates all events into an array
|
||||
- `until`: Creates a stream that emits events until a condition is met (in this case, until a resultEvent is received)
|
||||
|
||||
## Manually Triggering Events
|
||||
You can combine these utilities with other stream operators like `filter` and `map` to create powerful processing pipelines.
|
||||
|
||||
Normally, events are triggered by returning another event during a step. However, events can also be manually dispatched using the `ctx.sendEvent(event)` method within a workflow.
|
||||
## Next Steps
|
||||
|
||||
## Examples
|
||||
|
||||
You can find many useful examples of using workflows in the [examples folder](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/workflow).
|
||||
To learn more about workflows, check out [the documentation in the tutorial section](../../../llamaflow).
|
||||
|
||||
@@ -1,5 +1,20 @@
|
||||
# examples
|
||||
|
||||
## 0.3.12
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [82d4b46]
|
||||
- @llamaindex/server@0.1.6
|
||||
- @llamaindex/tools@0.0.7
|
||||
|
||||
## 0.3.11
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [294f502]
|
||||
- @llamaindex/tools@0.0.6
|
||||
|
||||
## 0.3.10
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -9,6 +9,12 @@ async function main() {
|
||||
args: ["-y", "@modelcontextprotocol/server-filesystem", "."],
|
||||
verbose: true,
|
||||
});
|
||||
// You can also connect to the MCP server using SSE
|
||||
// See: https://modelcontextprotocol.io/docs/concepts/transports#server-sent-events-sse
|
||||
// const server = mcp({
|
||||
// url: "http://localhost:8000/mcp",
|
||||
// verbose: true,
|
||||
// });
|
||||
|
||||
try {
|
||||
// Create an agent that uses the MCP tools
|
||||
@@ -21,9 +27,7 @@ async function main() {
|
||||
});
|
||||
|
||||
// Run a task
|
||||
const response = await myAgent.run(
|
||||
"what are the files in the current directory?",
|
||||
);
|
||||
const response = await myAgent.run("What are the available tools?");
|
||||
|
||||
console.log("Agent response:", response.data);
|
||||
} finally {
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
# Run LlamaIndex Server with simple steps
|
||||
|
||||
1. Setup environment variables
|
||||
|
||||
```bash
|
||||
export OPENAI_API_KEY=<your-openai-api-key>
|
||||
```
|
||||
|
||||
2. Run the server
|
||||
|
||||
```bash
|
||||
npx tsx llamaindex-server/simple-workflow/index.ts
|
||||
```
|
||||
|
||||
3. Open the app at `http://localhost:4000` and start chatting with the agent
|
||||
|
||||

|
||||
Binary file not shown.
|
After Width: | Height: | Size: 118 KiB |
@@ -0,0 +1,19 @@
|
||||
import { OpenAI } from "@llamaindex/openai";
|
||||
import { LlamaIndexServer } from "@llamaindex/server";
|
||||
import { weather } from "@llamaindex/tools";
|
||||
import "dotenv/config";
|
||||
import { agent } from "llamaindex";
|
||||
|
||||
const weatherAgent = agent({
|
||||
tools: [weather()],
|
||||
llm: new OpenAI({ model: "gpt-4o-mini" }),
|
||||
});
|
||||
|
||||
new LlamaIndexServer({
|
||||
workflow: () => weatherAgent,
|
||||
uiConfig: {
|
||||
appTitle: "Weather Agent",
|
||||
starterQuestions: ["Ho Chi Minh city weather", "New York weather"],
|
||||
},
|
||||
port: 4000,
|
||||
}).start();
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@llamaindex/examples",
|
||||
"version": "0.3.10",
|
||||
"version": "0.3.12",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"lint": "eslint .",
|
||||
@@ -50,8 +50,9 @@
|
||||
"@llamaindex/together": "^0.0.12",
|
||||
"@llamaindex/jinaai": "^0.0.12",
|
||||
"@llamaindex/perplexity": "^0.0.9",
|
||||
"@llamaindex/server": "^0.1.6",
|
||||
"@llamaindex/supabase": "^0.1.1",
|
||||
"@llamaindex/tools": "^0.0.5",
|
||||
"@llamaindex/tools": "^0.0.7",
|
||||
"@notionhq/client": "^2.2.15",
|
||||
"@pinecone-database/pinecone": "^4.0.0",
|
||||
"@llamaindex/assemblyai": "^0.1.1",
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
# Workflow Examples
|
||||
|
||||
These examples demonstrate LlamaIndexTS's workflow system. Check out [its documentation](https://ts.llamaindex.ai/modules/workflows) for more information.
|
||||
|
||||
## Running the Examples
|
||||
|
||||
To run the examples, make sure to run them from the parent folder called `examples`). For example, to run the joke workflow, run `npx tsx workflow/joke.ts`.
|
||||
@@ -1,157 +0,0 @@
|
||||
import { OpenAI } from "@llamaindex/openai";
|
||||
import {
|
||||
HandlerContext,
|
||||
StartEvent,
|
||||
StopEvent,
|
||||
Workflow,
|
||||
WorkflowEvent,
|
||||
} from "llamaindex";
|
||||
|
||||
const MAX_REVIEWS = 3;
|
||||
|
||||
type Context = {
|
||||
specification: string;
|
||||
numberReviews: number;
|
||||
};
|
||||
|
||||
// Using the o1-preview model (see https://platform.openai.com/docs/guides/reasoning?reasoning-prompt-examples=coding-planning)
|
||||
const llm = new OpenAI({ model: "o1-preview", temperature: 1 });
|
||||
|
||||
// example specification from https://platform.openai.com/docs/guides/reasoning?reasoning-prompt-examples=coding-planning
|
||||
const specification = `Python app that takes user questions and looks them up in a
|
||||
database where they are mapped to answers. If there is a close match, it retrieves
|
||||
the matched answer. If there isn't, it asks the user to provide an answer and
|
||||
stores the question/answer pair in the database.`;
|
||||
|
||||
// Create custom event types
|
||||
export class MessageEvent extends WorkflowEvent<{ msg: string }> {}
|
||||
|
||||
export class CodeEvent extends WorkflowEvent<{ code: string }> {}
|
||||
|
||||
export class ReviewEvent extends WorkflowEvent<{
|
||||
review: string;
|
||||
code: string;
|
||||
}> {}
|
||||
|
||||
// Helper function to truncate long strings
|
||||
const truncate = (str: string) => {
|
||||
const MAX_LENGTH = 60;
|
||||
if (str.length <= MAX_LENGTH) return str;
|
||||
return str.slice(0, MAX_LENGTH) + "...";
|
||||
};
|
||||
|
||||
// the architect is responsible for writing the structure and the initial code based on the specification
|
||||
const architect = async (
|
||||
context: HandlerContext<Context>,
|
||||
_: StartEvent<string>,
|
||||
) => {
|
||||
const spec = context.data.specification;
|
||||
// write a message to send an update to the user
|
||||
context.sendEvent(
|
||||
new MessageEvent({
|
||||
msg: `Writing app using this specification: ${truncate(spec)}`,
|
||||
}),
|
||||
);
|
||||
const prompt = `Build an app for this specification: <spec>${spec}</spec>. Make a plan for the directory structure you'll need, then return each file in full. Don't supply any reasoning, just code.`;
|
||||
const code = await llm.complete({ prompt });
|
||||
return new CodeEvent({ code: code.text });
|
||||
};
|
||||
|
||||
// the coder is responsible for updating the code based on the review
|
||||
const coder = async (context: HandlerContext<Context>, ev: ReviewEvent) => {
|
||||
// get the specification from the context
|
||||
const spec = context.data.specification;
|
||||
// get the latest review and code
|
||||
const { review, code } = ev.data;
|
||||
// write a message to send an update to the user
|
||||
context.sendEvent(
|
||||
new MessageEvent({
|
||||
msg: `Update code based on review: ${truncate(review)}`,
|
||||
}),
|
||||
);
|
||||
const prompt = `We need to improve code that should implement this specification: <spec>${spec}</spec>. Here is the current code: <code>${code}</code>. And here is a review of the code: <review>${review}</review>. Improve the code based on the review, keep the specification in mind, and return the full updated code. Don't supply any reasoning, just code.`;
|
||||
const updatedCode = await llm.complete({ prompt });
|
||||
return new CodeEvent({ code: updatedCode.text });
|
||||
};
|
||||
|
||||
// the reviewer is responsible for reviewing the code and providing feedback
|
||||
const reviewer = async (context: HandlerContext<Context>, ev: CodeEvent) => {
|
||||
// get the specification from the context
|
||||
const spec = context.data.specification;
|
||||
// get latest code from the event
|
||||
const { code } = ev.data;
|
||||
// update and check the number of reviews
|
||||
context.data.numberReviews++;
|
||||
if (context.data.numberReviews > MAX_REVIEWS) {
|
||||
// the we've done this too many times - return the code
|
||||
context.sendEvent(
|
||||
new MessageEvent({
|
||||
msg: `Already reviewed ${
|
||||
context.data.numberReviews - 1
|
||||
} times, stopping!`,
|
||||
}),
|
||||
);
|
||||
return new StopEvent({ result: code });
|
||||
}
|
||||
// write a message to send an update to the user
|
||||
context.sendEvent(
|
||||
new MessageEvent({
|
||||
msg: `Review #${context.data.numberReviews}: ${truncate(code)}`,
|
||||
}),
|
||||
);
|
||||
const prompt = `Review this code: <code>${code}</code>. Check if the code quality and whether it correctly implements this specification: <spec>${spec}</spec>. If you're satisfied, just return 'Looks great', nothing else. If not, return a review with a list of changes you'd like to see.`;
|
||||
const review = (await llm.complete({ prompt })).text;
|
||||
if (review.includes("Looks great")) {
|
||||
// the reviewer is satisfied with the code, let's return the review
|
||||
context.sendEvent(
|
||||
new MessageEvent({
|
||||
msg: `Reviewer says: ${review}`,
|
||||
}),
|
||||
);
|
||||
return new StopEvent({ result: code });
|
||||
}
|
||||
|
||||
return new ReviewEvent({ review, code });
|
||||
};
|
||||
|
||||
const codeAgent = new Workflow<Context, string, string>();
|
||||
codeAgent.addStep(
|
||||
{
|
||||
inputs: [StartEvent<string>],
|
||||
outputs: [CodeEvent],
|
||||
},
|
||||
architect,
|
||||
);
|
||||
codeAgent.addStep(
|
||||
{
|
||||
inputs: [ReviewEvent],
|
||||
outputs: [CodeEvent],
|
||||
},
|
||||
coder,
|
||||
);
|
||||
codeAgent.addStep(
|
||||
{
|
||||
inputs: [CodeEvent],
|
||||
outputs: [ReviewEvent, StopEvent],
|
||||
},
|
||||
reviewer,
|
||||
);
|
||||
|
||||
// Usage
|
||||
async function main() {
|
||||
const run = codeAgent.run(specification).with({
|
||||
specification,
|
||||
numberReviews: 0,
|
||||
});
|
||||
for await (const event of run) {
|
||||
if (event instanceof MessageEvent) {
|
||||
const msg = (event as MessageEvent).data.msg;
|
||||
console.log(`${msg}\n`);
|
||||
} else if (event instanceof StopEvent) {
|
||||
const result = (event as StopEvent<string>).data;
|
||||
console.log("Final code:\n", result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,88 +0,0 @@
|
||||
import { OpenAI } from "@llamaindex/openai";
|
||||
import {
|
||||
HandlerContext,
|
||||
StartEvent,
|
||||
StopEvent,
|
||||
Workflow,
|
||||
WorkflowEvent,
|
||||
} from "llamaindex";
|
||||
|
||||
// Create LLM instance
|
||||
const llm = new OpenAI();
|
||||
|
||||
// Create custom event types
|
||||
export class JokeEvent extends WorkflowEvent<{ joke: string }> {}
|
||||
|
||||
export class CritiqueEvent extends WorkflowEvent<{ critique: string }> {}
|
||||
|
||||
export class AnalysisEvent extends WorkflowEvent<{ analysis: string }> {}
|
||||
|
||||
const generateJoke = async (_: unknown, ev: StartEvent<string>) => {
|
||||
const prompt = `Write your best joke about ${ev.data}.`;
|
||||
const response = await llm.complete({ prompt });
|
||||
return new JokeEvent({ joke: response.text });
|
||||
};
|
||||
|
||||
const critiqueJoke = async (_: unknown, ev: JokeEvent) => {
|
||||
const prompt = `Give a thorough critique of the following joke: ${ev.data.joke}`;
|
||||
const response = await llm.complete({ prompt });
|
||||
return new CritiqueEvent({ critique: response.text });
|
||||
};
|
||||
|
||||
const analyzeJoke = async (_: unknown, ev: JokeEvent) => {
|
||||
const prompt = `Give a thorough analysis of the following joke: ${ev.data.joke}`;
|
||||
const response = await llm.complete({ prompt });
|
||||
return new AnalysisEvent({ analysis: response.text });
|
||||
};
|
||||
|
||||
const reportJoke = async (
|
||||
context: HandlerContext,
|
||||
ev1: AnalysisEvent,
|
||||
ev2: CritiqueEvent,
|
||||
) => {
|
||||
const subPrompts = [ev1.data.analysis, ev2.data.critique];
|
||||
|
||||
const prompt = `Based on the following information about a joke:\n${subPrompts.join(
|
||||
"\n",
|
||||
)}\nProvide a comprehensive report on the joke's quality and impact.`;
|
||||
const response = await llm.complete({ prompt });
|
||||
return new StopEvent(response.text);
|
||||
};
|
||||
|
||||
const jokeFlow = new Workflow<unknown, string, string>();
|
||||
jokeFlow.addStep(
|
||||
{
|
||||
inputs: [StartEvent<string>],
|
||||
outputs: [JokeEvent],
|
||||
},
|
||||
generateJoke,
|
||||
);
|
||||
jokeFlow.addStep(
|
||||
{
|
||||
inputs: [JokeEvent],
|
||||
outputs: [CritiqueEvent],
|
||||
},
|
||||
critiqueJoke,
|
||||
);
|
||||
jokeFlow.addStep(
|
||||
{
|
||||
inputs: [JokeEvent],
|
||||
outputs: [AnalysisEvent],
|
||||
},
|
||||
analyzeJoke,
|
||||
);
|
||||
jokeFlow.addStep(
|
||||
{
|
||||
inputs: [AnalysisEvent, CritiqueEvent],
|
||||
outputs: [StopEvent<string>],
|
||||
},
|
||||
reportJoke,
|
||||
);
|
||||
|
||||
// Usage
|
||||
async function main() {
|
||||
const result = await jokeFlow.run("pirates");
|
||||
console.log(result.data);
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,44 +0,0 @@
|
||||
import { OpenAI } from "@llamaindex/openai";
|
||||
import { StartEvent, StopEvent, Workflow, WorkflowEvent } from "llamaindex";
|
||||
|
||||
// Create LLM instance
|
||||
const llm = new OpenAI();
|
||||
|
||||
// Create a custom event type
|
||||
export class JokeEvent extends WorkflowEvent<{ joke: string }> {}
|
||||
|
||||
const generateJoke = async (_: unknown, ev: StartEvent<string>) => {
|
||||
const prompt = `Write your best joke about ${ev.data}.`;
|
||||
const response = await llm.complete({ prompt });
|
||||
return new JokeEvent({ joke: response.text });
|
||||
};
|
||||
|
||||
const critiqueJoke = async (_: unknown, ev: JokeEvent) => {
|
||||
const prompt = `Give a thorough critique of the following joke: ${ev.data.joke}`;
|
||||
const response = await llm.complete({ prompt });
|
||||
return new StopEvent(response.text);
|
||||
};
|
||||
|
||||
const jokeFlow = new Workflow<unknown, string, string>();
|
||||
jokeFlow.addStep(
|
||||
{
|
||||
inputs: [StartEvent<string>],
|
||||
outputs: [JokeEvent],
|
||||
},
|
||||
generateJoke,
|
||||
);
|
||||
jokeFlow.addStep(
|
||||
{
|
||||
inputs: [JokeEvent],
|
||||
outputs: [StopEvent<string>],
|
||||
},
|
||||
critiqueJoke,
|
||||
);
|
||||
|
||||
// Usage
|
||||
async function main() {
|
||||
const result = await jokeFlow.run("pirates");
|
||||
console.log(result.data);
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,66 +0,0 @@
|
||||
import { OpenAI } from "@llamaindex/openai";
|
||||
import {
|
||||
HandlerContext,
|
||||
StartEvent,
|
||||
StopEvent,
|
||||
Workflow,
|
||||
WorkflowEvent,
|
||||
} from "llamaindex";
|
||||
|
||||
// Create LLM instance
|
||||
const llm = new OpenAI();
|
||||
|
||||
// Create custom event types
|
||||
export class JokeEvent extends WorkflowEvent<{ joke: string }> {}
|
||||
|
||||
export class MessageEvent extends WorkflowEvent<{ msg: string }> {}
|
||||
|
||||
const generateJoke = async (context: HandlerContext, ev: StartEvent) => {
|
||||
context.sendEvent(
|
||||
new MessageEvent({ msg: `Generating a joke about: ${ev.data}` }),
|
||||
);
|
||||
const prompt = `Write your best joke about ${ev.data}.`;
|
||||
const response = await llm.complete({ prompt });
|
||||
return new JokeEvent({ joke: response.text });
|
||||
};
|
||||
|
||||
const critiqueJoke = async (context: HandlerContext, ev: JokeEvent) => {
|
||||
context.sendEvent(
|
||||
new MessageEvent({ msg: `Write a critique of this joke: ${ev.data.joke}` }),
|
||||
);
|
||||
const prompt = `Give a thorough critique of the following joke: ${ev.data.joke}`;
|
||||
const response = await llm.complete({ prompt });
|
||||
return new StopEvent(response.text);
|
||||
};
|
||||
|
||||
const jokeFlow = new Workflow();
|
||||
jokeFlow.addStep(
|
||||
{
|
||||
inputs: [StartEvent<string>],
|
||||
outputs: [JokeEvent],
|
||||
},
|
||||
generateJoke,
|
||||
);
|
||||
jokeFlow.addStep(
|
||||
{
|
||||
inputs: [JokeEvent],
|
||||
outputs: [StopEvent<string>],
|
||||
},
|
||||
critiqueJoke,
|
||||
);
|
||||
|
||||
// Usage
|
||||
async function main() {
|
||||
const run = jokeFlow.run("pirates");
|
||||
for await (const event of run) {
|
||||
if (event instanceof MessageEvent) {
|
||||
console.log("Message:");
|
||||
console.log((event as MessageEvent).data.msg);
|
||||
} else if (event instanceof StopEvent) {
|
||||
console.log("Result:");
|
||||
console.log((event as StopEvent<string>).data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,48 +0,0 @@
|
||||
import { StartEvent, StopEvent, Workflow } from "llamaindex";
|
||||
|
||||
const longRunning = async (_: unknown, ev: StartEvent<string>) => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 2000)); // Wait for 2 seconds
|
||||
return new StopEvent("We waited 2 seconds");
|
||||
};
|
||||
|
||||
async function timeout() {
|
||||
const workflow = new Workflow<unknown, string, string>({
|
||||
timeout: 1,
|
||||
});
|
||||
workflow.addStep(
|
||||
{
|
||||
inputs: [StartEvent<string>],
|
||||
outputs: [StopEvent<string>],
|
||||
},
|
||||
longRunning,
|
||||
);
|
||||
try {
|
||||
await workflow.run("Let's start");
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
}
|
||||
|
||||
async function notimeout() {
|
||||
// Increase timeout to 3 seconds - no timeout
|
||||
const workflow = new Workflow<unknown, string, string>({
|
||||
timeout: 3,
|
||||
});
|
||||
workflow.addStep(
|
||||
{
|
||||
inputs: [StartEvent<string>],
|
||||
outputs: [StopEvent<string>],
|
||||
},
|
||||
longRunning,
|
||||
);
|
||||
const result = await workflow.run("Let's start");
|
||||
console.log(result.data);
|
||||
}
|
||||
|
||||
async function main() {
|
||||
await timeout();
|
||||
console.log("---");
|
||||
await notimeout();
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,73 +0,0 @@
|
||||
import { OpenAI } from "@llamaindex/openai";
|
||||
import { StartEvent, StopEvent, Workflow, WorkflowEvent } from "llamaindex";
|
||||
|
||||
// Create LLM instance
|
||||
const llm = new OpenAI();
|
||||
|
||||
// Create a custom event type
|
||||
export class JokeEvent extends WorkflowEvent<{ joke: string }> {}
|
||||
|
||||
const generateJoke = async (_: unknown, ev: StartEvent<string>) => {
|
||||
const prompt = `Write your best joke about ${ev.data}.`;
|
||||
const response = await llm.complete({ prompt });
|
||||
return new JokeEvent({ joke: response.text });
|
||||
};
|
||||
|
||||
const critiqueJoke = async (_: unknown, ev: JokeEvent) => {
|
||||
const prompt = `Give a thorough critique of the following joke: ${ev.data.joke}`;
|
||||
const response = await llm.complete({ prompt });
|
||||
return new StopEvent(response.text);
|
||||
};
|
||||
|
||||
async function validateFails() {
|
||||
try {
|
||||
const jokeFlow = new Workflow();
|
||||
jokeFlow.addStep(
|
||||
{
|
||||
inputs: [StartEvent<string>],
|
||||
outputs: [StopEvent<string>],
|
||||
},
|
||||
// @ts-expect-error outputs should be JokeEvent
|
||||
generateJoke,
|
||||
);
|
||||
jokeFlow.addStep(
|
||||
{
|
||||
inputs: [JokeEvent],
|
||||
outputs: [StopEvent],
|
||||
},
|
||||
critiqueJoke,
|
||||
);
|
||||
await jokeFlow.run("pirates").strict();
|
||||
} catch (e) {
|
||||
console.error("Validation failed:", e);
|
||||
}
|
||||
}
|
||||
|
||||
async function validate() {
|
||||
const jokeFlow = new Workflow();
|
||||
jokeFlow.addStep(
|
||||
{
|
||||
inputs: [StartEvent<string>],
|
||||
outputs: [JokeEvent],
|
||||
},
|
||||
generateJoke,
|
||||
);
|
||||
jokeFlow.addStep(
|
||||
{
|
||||
inputs: [JokeEvent],
|
||||
outputs: [StopEvent<string>],
|
||||
},
|
||||
critiqueJoke,
|
||||
);
|
||||
const result = await jokeFlow.run("pirates").strict();
|
||||
console.log(result.data);
|
||||
}
|
||||
|
||||
// Usage
|
||||
async function main() {
|
||||
await validateFails();
|
||||
console.log("---");
|
||||
await validate();
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,5 +1,11 @@
|
||||
# @llamaindex/server
|
||||
|
||||
## 0.1.6
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 82d4b46: feat: re-add supports for artifacts
|
||||
|
||||
## 0.1.5
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -1,149 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { ChatSection as ChatSectionUI } from "@llamaindex/chat-ui";
|
||||
import "@llamaindex/chat-ui/styles/markdown.css";
|
||||
import "@llamaindex/chat-ui/styles/pdf.css";
|
||||
import { useChat } from "ai/react";
|
||||
import { Sparkles, Star } from "lucide-react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { RenderingErrors } from "./rendering-errors";
|
||||
import { Button } from "./ui/button";
|
||||
import CustomChatInput from "./ui/chat/chat-input";
|
||||
import CustomChatMessages from "./ui/chat/chat-messages";
|
||||
import { fetchComponentDefinitions } from "./ui/chat/custom/events/loader";
|
||||
import { ComponentDef } from "./ui/chat/custom/events/types";
|
||||
import { getConfig } from "./ui/lib/utils";
|
||||
|
||||
export default function ChatSection() {
|
||||
const [componentDefs, setComponentDefs] = useState<ComponentDef[]>([]);
|
||||
const [errors, setErrors] = useState<string[]>([]); // contain all errors when compiling with Babel and runtime
|
||||
|
||||
const appendError = (error: string) => {
|
||||
setErrors((prev) => [...prev, error]);
|
||||
};
|
||||
|
||||
const uniqueErrors = useMemo(() => {
|
||||
return Array.from(new Set(errors));
|
||||
}, [errors]);
|
||||
|
||||
// fetch component definitions and use Babel to tranform JSX code to JS code
|
||||
// this is triggered only once when the page is initialised
|
||||
useEffect(() => {
|
||||
fetchComponentDefinitions().then(({ components, errors }) => {
|
||||
setComponentDefs(components);
|
||||
if (errors.length > 0) {
|
||||
setErrors((prev) => [...prev, ...errors]);
|
||||
}
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handler = useChat({
|
||||
api: getConfig("CHAT_API"),
|
||||
onError: (error: unknown) => {
|
||||
if (!(error instanceof Error)) throw error;
|
||||
let errorMessage: string;
|
||||
try {
|
||||
errorMessage = JSON.parse(error.message).detail;
|
||||
} catch (e) {
|
||||
errorMessage = error.message;
|
||||
}
|
||||
alert(errorMessage);
|
||||
},
|
||||
experimental_throttle: 100,
|
||||
});
|
||||
return (
|
||||
<>
|
||||
<div className="grid h-screen w-screen grid-cols-4 gap-4 overflow-hidden">
|
||||
<div className="col-span-1">
|
||||
<div className="flex flex-col gap-8 p-2 pl-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<Sparkles className="size-4" />
|
||||
<h1 className="font-semibold">{getConfig("APP_TITLE")}</h1>
|
||||
</div>
|
||||
<RenderingErrors
|
||||
uniqueErrors={uniqueErrors}
|
||||
clearErrors={() => setErrors([])}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="col-span-2 h-full min-h-0">
|
||||
<ChatSectionUI handler={handler} className="p-0">
|
||||
<CustomChatMessages
|
||||
componentDefs={componentDefs}
|
||||
appendError={appendError}
|
||||
/>
|
||||
<CustomChatInput />
|
||||
</ChatSectionUI>
|
||||
</div>
|
||||
<div className="col-span-1">
|
||||
<LlamaIndexLinks />
|
||||
</div>
|
||||
</div>
|
||||
<TailwindCDNInjection />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function LlamaIndexLinks() {
|
||||
return (
|
||||
<div className="flex items-center justify-end gap-4 p-2 pr-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<a
|
||||
href="https://www.llamaindex.ai/"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-sm text-gray-600 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200"
|
||||
>
|
||||
Built by LlamaIndex
|
||||
</a>
|
||||
<img
|
||||
className="h-[24px] w-[24px] rounded-sm"
|
||||
src="/llama.png"
|
||||
alt="Llama Logo"
|
||||
/>
|
||||
</div>
|
||||
<a
|
||||
href="https://github.com/run-llama/LlamaIndexTS"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Button variant="outline" size="sm">
|
||||
<Star className="mr-2 size-4" />
|
||||
Star on GitHub
|
||||
</Button>
|
||||
</a>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The default border color has changed to `currentColor` in Tailwind CSS v4,
|
||||
* so adding these compatibility styles to make sure everything still
|
||||
* looks the same as it did with Tailwind CSS v3.
|
||||
*/
|
||||
const tailwindConfig = `
|
||||
@import "tailwindcss";
|
||||
|
||||
@layer base {
|
||||
*,
|
||||
::after,
|
||||
::before,
|
||||
::backdrop,
|
||||
::file-selector-button {
|
||||
border-color: var(--color-gray-200, currentColor);
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
function TailwindCDNInjection() {
|
||||
if (!getConfig("COMPONENTS_API")) return null;
|
||||
return (
|
||||
<>
|
||||
<script
|
||||
async
|
||||
src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"
|
||||
></script>
|
||||
<style type="text/tailwindcss">{tailwindConfig}</style>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
"use client";
|
||||
|
||||
import { ChatCanvas, useChatCanvas } from "@llamaindex/chat-ui";
|
||||
import { ResizableHandle, ResizablePanel } from "../../resizable";
|
||||
import { CodeArtifactRenderer } from "./preview";
|
||||
|
||||
export function ChatCanvasPanel() {
|
||||
const { displayedArtifact, isCanvasOpen } = useChatCanvas();
|
||||
if (!displayedArtifact || !isCanvasOpen) return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
<ResizableHandle withHandle />
|
||||
<ResizablePanel defaultSize={60} minSize={50}>
|
||||
<ChatCanvas className="w-full">
|
||||
<ChatCanvas.CodeArtifact
|
||||
tabs={{ preview: <CodeArtifactRenderer /> }}
|
||||
/>
|
||||
<ChatCanvas.DocumentArtifact />
|
||||
</ChatCanvas>
|
||||
</ResizablePanel>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
"use client";
|
||||
|
||||
import { CodeArtifact, useChatCanvas } from "@llamaindex/chat-ui";
|
||||
import { Loader2, WandSparkles } from "lucide-react";
|
||||
import React, { FunctionComponent, useEffect, useState } from "react";
|
||||
import {
|
||||
Accordion,
|
||||
AccordionContent,
|
||||
AccordionItem,
|
||||
AccordionTrigger,
|
||||
} from "../../accordion";
|
||||
import { buttonVariants } from "../../button";
|
||||
import { cn } from "../../lib/utils";
|
||||
import { DynamicComponentErrorBoundary } from "../custom/events/error-boundary";
|
||||
import { parseComponent } from "../custom/events/loader";
|
||||
|
||||
const SUPPORTED_FRONTEND_PREVIEW = [
|
||||
"js",
|
||||
"ts",
|
||||
"jsx",
|
||||
"tsx",
|
||||
"javascript",
|
||||
"typescript",
|
||||
];
|
||||
|
||||
export function CodeArtifactRenderer() {
|
||||
const { displayedArtifact } = useChatCanvas();
|
||||
|
||||
if (displayedArtifact?.type !== "code") return null;
|
||||
const codeArtifact = displayedArtifact as CodeArtifact;
|
||||
|
||||
if (!SUPPORTED_FRONTEND_PREVIEW.includes(codeArtifact.data.language)) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center gap-2">
|
||||
<p className="text-sm text-gray-500">
|
||||
Preview is not supported for this language
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return <CodeArtifactRendererComp artifact={codeArtifact} />;
|
||||
}
|
||||
|
||||
function CodeArtifactRendererComp({ artifact }: { artifact: CodeArtifact }) {
|
||||
const { appendErrors } = useChatCanvas();
|
||||
const [isRendering, setIsRendering] = useState(true);
|
||||
const [component, setComponent] = useState<FunctionComponent | null>(null);
|
||||
|
||||
const {
|
||||
data: { code, file_name },
|
||||
} = artifact;
|
||||
|
||||
useEffect(() => {
|
||||
const renderComponent = async () => {
|
||||
setIsRendering(true);
|
||||
const { component: parsedComponent, error } = await parseComponent(
|
||||
code,
|
||||
file_name,
|
||||
);
|
||||
|
||||
if (error) {
|
||||
setComponent(null);
|
||||
appendErrors(artifact, [error]);
|
||||
} else {
|
||||
setComponent(() => parsedComponent);
|
||||
}
|
||||
|
||||
setIsRendering(false);
|
||||
};
|
||||
|
||||
renderComponent();
|
||||
}, [artifact]);
|
||||
|
||||
if (isRendering) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center gap-2">
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
<p className="text-sm text-gray-500">Rendering Artifact...</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!component) {
|
||||
return <CodeErrors artifact={artifact} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<DynamicComponentErrorBoundary
|
||||
onError={(error) => appendErrors(artifact, [error])}
|
||||
>
|
||||
{React.createElement(component)}
|
||||
</DynamicComponentErrorBoundary>
|
||||
);
|
||||
}
|
||||
|
||||
function CodeErrors({ artifact }: { artifact: CodeArtifact }) {
|
||||
const { getCodeErrors, fixCodeErrors } = useChatCanvas();
|
||||
const uniqueErrors = getCodeErrors(artifact);
|
||||
|
||||
if (uniqueErrors.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-10 px-10 pt-10">
|
||||
<p className="text-center text-sm text-gray-500">
|
||||
Error when rendering code, please check the details and try fixing them.
|
||||
</p>
|
||||
<Accordion
|
||||
type="single"
|
||||
defaultValue="errors"
|
||||
collapsible
|
||||
className="w-full rounded-xl border border-gray-100 bg-white shadow-md"
|
||||
>
|
||||
<AccordionItem value="errors" className="border-none px-4">
|
||||
<AccordionTrigger className="py-2 hover:no-underline">
|
||||
<div className="flex flex-1 items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-muted-foreground font-bold">
|
||||
Rendering errors
|
||||
</span>
|
||||
<span className="inline-flex h-5 w-5 items-center justify-center rounded-full bg-yellow-500 text-xs text-white">
|
||||
{uniqueErrors.length}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<div
|
||||
className={cn(
|
||||
buttonVariants({ variant: "default", size: "sm" }),
|
||||
"mr-2 h-8 cursor-pointer bg-gradient-to-r from-blue-500 to-purple-500 text-white hover:from-blue-600 hover:to-purple-600",
|
||||
)}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
fixCodeErrors(artifact);
|
||||
}}
|
||||
>
|
||||
<WandSparkles className="mr-2 h-4 w-4" />
|
||||
<span>Fix errors</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="pb-4">
|
||||
<div className="space-y-2">
|
||||
{uniqueErrors.map((error, index) => (
|
||||
<p key={index} className="text-muted-foreground text-sm">
|
||||
{error}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
"use client";
|
||||
|
||||
import { Sparkles, Star } from "lucide-react";
|
||||
import { Button } from "../button";
|
||||
import { getConfig } from "../lib/utils";
|
||||
|
||||
export function ChatHeader() {
|
||||
return (
|
||||
<div className="flex items-center justify-between px-4 pt-2">
|
||||
<ChatAppTitle />
|
||||
<LlamaIndexLinks />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ChatAppTitle() {
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<Sparkles className="size-4" />
|
||||
<h1 className="font-semibold">{getConfig("APP_TITLE")}</h1>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function LlamaIndexLinks() {
|
||||
return (
|
||||
<div className="flex items-center justify-end gap-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<a
|
||||
href="https://www.llamaindex.ai/"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-sm text-gray-600 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200"
|
||||
>
|
||||
Built by LlamaIndex
|
||||
</a>
|
||||
<img
|
||||
className="h-[24px] w-[24px] rounded-sm"
|
||||
src="/llama.png"
|
||||
alt="Llama Logo"
|
||||
/>
|
||||
</div>
|
||||
<a
|
||||
href="https://github.com/run-llama/LlamaIndexTS"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Button variant="outline" size="sm">
|
||||
<Star className="mr-2 size-4" />
|
||||
Star on GitHub
|
||||
</Button>
|
||||
</a>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* The default border color has changed to `currentColor` in Tailwind CSS v4,
|
||||
* so adding these compatibility styles to make sure everything still
|
||||
* looks the same as it did with Tailwind CSS v3.
|
||||
*/
|
||||
const tailwindConfig = `
|
||||
@import "tailwindcss";
|
||||
|
||||
@layer base {
|
||||
*,
|
||||
::after,
|
||||
::before,
|
||||
::backdrop,
|
||||
::file-selector-button {
|
||||
border-color: var(--color-gray-200, currentColor);
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export function ChatInjection() {
|
||||
return (
|
||||
<>
|
||||
<script
|
||||
async
|
||||
src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"
|
||||
></script>
|
||||
<style type="text/tailwindcss">{tailwindConfig}</style>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -19,6 +19,7 @@ export function ChatMessageContent({
|
||||
<ToolAnnotations />
|
||||
<ChatMessage.Content.Image />
|
||||
<DynamicEvents componentDefs={componentDefs} appendError={appendError} />
|
||||
<ChatMessage.Content.Artifact />
|
||||
<ChatMessage.Content.Markdown />
|
||||
<ChatMessage.Content.DocumentFile />
|
||||
<ChatMessage.Content.Source />
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
"use client";
|
||||
|
||||
import { ChatSection as ChatUI } from "@llamaindex/chat-ui";
|
||||
import { useChat } from "ai/react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { getConfig } from "../lib/utils";
|
||||
import { ResizablePanel, ResizablePanelGroup } from "../resizable";
|
||||
import { ChatCanvasPanel } from "./canvas/panel";
|
||||
import { ChatHeader } from "./chat-header";
|
||||
import { ChatInjection } from "./chat-injection";
|
||||
import CustomChatInput from "./chat-input";
|
||||
import CustomChatMessages from "./chat-messages";
|
||||
import { DynamicEventsErrors } from "./custom/events/dynamic-events-errors";
|
||||
import { fetchComponentDefinitions } from "./custom/events/loader";
|
||||
import { ComponentDef } from "./custom/events/types";
|
||||
|
||||
export default function ChatSection() {
|
||||
const handler = useChat({
|
||||
api: getConfig("CHAT_API"),
|
||||
onError: (error: unknown) => {
|
||||
if (!(error instanceof Error)) throw error;
|
||||
let errorMessage: string;
|
||||
try {
|
||||
errorMessage = JSON.parse(error.message).detail;
|
||||
} catch (e) {
|
||||
errorMessage = error.message;
|
||||
}
|
||||
alert(errorMessage);
|
||||
},
|
||||
experimental_throttle: 100,
|
||||
});
|
||||
return (
|
||||
<>
|
||||
<div className="flex h-screen w-screen flex-col overflow-hidden">
|
||||
<ChatHeader />
|
||||
<ChatUI
|
||||
handler={handler}
|
||||
className="flex min-h-0 flex-1 flex-row justify-center gap-4 px-4 py-0"
|
||||
>
|
||||
<ResizablePanelGroup direction="horizontal">
|
||||
<ChatSectionPanel />
|
||||
<ChatCanvasPanel />
|
||||
</ResizablePanelGroup>
|
||||
</ChatUI>
|
||||
</div>
|
||||
<ChatInjection />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function ChatSectionPanel() {
|
||||
const [componentDefs, setComponentDefs] = useState<ComponentDef[]>([]);
|
||||
const [dynamicEventsErrors, setDynamicEventsErrors] = useState<string[]>([]); // contain all errors when rendering dynamic events from componentDir
|
||||
|
||||
const appendError = (error: string) => {
|
||||
setDynamicEventsErrors((prev) => [...prev, error]);
|
||||
};
|
||||
|
||||
const uniqueErrors = useMemo(() => {
|
||||
return Array.from(new Set(dynamicEventsErrors));
|
||||
}, [dynamicEventsErrors]);
|
||||
|
||||
// fetch component definitions and use Babel to tranform JSX code to JS code
|
||||
// this is triggered only once when the page is initialised
|
||||
useEffect(() => {
|
||||
fetchComponentDefinitions().then(({ components, errors }) => {
|
||||
setComponentDefs(components);
|
||||
if (errors.length > 0) {
|
||||
setDynamicEventsErrors((prev) => [...prev, ...errors]);
|
||||
}
|
||||
});
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<ResizablePanel defaultSize={40} minSize={30} className="max-w-1/2 mx-auto">
|
||||
<div className="flex h-full min-w-0 flex-1 flex-col gap-4">
|
||||
<DynamicEventsErrors
|
||||
errors={uniqueErrors}
|
||||
clearErrors={() => setDynamicEventsErrors([])}
|
||||
/>
|
||||
<CustomChatMessages
|
||||
componentDefs={componentDefs}
|
||||
appendError={appendError}
|
||||
/>
|
||||
<CustomChatInput />
|
||||
</div>
|
||||
</ResizablePanel>
|
||||
);
|
||||
}
|
||||
+10
-10
@@ -8,18 +8,18 @@ import {
|
||||
AccordionContent,
|
||||
AccordionItem,
|
||||
AccordionTrigger,
|
||||
} from "./ui/accordion";
|
||||
import { buttonVariants } from "./ui/button";
|
||||
import { cn } from "./ui/lib/utils";
|
||||
} from "../../../accordion";
|
||||
import { buttonVariants } from "../../../button";
|
||||
import { cn } from "../../../lib/utils";
|
||||
|
||||
export function RenderingErrors({
|
||||
uniqueErrors,
|
||||
export function DynamicEventsErrors({
|
||||
errors,
|
||||
clearErrors,
|
||||
}: {
|
||||
uniqueErrors: string[];
|
||||
errors: string[];
|
||||
clearErrors: () => void;
|
||||
}) {
|
||||
if (uniqueErrors.length === 0) return null;
|
||||
if (errors.length === 0) return null;
|
||||
return (
|
||||
<Accordion
|
||||
type="single"
|
||||
@@ -32,10 +32,10 @@ export function RenderingErrors({
|
||||
<div className="flex flex-1 items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-muted-foreground font-bold">
|
||||
Rendering errors
|
||||
Errors when rendering dynamic events from components directory
|
||||
</span>
|
||||
<span className="inline-flex h-5 w-5 items-center justify-center rounded-full bg-yellow-500 text-xs text-white">
|
||||
{uniqueErrors.length}
|
||||
{errors.length}
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
@@ -52,7 +52,7 @@ export function RenderingErrors({
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="pb-4">
|
||||
<div className="space-y-2">
|
||||
{uniqueErrors.map((error, index) => (
|
||||
{errors.map((error, index) => (
|
||||
<p key={index} className="text-muted-foreground text-sm">
|
||||
{error}
|
||||
</p>
|
||||
@@ -122,7 +122,7 @@ export async function parseImports(code: string) {
|
||||
const importPromises = imports.map(async ({ name, source }) => {
|
||||
if (!(source in SOURCE_MAP)) {
|
||||
throw new Error(
|
||||
`Fail to import ${name} from ${source}. Reason: Module not found. \nCurrently we only support importing UI components from Shadcn components, widgets from "llamaindex/chat-ui/widgets" and icons from "lucide-react". See https://ts.llamaindex.ai/docs/llamaindex/modules/ui/llamaindex-server for more information.`,
|
||||
`Fail to import ${name} from ${source}. Reason: Module not found. \nCurrently we only support importing UI components from Shadcn components, widgets from "llamaindex/chat-ui/widgets" and icons from "lucide-react"`,
|
||||
);
|
||||
}
|
||||
try {
|
||||
|
||||
@@ -2,9 +2,10 @@
|
||||
"use client";
|
||||
|
||||
import * as Babel from "@babel/standalone";
|
||||
import { FunctionComponent } from "react";
|
||||
import { getConfig } from "../../../lib/utils";
|
||||
import { parseImports } from "./import";
|
||||
import { ComponentDef, EventRenderComponent } from "./types";
|
||||
import { ComponentDef } from "./types";
|
||||
|
||||
export type SourceComponentDef = {
|
||||
type: string;
|
||||
@@ -17,11 +18,10 @@ export async function fetchComponentDefinitions(): Promise<{
|
||||
errors: string[];
|
||||
}> {
|
||||
const endpoint = getConfig("COMPONENTS_API");
|
||||
if (!endpoint)
|
||||
return {
|
||||
components: [],
|
||||
errors: ["/api/components endpoint is not defined in config"],
|
||||
};
|
||||
if (!endpoint) {
|
||||
console.warn("/api/components endpoint is not defined in config");
|
||||
return { components: [], errors: [] };
|
||||
}
|
||||
|
||||
const response = await fetch(endpoint);
|
||||
const components = (await response.json()) as SourceComponentDef[];
|
||||
@@ -59,10 +59,10 @@ export async function fetchComponentDefinitions(): Promise<{
|
||||
}
|
||||
|
||||
// create React component from code
|
||||
async function parseComponent(
|
||||
export async function parseComponent(
|
||||
code: string,
|
||||
filename: string,
|
||||
): Promise<{ component: EventRenderComponent | null; error?: string }> {
|
||||
): Promise<{ component: FunctionComponent<any> | null; error?: string }> {
|
||||
try {
|
||||
const [transpiledCode, resolvedImports] = await Promise.all([
|
||||
transpileCode(code, filename),
|
||||
@@ -119,7 +119,7 @@ async function createComponentFromCode(
|
||||
transpiledCode: string,
|
||||
importMap: Record<string, any>,
|
||||
componentName: string | null = "Component",
|
||||
): Promise<EventRenderComponent | null> {
|
||||
): Promise<FunctionComponent<any> | null> {
|
||||
const argNames = Object.keys(importMap); // e.g., ["React", "Button", "Badge"]
|
||||
const argValues = Object.values(importMap); // list of corresponding modules
|
||||
|
||||
|
||||
@@ -5,5 +5,3 @@ export type ComponentDef = {
|
||||
type: string; // eg. deep_research_event
|
||||
comp: FunctionComponent<{ events: JSONValue[] }>;
|
||||
};
|
||||
|
||||
export type EventRenderComponent = FunctionComponent<{ events: JSONValue[] }>;
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import type { Metadata } from "next";
|
||||
import { Inter } from "next/font/google";
|
||||
|
||||
import "@llamaindex/chat-ui/styles/markdown.css";
|
||||
import "@llamaindex/chat-ui/styles/pdf.css";
|
||||
import "./globals.css";
|
||||
|
||||
const inter = Inter({ subsets: ["latin"] });
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import { Loader2 } from "lucide-react";
|
||||
import dynamic from "next/dynamic";
|
||||
|
||||
const ChatSection = dynamic(() => import("./components/chat-section"), {
|
||||
const ChatSection = dynamic(() => import("./components/ui/chat/chat-section"), {
|
||||
ssr: false,
|
||||
loading: () => (
|
||||
<div className="flex h-full w-full items-center justify-center">
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@llamaindex/server",
|
||||
"description": "LlamaIndex Server",
|
||||
"version": "0.1.5",
|
||||
"version": "0.1.6",
|
||||
"type": "module",
|
||||
"main": "./dist/index.cjs",
|
||||
"module": "./dist/index.js",
|
||||
@@ -62,7 +62,7 @@
|
||||
"@babel/types": "^7.27.0",
|
||||
"@hookform/resolvers": "^5.0.1",
|
||||
"@llama-flow/core": "^0.3.4",
|
||||
"@llamaindex/chat-ui": "0.4.0",
|
||||
"@llamaindex/chat-ui": "0.4.1",
|
||||
"@llamaindex/env": "workspace:*",
|
||||
"@radix-ui/react-accordion": "^1.2.3",
|
||||
"@radix-ui/react-alert-dialog": "^1.1.7",
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { randomUUID } from "@llamaindex/env";
|
||||
import type { Message } from "ai";
|
||||
import {
|
||||
MetadataMode,
|
||||
WorkflowEvent,
|
||||
type Metadata,
|
||||
type NodeWithScore,
|
||||
} from "llamaindex";
|
||||
import { z } from "zod";
|
||||
|
||||
// Events that appended to stream as annotations
|
||||
export type SourceEventNode = {
|
||||
@@ -88,3 +90,128 @@ export function toAgentRunEvent(input: {
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export type ArtifactType = "code" | "document";
|
||||
|
||||
export type Artifact<T = unknown> = {
|
||||
created_at: number;
|
||||
type: ArtifactType;
|
||||
data: T;
|
||||
};
|
||||
|
||||
export type CodeArtifactData = {
|
||||
file_name: string;
|
||||
code: string;
|
||||
language: string;
|
||||
};
|
||||
|
||||
export type DocumentArtifactData = {
|
||||
title: string;
|
||||
content: string;
|
||||
type: string; // markdown, html,...
|
||||
};
|
||||
|
||||
export type CodeArtifact = Artifact<CodeArtifactData> & {
|
||||
type: "code";
|
||||
};
|
||||
|
||||
export type DocumentArtifact = Artifact<DocumentArtifactData> & {
|
||||
type: "document";
|
||||
};
|
||||
|
||||
export class ArtifactEvent extends WorkflowEvent<{
|
||||
type: "artifact";
|
||||
data: Artifact;
|
||||
}> {}
|
||||
|
||||
export const codeArtifactSchema = z.object({
|
||||
type: z.literal("code"),
|
||||
data: z.object({
|
||||
file_name: z.string(),
|
||||
code: z.string(),
|
||||
language: z.string(),
|
||||
}),
|
||||
created_at: z.number(),
|
||||
});
|
||||
|
||||
export const documentArtifactSchema = z.object({
|
||||
type: z.literal("document"),
|
||||
data: z.object({
|
||||
title: z.string(),
|
||||
content: z.string(),
|
||||
type: z.string(),
|
||||
}),
|
||||
created_at: z.number(),
|
||||
});
|
||||
|
||||
export const artifactSchema = z.union([
|
||||
codeArtifactSchema,
|
||||
documentArtifactSchema,
|
||||
]);
|
||||
|
||||
export const artifactAnnotationSchema = z.object({
|
||||
type: z.literal("artifact"),
|
||||
data: artifactSchema,
|
||||
});
|
||||
|
||||
export function extractAllArtifacts(messages: Message[]): Artifact[] {
|
||||
const allArtifacts: Artifact[] = [];
|
||||
|
||||
for (const message of messages) {
|
||||
const artifacts =
|
||||
message.annotations
|
||||
?.filter(
|
||||
(annotation) =>
|
||||
artifactAnnotationSchema.safeParse(annotation).success,
|
||||
)
|
||||
.map((artifact) => artifact as Artifact) ?? [];
|
||||
|
||||
allArtifacts.push(...artifacts);
|
||||
}
|
||||
|
||||
return allArtifacts;
|
||||
}
|
||||
|
||||
export function extractLastArtifact(
|
||||
requestBody: unknown,
|
||||
type: "code",
|
||||
): CodeArtifact | undefined;
|
||||
|
||||
export function extractLastArtifact(
|
||||
requestBody: unknown,
|
||||
type: "document",
|
||||
): DocumentArtifact | undefined;
|
||||
|
||||
export function extractLastArtifact(
|
||||
requestBody: unknown,
|
||||
type?: ArtifactType,
|
||||
): Artifact | undefined;
|
||||
|
||||
export function extractLastArtifact(
|
||||
requestBody: unknown,
|
||||
type?: ArtifactType,
|
||||
): CodeArtifact | DocumentArtifact | Artifact | undefined {
|
||||
const { messages } = (requestBody as { messages?: Message[] }) ?? {};
|
||||
if (!messages) return undefined;
|
||||
|
||||
const artifacts = extractAllArtifacts(messages);
|
||||
if (!artifacts.length) return undefined;
|
||||
|
||||
if (type) {
|
||||
const lastArtifact = artifacts
|
||||
.reverse()
|
||||
.find((artifact) => artifact.type === type);
|
||||
|
||||
if (!lastArtifact) return undefined;
|
||||
|
||||
if (type === "code") {
|
||||
return lastArtifact as CodeArtifact;
|
||||
}
|
||||
|
||||
if (type === "document") {
|
||||
return lastArtifact as DocumentArtifact;
|
||||
}
|
||||
}
|
||||
|
||||
return artifacts[artifacts.length - 1];
|
||||
}
|
||||
|
||||
@@ -29,7 +29,10 @@ export const handleChat = async (
|
||||
|
||||
const stream = await runWorkflow(workflow, {
|
||||
userInput: lastMessage.content,
|
||||
chatHistory: messages.slice(0, -1) as ChatMessage[],
|
||||
chatHistory: messages.slice(0, -1).map((message) => ({
|
||||
content: message.content,
|
||||
role: message.role as ChatMessage["role"],
|
||||
})),
|
||||
});
|
||||
|
||||
pipeStreamToResponse(res, stream);
|
||||
|
||||
@@ -1,5 +1,17 @@
|
||||
# @llamaindex/tools
|
||||
|
||||
## 0.0.7
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 82d4b46: feat: re-add supports for artifacts
|
||||
|
||||
## 0.0.6
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 294f502: Support SSE for MCP tools adapter
|
||||
|
||||
## 0.0.5
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@llamaindex/tools",
|
||||
"description": "LlamaIndex Tools",
|
||||
"version": "0.0.5",
|
||||
"version": "0.0.7",
|
||||
"type": "module",
|
||||
"main": "./dist/index.cjs",
|
||||
"module": "./dist/index.js",
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
export * from "./tools/code-artifact-generator";
|
||||
export * from "./tools/code-generator";
|
||||
export * from "./tools/document-artifact-generator";
|
||||
export * from "./tools/document-generator";
|
||||
export * from "./tools/duckduckgo";
|
||||
export * from "./tools/form-filling";
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import { Settings, type JSONValue } from "@llamaindex/core/global";
|
||||
import type { ChatMessage, LLM } from "@llamaindex/core/llms";
|
||||
import { tool } from "@llamaindex/core/tools";
|
||||
import { z } from "zod";
|
||||
|
||||
const CODE_ARTIFACT_GENERATION_PROMPT = `You are a highly skilled software engineer. Your task is to generate a code artifact based on the user's request.
|
||||
Follow these instructions exactly:
|
||||
1. Carefully read the user's requirements. If any details are ambiguous or missing, make reasonable assumptions and clearly reflect those in your output.
|
||||
2. For code requests:
|
||||
- If the user does not specify a framework or language, default to a React component using the Next.js framework.
|
||||
- For Next.js, use Shadcn UI components, Typescript, @types/node, @types/react, @types/react-dom, PostCSS, and TailwindCSS.
|
||||
- Please don't use inline styles or any external libraries.
|
||||
- For Shadcn ui components, you can import them like this: import { Button } from "@/components/ui/button"
|
||||
- Ensure the code is idiomatic, production-ready, and includes necessary imports.
|
||||
- Only generate code relevant to the user's request—do not add extra boilerplate.
|
||||
3. Return ONLY valid, parseable JSON in the following format. Do not include any explanations, markdown formatting, or code blocks around the JSON.
|
||||
|
||||
{
|
||||
"type": "code",
|
||||
"data": {
|
||||
"file_name": "filename.ext",
|
||||
"code": "your code here",
|
||||
"language": "programming language"
|
||||
}
|
||||
}
|
||||
|
||||
4. Your entire response must be valid JSON matching this format exactly. Do not include any explanations, markdown formatting, or code blocks around the JSON.
|
||||
---
|
||||
EXAMPLE
|
||||
{
|
||||
"type": "code",
|
||||
"data": {
|
||||
"file_name": "MyComponent.tsx",
|
||||
"code": "import React from 'react';\nexport default function MyComponent() { return <div>Hello World</div>; }",
|
||||
"language": "typescript"
|
||||
}
|
||||
}`;
|
||||
|
||||
type CodeArtifact = {
|
||||
created_at: number;
|
||||
type: "code";
|
||||
data: {
|
||||
file_name: string;
|
||||
code: string;
|
||||
language: string;
|
||||
};
|
||||
};
|
||||
|
||||
export type CodeArtifactGeneratorToolOutput = CodeArtifact;
|
||||
|
||||
export const codeArtifactGenerator = ({
|
||||
llm,
|
||||
lastArtifact,
|
||||
}: {
|
||||
llm?: LLM;
|
||||
lastArtifact?: CodeArtifact;
|
||||
}) => {
|
||||
return tool({
|
||||
name: "code_artifact_generator",
|
||||
description: "Generate a code artifact based on the input.",
|
||||
parameters: z.object({
|
||||
requirement: z
|
||||
.string()
|
||||
.describe("The description of the code artifact you want to build."),
|
||||
}),
|
||||
execute: async ({ requirement }) => {
|
||||
const artifact = await generateCodeArtifact(
|
||||
requirement,
|
||||
lastArtifact,
|
||||
llm,
|
||||
);
|
||||
return artifact as JSONValue;
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
async function generateCodeArtifact(
|
||||
requirement: string,
|
||||
lastArtifact?: CodeArtifact,
|
||||
llm?: LLM,
|
||||
): Promise<CodeArtifact | null> {
|
||||
const userMessage = `
|
||||
Generate a code artifact: ${requirement}
|
||||
${lastArtifact ? `The existing content is: \n\`\`\`${lastArtifact.data.code}\`\`\`` : ""}`;
|
||||
|
||||
const messages: ChatMessage[] = [
|
||||
{ role: "system", content: CODE_ARTIFACT_GENERATION_PROMPT },
|
||||
{ role: "user", content: userMessage },
|
||||
];
|
||||
|
||||
try {
|
||||
const response = await (llm ?? Settings.llm).chat({ messages });
|
||||
const content = response.message.content.toString();
|
||||
const jsonContent = content
|
||||
.replace(/^```json\s*|\s*```$/g, "")
|
||||
.replace(/^`+|`+$/g, "")
|
||||
.trim();
|
||||
|
||||
const parsedResponse = JSON.parse(jsonContent);
|
||||
|
||||
const artifact: CodeArtifact = {
|
||||
type: "code",
|
||||
data: parsedResponse.data,
|
||||
created_at: Date.now(),
|
||||
};
|
||||
|
||||
return artifact;
|
||||
} catch (error) {
|
||||
console.error("Failed to generate code artifact", error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import { Settings, type JSONValue } from "@llamaindex/core/global";
|
||||
import type { ChatMessage, LLM } from "@llamaindex/core/llms";
|
||||
import { tool } from "@llamaindex/core/tools";
|
||||
import { z } from "zod";
|
||||
|
||||
const DOCUMENT_ARTIFACT_GENERATION_PROMPT = `You are a highly skilled content creator. Your task is to generate a document artifact based on the user's request.
|
||||
Follow these instructions exactly:
|
||||
1. Carefully read the user's requirements. If any details are ambiguous or missing, make reasonable assumptions and clearly reflect those in your output.
|
||||
2. For document requests:
|
||||
- Always generate Markdown (.md) documents.
|
||||
- Use clear structure: headings, subheadings, lists, and tables for comparisons.
|
||||
- Ensure content is concise, well-organized, and directly addresses the user's needs.
|
||||
3. Return ONLY valid, parseable JSON in the following format. Do not include any explanations, markdown formatting, or code blocks around the JSON.
|
||||
|
||||
{
|
||||
"type": "document",
|
||||
"data": {
|
||||
"title": "Document Title",
|
||||
"content": "Markdown content here",
|
||||
"type": "markdown"
|
||||
}
|
||||
}
|
||||
|
||||
4. Your entire response must be valid JSON matching this format exactly. Do not include any explanations, markdown formatting, or code blocks around the JSON.
|
||||
---
|
||||
EXAMPLE
|
||||
{
|
||||
"type": "document",
|
||||
"data": {
|
||||
"title": "Quick Start Guide",
|
||||
"content": "# Quick Start\n\nFollow these steps to begin...",
|
||||
"type": "markdown"
|
||||
}
|
||||
}`;
|
||||
|
||||
type DocumentArtifact = {
|
||||
created_at: number;
|
||||
type: "document";
|
||||
data: {
|
||||
title: string;
|
||||
content: string;
|
||||
type: string;
|
||||
};
|
||||
};
|
||||
|
||||
export type DocumentArtifactGeneratorToolOutput = DocumentArtifact;
|
||||
|
||||
export const documentArtifactGenerator = ({
|
||||
llm,
|
||||
lastArtifact,
|
||||
}: {
|
||||
llm?: LLM;
|
||||
lastArtifact?: DocumentArtifact;
|
||||
}) => {
|
||||
return tool({
|
||||
name: "document_artifact_generator",
|
||||
description: "Generate a document artifact based on the input.",
|
||||
parameters: z.object({
|
||||
requirement: z
|
||||
.string()
|
||||
.describe(
|
||||
"The description of the document artifact you want to build.",
|
||||
),
|
||||
}),
|
||||
execute: async ({ requirement }) => {
|
||||
const artifact = await generateDocumentArtifact(
|
||||
requirement,
|
||||
lastArtifact,
|
||||
llm,
|
||||
);
|
||||
return artifact as JSONValue;
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
async function generateDocumentArtifact(
|
||||
requirement: string,
|
||||
lastArtifact?: DocumentArtifact,
|
||||
llm?: LLM,
|
||||
): Promise<DocumentArtifact | null> {
|
||||
const userMessage = `
|
||||
Generate a document artifact: ${requirement}
|
||||
${lastArtifact ? `The existing content is: \n\`\`\`${lastArtifact.data.content}\`\`\`` : ""}
|
||||
`;
|
||||
|
||||
const messages: ChatMessage[] = [
|
||||
{ role: "system", content: DOCUMENT_ARTIFACT_GENERATION_PROMPT },
|
||||
{ role: "user", content: userMessage },
|
||||
];
|
||||
|
||||
try {
|
||||
const response = await (llm ?? Settings.llm).chat({ messages });
|
||||
const content = response.message.content.toString();
|
||||
const jsonContent = content
|
||||
.replace(/^```json\s*|\s*```$/g, "")
|
||||
.replace(/^`+|`+$/g, "")
|
||||
.trim();
|
||||
|
||||
const parsedResponse = JSON.parse(jsonContent);
|
||||
|
||||
const artifact: DocumentArtifact = {
|
||||
type: "document",
|
||||
data: parsedResponse.data,
|
||||
created_at: Date.now(),
|
||||
};
|
||||
|
||||
return artifact;
|
||||
} catch (error) {
|
||||
console.error("Failed to generate document artifact", error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,10 @@ import type { JSONValue } from "@llamaindex/core/global";
|
||||
import type { BaseToolWithCall } from "@llamaindex/core/llms";
|
||||
import { FunctionTool } from "@llamaindex/core/tools";
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import {
|
||||
SSEClientTransport,
|
||||
type SSEClientTransportOptions,
|
||||
} from "@modelcontextprotocol/sdk/client/sse.js";
|
||||
import {
|
||||
StdioClientTransport,
|
||||
type StdioServerParameters,
|
||||
@@ -13,7 +17,7 @@ interface ToolInput {
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
type MCPClientOptions = StdioServerParameters & {
|
||||
type MCPCommonOptions = {
|
||||
/**
|
||||
* The prefix to add to the tool name
|
||||
*/
|
||||
@@ -32,11 +36,20 @@ type MCPClientOptions = StdioServerParameters & {
|
||||
verbose?: boolean;
|
||||
};
|
||||
|
||||
type StdioMCPClientOptions = StdioServerParameters & MCPCommonOptions;
|
||||
type SSEMCPClientOptions = SSEClientTransportOptions &
|
||||
MCPCommonOptions & {
|
||||
url: string;
|
||||
};
|
||||
|
||||
type MCPClientOptions = StdioMCPClientOptions | SSEMCPClientOptions;
|
||||
|
||||
class MCPClient {
|
||||
private mcp: Client;
|
||||
private transport: StdioClientTransport | null = null;
|
||||
private transport: StdioClientTransport | SSEClientTransport | null = null;
|
||||
private verbose: boolean;
|
||||
private toolNamePrefix?: string | undefined;
|
||||
private connected: boolean = false;
|
||||
|
||||
constructor(options: MCPClientOptions) {
|
||||
this.mcp = new Client({
|
||||
@@ -46,18 +59,34 @@ class MCPClient {
|
||||
|
||||
this.verbose = options.verbose ?? false;
|
||||
this.toolNamePrefix = options.toolNamePrefix;
|
||||
this.connectToSever(options);
|
||||
if ("url" in options) {
|
||||
this.transport = new SSEClientTransport(
|
||||
new URL(options.url),
|
||||
options as SSEClientTransportOptions,
|
||||
);
|
||||
} else {
|
||||
this.transport = new StdioClientTransport(
|
||||
options as StdioServerParameters,
|
||||
);
|
||||
}
|
||||
this.connected = false;
|
||||
}
|
||||
|
||||
async connectToSever(options: StdioServerParameters) {
|
||||
async connectToSever() {
|
||||
if (this.verbose) {
|
||||
console.log("Connecting to MCP server...");
|
||||
}
|
||||
this.transport = new StdioClientTransport(options);
|
||||
if (!this.transport) {
|
||||
throw new Error("Initialized with invalid options");
|
||||
}
|
||||
await this.mcp.connect(this.transport);
|
||||
this.connected = true;
|
||||
}
|
||||
|
||||
async listTools(): Promise<Tool[]> {
|
||||
private async listTools(): Promise<Tool[]> {
|
||||
if (!this.connected) {
|
||||
await this.connectToSever();
|
||||
}
|
||||
const tools = await this.mcp.listTools();
|
||||
return tools.tools;
|
||||
}
|
||||
|
||||
Generated
+12
-6
@@ -713,6 +713,9 @@ importers:
|
||||
'@llamaindex/replicate':
|
||||
specifier: ^0.0.44
|
||||
version: link:../packages/providers/replicate
|
||||
'@llamaindex/server':
|
||||
specifier: ^0.1.6
|
||||
version: link:../packages/server
|
||||
'@llamaindex/supabase':
|
||||
specifier: ^0.1.1
|
||||
version: link:../packages/providers/storage/supabase
|
||||
@@ -720,7 +723,7 @@ importers:
|
||||
specifier: ^0.0.12
|
||||
version: link:../packages/providers/together
|
||||
'@llamaindex/tools':
|
||||
specifier: ^0.0.5
|
||||
specifier: ^0.0.7
|
||||
version: link:../packages/tools
|
||||
'@llamaindex/upstash':
|
||||
specifier: ^0.0.16
|
||||
@@ -1701,8 +1704,8 @@ importers:
|
||||
specifier: ^0.3.4
|
||||
version: 0.3.4(@modelcontextprotocol/sdk@1.9.0)(hono@4.7.7)(next@15.3.0(@opentelemetry/api@1.9.0)(react-dom@19.1.0(react@19.1.0))(react@19.1.0))(p-retry@6.2.1)(zod@3.24.2)
|
||||
'@llamaindex/chat-ui':
|
||||
specifier: 0.4.0
|
||||
version: 0.4.0(@types/react-dom@19.0.4(@types/react@19.0.10))(@types/react@19.0.10)(react-dom@19.1.0(react@19.1.0))(react@19.1.0)
|
||||
specifier: 0.4.1
|
||||
version: 0.4.1(@types/react-dom@19.0.4(@types/react@19.0.10))(@types/react@19.0.10)(react-dom@19.1.0(react@19.1.0))(react@19.1.0)
|
||||
'@llamaindex/env':
|
||||
specifier: workspace:*
|
||||
version: link:../env
|
||||
@@ -3866,8 +3869,8 @@ packages:
|
||||
peerDependencies:
|
||||
react: ^18.2.0 || ^19.0.0 || ^19.0.0-rc
|
||||
|
||||
'@llamaindex/chat-ui@0.4.0':
|
||||
resolution: {integrity: sha512-u9jOUuyKPDFnJsorfH8oIE0UVO+zlabbD8lgTFbN37XUdYFFG4rteEYwUWc/n4/h/GjnFcTfxpiyWmiwTKzicw==}
|
||||
'@llamaindex/chat-ui@0.4.1':
|
||||
resolution: {integrity: sha512-lRPsnpPe2mBJJVlKEpIKSmr5ofCGVRP7U21CfSCFaFVA/V81BaZZ/gyt2G8+vzXmTWGqRYJGBNHcsGVPx0G7Mw==}
|
||||
peerDependencies:
|
||||
react: ^18.2.0 || ^19.0.0 || ^19.0.0-rc
|
||||
|
||||
@@ -3904,6 +3907,7 @@ packages:
|
||||
|
||||
'@mixedbread-ai/sdk@2.2.11':
|
||||
resolution: {integrity: sha512-NJiY6BVPR+s/DTzUPQS1Pv418trOmII/8hftmIqxXlYaKbIrgJimQfwCW9M6Y21YPcMA8zTQGYZHm4IWlMjIQw==}
|
||||
deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.
|
||||
|
||||
'@modelcontextprotocol/sdk@0.5.0':
|
||||
resolution: {integrity: sha512-RXgulUX6ewvxjAG0kOpLMEdXXWkzWgaoCGaA2CwNW7cQCIphjpJhjpHSiaPdVCnisjRF/0Cm9KWHUuIoeiAblQ==}
|
||||
@@ -15989,12 +15993,14 @@ snapshots:
|
||||
- react-dom
|
||||
- supports-color
|
||||
|
||||
'@llamaindex/chat-ui@0.4.0(@types/react-dom@19.0.4(@types/react@19.0.10))(@types/react@19.0.10)(react-dom@19.1.0(react@19.1.0))(react@19.1.0)':
|
||||
'@llamaindex/chat-ui@0.4.1(@types/react-dom@19.0.4(@types/react@19.0.10))(@types/react@19.0.10)(react-dom@19.1.0(react@19.1.0))(react@19.1.0)':
|
||||
dependencies:
|
||||
'@llamaindex/pdf-viewer': 1.3.0(@types/react@19.0.10)(react-dom@19.1.0(react@19.1.0))(react@19.1.0)
|
||||
'@radix-ui/react-accordion': 1.2.4(@types/react-dom@19.0.4(@types/react@19.0.10))(@types/react@19.0.10)(react-dom@19.1.0(react@19.1.0))(react@19.1.0)
|
||||
'@radix-ui/react-collapsible': 1.1.4(@types/react-dom@19.0.4(@types/react@19.0.10))(@types/react@19.0.10)(react-dom@19.1.0(react@19.1.0))(react@19.1.0)
|
||||
'@radix-ui/react-hover-card': 1.1.7(@types/react-dom@19.0.4(@types/react@19.0.10))(@types/react@19.0.10)(react-dom@19.1.0(react@19.1.0))(react@19.1.0)
|
||||
'@radix-ui/react-icons': 1.3.2(react@19.1.0)
|
||||
'@radix-ui/react-popover': 1.1.7(@types/react-dom@19.0.4(@types/react@19.0.10))(@types/react@19.0.10)(react-dom@19.1.0(react@19.1.0))(react@19.1.0)
|
||||
'@radix-ui/react-progress': 1.1.3(@types/react-dom@19.0.4(@types/react@19.0.10))(@types/react@19.0.10)(react-dom@19.1.0(react@19.1.0))(react@19.1.0)
|
||||
'@radix-ui/react-select': 2.1.7(@types/react-dom@19.0.4(@types/react@19.0.10))(@types/react@19.0.10)(react-dom@19.1.0(react@19.1.0))(react@19.1.0)
|
||||
'@radix-ui/react-slot': 1.2.0(@types/react@19.0.10)(react@19.1.0)
|
||||
|
||||
Reference in New Issue
Block a user