Skip to content

Commit

Permalink
feat: handle stateless (#33)
Browse files Browse the repository at this point in the history
  • Loading branch information
luoling8192 authored Jan 7, 2025
1 parent 540214c commit 4d56fd5
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 2 deletions.
37 changes: 35 additions & 2 deletions packages/neuri/src/index.test.ts
Original file line number Diff line number Diff line change
@@ -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 () => {
Expand Down Expand Up @@ -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)
})
})
17 changes: 17 additions & 0 deletions packages/neuri/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ function newContext(options: NeuriContextOptions): NeuriContext {

export interface Neuri {
handle: <R>(message: Message | Message[], handler: (ctx: NeuriContext) => Promise<R>) => Promise<R>
handleStateless: <R>(message: Message | Message[], handler: (ctx: NeuriContext) => Promise<R>) => Promise<R>
}

interface NeuriInternal extends Neuri {
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 4d56fd5

Please sign in to comment.