Skip to content

Commit

Permalink
[api] return response in a streaming way (#136)
Browse files Browse the repository at this point in the history
* stream the result back

* add debug hack

* increase the stream interval

* every 5 letters

* refactor

* update system message

* clean up

* Revert "add debug hack"

This reverts commit e7c0dd7.
  • Loading branch information
qizheng7 authored Jun 17, 2023
1 parent b5d2d94 commit 62bb754
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 11 deletions.
35 changes: 34 additions & 1 deletion skyagi-web/src/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,37 @@ export const checkValidity = (data: any) => {
} else {
return true;
}
};
};

export function sleep(ms: number): void {
const start = Date.now();
while (Date.now() - start < ms) {}
}

export async function getResponseStream(metadata: object, respMsg: string) {
const encoder = new TextEncoder();
const stream = new ReadableStream({
start(controller) {
for (const [key, value] of Object.entries(metadata)) {
const metaDataMsg = JSON.stringify({[key]: value});
controller.enqueue(JSON.stringify(metaDataMsg));
sleep(1000); // Sleep for 1 second
}

let totalLen = respMsg.length;
let chunkSize = 5, start = 0, end = chunkSize;
const interval = setInterval(() => {
const encodedData = encoder.encode(respMsg.slice(start, end));
controller.enqueue(encodedData);
start = end;
end = end + chunkSize >= totalLen ? totalLen : end + chunkSize;
if (start >= end) {
clearInterval(interval);
controller.close();
}
}, 1000);
},
});

return stream;
}
12 changes: 6 additions & 6 deletions skyagi-web/src/routes/api/send-conversation-message/+server.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { RequestHandler } from './$types';
import type { Config } from '@sveltejs/adapter-vercel';
import { GenerativeAgent } from '$lib/agent';
import { getResponseStream } from '$lib/utils';

// Can switch to the edge func if serverless is not necessary
export const config: Config = {
Expand Down Expand Up @@ -56,12 +57,11 @@ export const PUT = (async ({ request, locals }: { request: Request; locals: App.
await agent.addMemory(`${agent.name} observed ${newMessage} and said ${respMsg}`);

// return
const resp = {
const respMetaData = {
'success': 1,
'resp_msg': {
'if_continue': ifContinue,
'message': respMsg
}
'if_continue': ifContinue
}
return new Response(JSON.stringify(resp), { status: 200 });

const stream = await getResponseStream(respMetaData, respMsg);
return new Response(stream);
}) satisfies RequestHandler;
15 changes: 11 additions & 4 deletions skyagi-web/src/routes/api/send-system-message/+server.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { RequestHandler } from './$types';
import type { Config } from '@sveltejs/adapter-vercel';
import { checkValidity } from '$lib/utils';
import { checkValidity, getResponseStream } from '$lib/utils';
import { AIMessagePromptTemplate, HumanMessagePromptTemplate, ChatPromptTemplate, SystemMessagePromptTemplate } from "langchain/prompts"
import { LLMChain } from "langchain/chains";
import { load_llm_from_config } from '$lib/model/model';
Expand Down Expand Up @@ -89,7 +89,7 @@ export const PUT = (async ({ request, locals }: { request: Request; locals: App.
let msgResp = respChainRes.text.trim();

if (msgResp.includes('NOTHING')) {
return new Response(JSON.stringify({ 'success': 1, 'resp_msg': { 'is_valid': false, 'message': '' } }), { status: 200 });
return new Response(JSON.stringify({ 'success': 1, 'is_valid': false, 'message': '' }), { status: 200 });
}

chatMessages.push(AIMessagePromptTemplate.fromTemplate(msgResp));
Expand All @@ -111,10 +111,17 @@ export const PUT = (async ({ request, locals }: { request: Request; locals: App.
const validationResp = validationChainRes.text.trim();

if (validationResp.includes('no')) {
return new Response(JSON.stringify({ 'success': 1, 'resp_msg': { 'is_valid': false, 'message': '' } }), { status: 200 });
return new Response(JSON.stringify({ 'success': 1, 'is_valid': false, 'message': '' }), { status: 200 });
}

msgResp = msgResp.slice(msgResp.startsWith('"') ? 1 : 0, msgResp.endsWith('"') ? -1 : undefined);

return new Response(JSON.stringify({ 'success': 1, 'resp_msg': { 'is_valid': true, 'message': msgResp } }), { status: 200 });
const respMetaData = {
'success': 1,
'is_valid': true
}

const stream = await getResponseStream(respMetaData, msgResp);
return new Response(stream);

}) satisfies RequestHandler;

1 comment on commit 62bb754

@vercel
Copy link

@vercel vercel bot commented on 62bb754 Jun 17, 2023

Choose a reason for hiding this comment

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

Successfully deployed to the following URLs:

skyagi – ./

skyagi-sky-agi.vercel.app
skyagi-git-main-sky-agi.vercel.app
app.skyagi.ai
skyagi.vercel.app

Please sign in to comment.