diff --git a/packages/neuri/src/index.test.ts b/packages/neuri/src/index.test.ts index fa1273e..00a78aa 100644 --- a/packages/neuri/src/index.test.ts +++ b/packages/neuri/src/index.test.ts @@ -1,8 +1,9 @@ -import { describe, expect, it } from 'vitest' +import type { Message } from '@xsai/shared-chat' +import { describe, expect, it } from 'vitest' import { object, string } from 'zod' import { agent, neuri } from '.' -import { messages, system, user } from './openai' +import { assistant, messages, system, user } from './openai' describe('neuri', async () => { it('should work', { timeout: 100000 }, async () => { @@ -37,4 +38,36 @@ describe('neuri', async () => { expect(name).contains('Neuri') }) + + it('should work with handleStateless', { timeout: 100000 }, async () => { + const n = await neuri() + .agent( + agent('consciousness') + .tool('getMyName', object({ name: string() }), async () => 'Your name is Neuri.') + .build(), + ) + .build({ + provider: { + apiKey: process.env.OPENAI_API_KEY!, + baseURL: process.env.OPENAI_API_BASEURL!, + }, + }) + + const historyMessage: Message[] = [] + historyMessage.push(system('You are a helpful assistant.')) + historyMessage.push(user('What is your name?')) + + await n.handleStateless(historyMessage, async (c) => { + const completion = await c.reroute('consciousness', c.messages, { model: 'gpt-3.5-turbo' }) + + const content = await completion?.firstContent() + if (content) { + historyMessage.push(assistant(content)) + } + + return content + }) + + expect(historyMessage.length).toBe(3) + }) }) diff --git a/packages/neuri/src/index.ts b/packages/neuri/src/index.ts index dba3395..719f41b 100644 --- a/packages/neuri/src/index.ts +++ b/packages/neuri/src/index.ts @@ -47,6 +47,7 @@ function newContext(options: NeuriContextOptions): NeuriContext { export interface Neuri { handle: (message: Message | Message[], handler: (ctx: NeuriContext) => Promise) => Promise + handleStateless: (message: Message | Message[], handler: (ctx: NeuriContext) => Promise) => Promise } interface NeuriInternal extends Neuri { @@ -126,6 +127,22 @@ function newNeuriBuilderBuild(cb: () => NeuriBuilderInternal): (options: { provi provider: options.provider, })) }, + async handleStateless(message, cb) { + const messages = [] + if (Array.isArray(message)) { + messages.push(...message) + } + else { + messages.push(message) + } + + return await cb(newContext({ + message, + messages, + agents: neuriInternal.agents, + provider: options.provider, + })) + }, } return neuriInternal