Skip to content
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

feat: use latest llamaindex version #76

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
feat: use latest llamaindex version
  • Loading branch information
thucpn committed Feb 16, 2024
commit b94a819edbc5732f20d89d614d5f1df919b76297
22 changes: 11 additions & 11 deletions app/api/fetch/embeddings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,27 +7,27 @@ import {
Document,
MetadataMode,
SentenceSplitter,
SimpleNodeParser,
VectorStoreIndex,
getNodesFromDocument,
serviceContextFromDefaults,
} from "llamaindex";

export default async function splitAndEmbed(
document: string,
): Promise<Embedding[]> {
const nodes = getNodesFromDocument(
new Document({ text: document }),
new SentenceSplitter({
const nodeParser = new SimpleNodeParser({
textSplitter: new SentenceSplitter({
chunkSize: DATASOURCES_CHUNK_SIZE,
chunkOverlap: DATASOURCES_CHUNK_OVERLAP,
}),
);

const nodesWithEmbeddings = await VectorStoreIndex.getNodeEmbeddingResults(
nodes,
serviceContextFromDefaults(),
true,
);
});
const nodes = nodeParser.getNodesFromDocuments([
new Document({ text: document }),
]);
const index = await VectorStoreIndex.fromDocuments(nodes, {
serviceContext: serviceContextFromDefaults(),
});
const nodesWithEmbeddings = await index.getNodeEmbeddingResults(nodes);

return nodesWithEmbeddings.map((nodeWithEmbedding) => ({
text: nodeWithEmbedding.getContent(MetadataMode.NONE),
Expand Down
29 changes: 19 additions & 10 deletions app/api/llm/route.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
import {
ChatHistory,
ChatMessage,
DefaultContextGenerator,
HistoryChatEngine,
ContextChatEngine,
IndexDict,
OpenAI,
ServiceContext,
SimpleChatEngine,
SimpleChatHistory,
SummaryChatHistory,
TextNode,
VectorStoreIndex,
serviceContextFromDefaults,
Response,
} from "llamaindex";
import { NextRequest, NextResponse } from "next/server";
import { LLMConfig, MessageContent } from "@/app/client/platforms/llm";
Expand All @@ -27,7 +28,6 @@ async function createChatEngine(
datasource?: string,
embeddings?: Embedding[],
) {
let contextGenerator;
if (datasource || embeddings) {
let index;
if (embeddings) {
Expand All @@ -39,12 +39,14 @@ async function createChatEngine(
const retriever = index!.asRetriever();
retriever.similarityTopK = 5;

contextGenerator = new DefaultContextGenerator({ retriever });
return new ContextChatEngine({
chatModel: serviceContext.llm,
retriever,
});
}

return new HistoryChatEngine({
return new SimpleChatEngine({
llm: serviceContext.llm,
contextGenerator,
});
}

Expand Down Expand Up @@ -75,9 +77,10 @@ async function createIndex(
}

function createReadableStream(
stream: AsyncGenerator<string, void, unknown>,
stream: AsyncIterable<Response>,
chatHistory: ChatHistory,
) {
const it = stream[Symbol.asyncIterator]();
let responseStream = new TransformStream();
const writer = responseStream.writable.getWriter();
let aborted = false;
Expand All @@ -88,10 +91,12 @@ function createReadableStream(
const encoder = new TextEncoder();
const onNext = async () => {
try {
const { value, done } = await stream.next();
const { value, done } = await it.next();
if (aborted) return;
if (!done) {
writer.write(encoder.encode(`data: ${JSON.stringify(value)}\n\n`));
writer.write(
encoder.encode(`data: ${JSON.stringify(value.response)}\n\n`),
);
onNext();
} else {
writer.write(
Expand Down Expand Up @@ -168,7 +173,11 @@ export async function POST(request: NextRequest) {
? new SummaryChatHistory({ llm, messages })
: new SimpleChatHistory({ messages });

const stream = await chatEngine.chat(message, chatHistory, true);
const stream = await chatEngine.chat({
message,
chatHistory,
stream: true,
});
const readableStream = createReadableStream(stream, chatHistory);

return new NextResponse(readableStream, {
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
"dotenv": "^16.3.1",
"emoji-picker-react": "^4.4.12",
"encoding": "^0.1.13",
"llamaindex": "0.0.0-20231110031459",
"llamaindex": "0.1.10",
"lucide-react": "^0.277.0",
"mermaid": "^10.3.1",
"nanoid": "^5.0.2",
Expand Down
Loading