fix(llm-pi-ai): withhold ChatGPT sign-in and serve one catalog
pi-ai 1.0.0 adds Sign in with ChatGPT to the `openai` provider, and that login refuses to start unless the app supplies a stable installation UUID through LoginOptions.getDeviceId. The harness keeps no installation ID meant for a third-party account sign-in, so the route offers its API-key login only; a Loader-composed test pins the offered methods. catalogProvider(), catalogModels(), and catalogProviderIds() now read one index that leaves out providers without a chat model, so a hand-declared route under such a key inherits nothing from pi-ai. The browser-worker stub gains the builtinModels refusal llm-pi-ai imports and drops the getBuiltinProviders reader nothing imports. The tool-argument streaming spec also covers the patched Anthropic Messages path.
This commit is contained in:
1 parent
abfa6302b7
commit
e1878e41ca
13 files changed
+134
-52
No files matched your search
@@ -5,10 +5,11 @@
|
||||
* statically at module scope, so the row cannot mount without it.
|
||||
*
|
||||
* Every symbol `llm-pi-ai` imports by name is present: a missing CommonJS symbol
|
||||
* would surface as `undefined` at call time instead of a link error. The four catalog readers
|
||||
* return empty collections rather than throwing — the row reads them while it
|
||||
* activates, and "this deployment ships no pi-ai provider" is the truth here.
|
||||
* Everything on a request path is loud.
|
||||
* would surface as `undefined` at call time instead of a link error. The row
|
||||
* reads the catalog while it activates, so the provider reader returns
|
||||
* providers without models and the two model readers return empty collections
|
||||
* instead of throwing: this deployment serves no pi-ai model. Everything on a
|
||||
* request path is loud.
|
||||
*/
|
||||
import { notImplementedFail } from '../notImplementedFail.ts'
|
||||
|
||||
@@ -26,7 +27,14 @@ export const getSupportedThinkingLevels = notImplementedFail(MODULE, 'getSupport
|
||||
/** Context-overflow predicate (unavailable). */
|
||||
export const isContextOverflow = notImplementedFail(MODULE, 'isContextOverflow')
|
||||
|
||||
/** Builtin provider ids of pi-ai 0.84.2, in catalog order. */
|
||||
/** Collection of every builtin provider (unavailable). */
|
||||
export const builtinModels = notImplementedFail(MODULE, 'builtinModels')
|
||||
|
||||
/**
|
||||
* Builtin provider ids as pi-ai 0.84.2 listed them, in catalog order. The list
|
||||
* is a fixed copy that pi-ai upgrades do not regenerate, so it omits providers
|
||||
* added since.
|
||||
*/
|
||||
const BUILTIN_PROVIDER_IDS: readonly string[] = [
|
||||
'amazon-bedrock', 'ant-ling', 'anthropic', 'azure-openai-responses', 'baseten', 'cerebras',
|
||||
'cloudflare-ai-gateway', 'cloudflare-workers-ai', 'deepseek', 'fireworks', 'github-copilot',
|
||||
@@ -39,10 +47,11 @@ const BUILTIN_PROVIDER_IDS: readonly string[] = [
|
||||
]
|
||||
|
||||
/**
|
||||
* Installed catalog providers, read while `llm-pi-ai` activates. Each carries the
|
||||
* api-key auth marker the adapter filters on, and no models: the provider
|
||||
* directory therefore matches the served deployment while every request path
|
||||
* lands on a loud symbol above.
|
||||
* Installed catalog providers, read while `llm-pi-ai` activates. `llm-pi-ai`
|
||||
* registers the whole catalog as configurable the moment it mounts and rejects
|
||||
* an empty registration, so these carry pi-ai's ids instead of being an empty
|
||||
* list. Each has the api-key auth marker the adapter filters on, and no
|
||||
* models, so every request path lands on a loud symbol above.
|
||||
* @returns one entry per builtin provider.
|
||||
*/
|
||||
export function builtinProviders(): unknown[] {
|
||||
@@ -54,16 +63,6 @@ export function builtinProviders(): unknown[] {
|
||||
}))
|
||||
}
|
||||
|
||||
/**
|
||||
* Provider route ids of the installed catalog. `llm-pi-ai` registers the whole
|
||||
* catalog as configurable the moment it mounts and rejects an empty
|
||||
* registration, so these are pi-ai's real ids rather than an empty list.
|
||||
* @returns the builtin provider ids.
|
||||
*/
|
||||
export function getBuiltinProviders(): string[] {
|
||||
return [...BUILTIN_PROVIDER_IDS]
|
||||
}
|
||||
|
||||
/**
|
||||
* Models of one installed catalog provider.
|
||||
* @returns no models.
|
||||
@@ -94,7 +93,6 @@ export const __esModule = true
|
||||
|
||||
/** CommonJS default export: the members `require()` hands a caller of this module. */
|
||||
export default {
|
||||
createProvider, createModels, getSupportedThinkingLevels, isContextOverflow, builtinProviders,
|
||||
getBuiltinModels, getAllBuiltinModels, getBuiltinProviders, anthropicMessagesApi, openAICompletionsApi,
|
||||
openAIResponsesApi,
|
||||
createProvider, createModels, getSupportedThinkingLevels, isContextOverflow, builtinModels, builtinProviders,
|
||||
getBuiltinModels, getAllBuiltinModels, anthropicMessagesApi, openAICompletionsApi, openAIResponsesApi,
|
||||
}
|
||||
@@ -50,7 +50,7 @@ const CALLED: [string, Record<string, unknown>, readonly string[]][] = [
|
||||
['got', got.default, ['post']],
|
||||
['@deepseek-ai/pi-ai', piAi, [
|
||||
'createProvider', 'createModels', 'openAICompletionsApi', 'openAIResponsesApi', 'anthropicMessagesApi',
|
||||
'isContextOverflow', 'getSupportedThinkingLevels',
|
||||
'isContextOverflow', 'getSupportedThinkingLevels', 'builtinModels',
|
||||
]],
|
||||
]
|
||||
|
||||
|
||||
@@ -87,8 +87,8 @@
|
||||
en: b6bd570c0159ba08
|
||||
zh: 7d2d91eea6a8d830
|
||||
/deepseek-ai-dsh-llm-pi-ai/known-limitations-and-deferred-work:
|
||||
en: 24213b5d80e1b1ea
|
||||
zh: e7524db2a35f6659
|
||||
en: 3ac77ae061cf0683
|
||||
zh: c25abff6da8c1a22
|
||||
/deepseek-ai-dsh-llm-pi-ai/known-limitations-and-deferred-work/dev-note:
|
||||
en: 3678dd0f6642c2a5
|
||||
zh: 75cbdd064cc64282
|
||||
@@ -216,6 +216,7 @@ These limits define where the adapter stops and future work begins. They are cur
|
||||
|
||||
- **`maxRequestImageBytes` counts base64 image payload only** — text, tools, descriptors, and JSON structure ride outside the bound, so it must sit below the gateway's request-body cap with headroom.
|
||||
- **A sign-in lives only in the process that started it** — an authorization attempt is not durable, so reloading the page mid-login abandons it and the human starts over. Signing out is `deleteRecord` on the stored record, which forgets it locally without telling the issuer.
|
||||
- **OpenAI offers no ChatGPT sign-in** — pi-ai's Sign in with ChatGPT identifies the installation to OpenAI with a stable UUID the app supplies, and the harness keeps no installation ID meant for a third-party account sign-in; the `openai` route signs in with an API key.
|
||||
- **Provider-native discovery answers through this plugin's ambient context** — a route naming no credential defers to the catalog provider's own resolution, which asks for environment values (`AZURE_OPENAI_API_KEY`, `AWS_PROFILE`, and each provider's own set) and for local credential files. Both questions are answered here: the credential seam is consulted before the process environment, and file existence is checked against the host process's filesystem with `~` expanded. What it cannot do is *read* a credential file's contents — a provider that parses `~/.aws/credentials` itself does so directly, outside the seam.
|
||||
- **Reset restores inherited configuration** — resetting a route supplied by a lower profile layer restores that route.
|
||||
- **Complete Config replacement can remove inherited dictionary entries** — a field reset instead restores its inherited value.
|
||||
|
||||
@@ -216,6 +216,7 @@ pi-ai 事件变成 harness 的推理、文本、工具调用、用量与 finish
|
||||
|
||||
- **`maxRequestImageBytes` 只计算 base64 图片载荷**,文本、工具、描述符与 JSON 结构在该上限之外,因此它必须留有余量地低于网关请求体上限。
|
||||
- **登录只存在于发起它的进程中**——授权尝试不持久,因此登录中途刷新页面会放弃它,用户需要重新开始。退出登录是对已存储记录执行 `deleteRecord`,只在本地忘记它,不会告知签发方。
|
||||
- **OpenAI 不提供 ChatGPT 登录**——pi-ai 的 Sign in with ChatGPT 用应用提供的稳定 UUID 向 OpenAI 标识安装实例,而 harness 没有用于第三方账号登录的安装 ID;`openai` 路由改用 API key 登录。
|
||||
- **提供方原生发现经本插件的 ambient context 回答**——不点名凭据的路由交由目录提供方自身解析,它会询问环境值(`AZURE_OPENAI_API_KEY`、`AWS_PROFILE` 及各提供方自有集合)与本地凭据文件。两个问题都在这里得到回答:凭据 seam 先于进程环境被查询,文件存在性则针对宿主进程的文件系统以 `~` 展开后检查。它做不到的是*读取*凭据文件内容——自行解析 `~/.aws/credentials` 的提供方会直接读取,不经该 seam。
|
||||
- **重置恢复继承配置**——重置下层 profile 提供的路由会恢复该路由。
|
||||
- **完整替换 Config 可以移除继承的字典条目**——字段重置则恢复其继承值。
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
* @module dsh-llm-pi-ai/catalog
|
||||
*/
|
||||
|
||||
import { builtinProviders, getAllBuiltinModels, getBuiltinModels, getBuiltinProviders } from '@earendil-works/pi-ai/providers/all'
|
||||
import { builtinProviders, getAllBuiltinModels, getBuiltinModels } from '@earendil-works/pi-ai/providers/all'
|
||||
import type { BuiltinProvider } from '@earendil-works/pi-ai/providers/all'
|
||||
import type {
|
||||
AnthropicMessagesCompat,
|
||||
@@ -166,41 +166,53 @@ export const CHAT_TEMPLATE_VARS = Object.keys(CHAT_TEMPLATE_VAR_GATE) as readonl
|
||||
let providerIndex: Map<string, Provider> | undefined
|
||||
|
||||
/**
|
||||
* Installed catalog providers by id, constructed once. Each entry owns the API
|
||||
* implementations for its own models, which is why a catalog route reuses this
|
||||
* provider instead of being rebuilt from parts.
|
||||
* @returns the catalog provider index.
|
||||
* Whether this adapter serves one installed catalog provider. It dispatches
|
||||
* chat requests only, so a provider whose catalog lists models but no chat
|
||||
* model (image-generation or classifier models alone) is not a catalog route;
|
||||
* a provider whose catalog lists no models at all stays one.
|
||||
* @param provider - the installed provider.
|
||||
* @returns whether the provider ships a chat model or lists no models.
|
||||
*/
|
||||
function servesChat(provider: Provider): boolean {
|
||||
const id = provider.id as BuiltinProvider
|
||||
return getBuiltinModels(id).length > 0 || getAllBuiltinModels(id).length === 0
|
||||
}
|
||||
|
||||
/**
|
||||
* Installed catalog providers this adapter serves, by id, constructed once.
|
||||
* Each entry owns the API implementations for its own models, which is why a
|
||||
* catalog route reuses this provider instead of being rebuilt from parts.
|
||||
* @returns the catalog provider index, in catalog order.
|
||||
*/
|
||||
function catalogProviders(): Map<string, Provider> {
|
||||
providerIndex ??= new Map(builtinProviders().map(provider => [provider.id, provider]))
|
||||
providerIndex ??= new Map(builtinProviders().filter(servesChat).map(provider => [provider.id, provider]))
|
||||
return providerIndex
|
||||
}
|
||||
|
||||
/**
|
||||
* The installed catalog provider for one route, when pi-ai ships one.
|
||||
* The installed catalog provider for one route, when pi-ai ships one this
|
||||
* adapter serves.
|
||||
* @param provider - provider route key.
|
||||
* @returns the catalog provider, or `undefined` for a route pi-ai does not ship.
|
||||
* @returns the catalog provider, or `undefined` for a route pi-ai does not ship
|
||||
* or ships without a chat model.
|
||||
*/
|
||||
export function catalogProvider(provider: string): Provider | undefined {
|
||||
return catalogProviders().get(provider)
|
||||
}
|
||||
|
||||
/**
|
||||
* Every provider route the installed pi-ai catalog ships, except a provider
|
||||
* whose catalog lists models but no chat model. This adapter dispatches chat
|
||||
* requests only, so a provider of image-generation or classifier models alone
|
||||
* is not a configurable route; a provider whose catalog lists no models stays.
|
||||
* Every provider route the installed pi-ai catalog ships and this adapter
|
||||
* serves: a provider whose catalog lists models but no chat model is left out.
|
||||
* @returns the catalog provider ids, in catalog order.
|
||||
*/
|
||||
export function catalogProviderIds(): readonly string[] {
|
||||
return getBuiltinProviders().filter(provider =>
|
||||
getBuiltinModels(provider).length > 0 || getAllBuiltinModels(provider).length === 0)
|
||||
return [...catalogProviders().keys()]
|
||||
}
|
||||
|
||||
/**
|
||||
* The installed catalog models for one route, indexed by model id.
|
||||
* @param provider - provider route key.
|
||||
* @returns catalog models by id; empty for a route pi-ai does not ship.
|
||||
* @returns catalog models by id; empty for a route {@link catalogProvider} does not return.
|
||||
*/
|
||||
export function catalogModels(provider: string): Map<string, Model<Api>> {
|
||||
if (!catalogProviders().has(provider)) return new Map()
|
||||
|
||||
@@ -16,19 +16,30 @@ import { recordKeyFor } from './auth.ts'
|
||||
import type { PiAiAuthInjection } from './adapter.ts'
|
||||
import { createModels } from './models.ts'
|
||||
|
||||
/**
|
||||
* Catalog providers whose OAuth login this adapter does not offer. pi-ai's Sign
|
||||
* in with ChatGPT (`openai`) identifies the installation to OpenAI with a
|
||||
* stable UUID that the app supplies through `LoginOptions.getDeviceId`, and it
|
||||
* refuses to start without one. The harness keeps no installation ID meant for
|
||||
* a third-party account sign-in, so the route signs in with an API key.
|
||||
*/
|
||||
const UNSERVED_OAUTH: ReadonlySet<string> = new Set(['openai'])
|
||||
|
||||
/**
|
||||
* The login methods one catalog provider offers.
|
||||
*
|
||||
* A method appears only when pi-ai can actually run it: `oauth` always carries
|
||||
* a `login`, while an api-key method has one only when the provider collects
|
||||
* its key interactively — which every installed one currently does, so a key is
|
||||
* typed into pi-ai's own prompt rather than into the settings form.
|
||||
* A method appears only when pi-ai can actually run it: `oauth` carries a
|
||||
* `login` that runs without app-supplied login options except for the
|
||||
* providers in {@link UNSERVED_OAUTH}, while an api-key method has one only
|
||||
* when the provider collects its key interactively — which every installed one
|
||||
* currently does, so a key is typed into pi-ai's own prompt rather than into
|
||||
* the settings form.
|
||||
* @param provider - the installed catalog provider, if pi-ai ships one.
|
||||
* @returns its methods, most preferred first; empty when it offers no login.
|
||||
*/
|
||||
function loginMethods(provider: Provider | undefined): AuthorizationMethod[] {
|
||||
const methods: AuthorizationMethod[] = []
|
||||
const oauth = provider?.auth.oauth
|
||||
const oauth = provider === undefined || UNSERVED_OAUTH.has(provider.id) ? undefined : provider.auth.oauth
|
||||
if (oauth !== undefined) methods.push({ id: 'oauth', label: oauth.loginLabel ?? oauth.name })
|
||||
const apiKey = provider?.auth.apiKey
|
||||
if (apiKey?.login !== undefined) methods.push({ id: 'api-key', label: apiKey.name })
|
||||
|
||||
@@ -7,7 +7,7 @@ import { describe, expect, it, vi } from 'vitest'
|
||||
// no catalog data, such as the browser-worker preview).
|
||||
vi.mock('@earendil-works/pi-ai/providers/all', async importOriginal => ({
|
||||
...await importOriginal<typeof import('@earendil-works/pi-ai/providers/all')>(),
|
||||
getBuiltinProviders: () => ['chat-provider', 'classifier-provider', 'uncataloged-provider'],
|
||||
builtinProviders: () => ['chat-provider', 'classifier-provider', 'uncataloged-provider'].map(id => ({ id })),
|
||||
getBuiltinModels: (provider: string) => provider === 'chat-provider' ? [{ id: 'chat-model' }] : [],
|
||||
getAllBuiltinModels: (provider: string) => {
|
||||
if (provider === 'chat-provider') return [{ id: 'chat-model' }]
|
||||
@@ -16,10 +16,17 @@ vi.mock('@earendil-works/pi-ai/providers/all', async importOriginal => ({
|
||||
},
|
||||
}))
|
||||
|
||||
import { catalogProviderIds } from '../src/catalog.ts'
|
||||
import { catalogModels, catalogProvider, catalogProviderIds } from '../src/catalog.ts'
|
||||
|
||||
describe('catalog provider ids', () => {
|
||||
it('drops a provider that lists only non-chat models and keeps one that lists none', () => {
|
||||
expect(catalogProviderIds()).toEqual(['chat-provider', 'uncataloged-provider'])
|
||||
})
|
||||
|
||||
it('answers no catalog provider or models for the provider it drops', () => {
|
||||
expect(catalogProvider('classifier-provider')).toBeUndefined()
|
||||
expect(catalogModels('classifier-provider').size).toBe(0)
|
||||
expect(catalogProvider('uncataloged-provider')).toEqual({ id: 'uncataloged-provider' })
|
||||
expect([...catalogModels('chat-provider').keys()]).toEqual(['chat-model'])
|
||||
})
|
||||
})
|
||||
@@ -7,10 +7,11 @@ const configurations = new WeakMap<Context, Awaited<ReturnType<typeof liveConfig
|
||||
import * as LlmPiAi from '@deepseek-ai/dsh-llm-pi-ai'
|
||||
import { PiAiAdapter } from '@deepseek-ai/dsh-llm-pi-ai'
|
||||
import type { ContextFormed } from '@deepseek-ai/dsh-llm'
|
||||
import { getBuiltinModels } from '@earendil-works/pi-ai/providers/all'
|
||||
import { getAllBuiltinModels, getBuiltinModels, getBuiltinProviders } from '@earendil-works/pi-ai/providers/all'
|
||||
import { AssistantMessageEventStream } from '@earendil-works/pi-ai/utils/event-stream'
|
||||
import { normalizeContext } from '@earendil-works/pi-ai/utils/transcript'
|
||||
import type { Api, Model, OpenAICompletionsCompat, Provider } from '@earendil-works/pi-ai'
|
||||
import { catalogModels, catalogProvider } from '../src/catalog.ts'
|
||||
import { resolveProfiles } from '../src/config.ts'
|
||||
import { createModels, createProvider, getSupportedThinkingLevels } from '../src/models.ts'
|
||||
import { buildProvider, supportedProtocols } from '../src/provider.ts'
|
||||
@@ -1243,9 +1244,14 @@ describe('configurable-provider directory', () => {
|
||||
const offered = ctx.llm.listConfigurableProviders().map(entry => entry.provider)
|
||||
|
||||
// The installed catalog ships `typesafe` with classifier models only; with
|
||||
// nothing to dispatch a chat request to, the route is not offered.
|
||||
// nothing to dispatch a chat request to, the route is not offered and is
|
||||
// not a catalog route anywhere else either.
|
||||
expect(getBuiltinProviders()).toContain('typesafe')
|
||||
expect(getAllBuiltinModels('typesafe').length).toBeGreaterThan(0)
|
||||
expect(getBuiltinModels('typesafe')).toEqual([])
|
||||
expect(offered).not.toContain('typesafe')
|
||||
expect(catalogProvider('typesafe')).toBeUndefined()
|
||||
expect(catalogModels('typesafe').size).toBe(0)
|
||||
})
|
||||
|
||||
it('lists a route a stored profile names as a catalog route, not a declared one', async () => {
|
||||
|
||||
@@ -9,6 +9,7 @@ import { Context } from '@deepseek-ai/cordis'
|
||||
import Loader, { type ModuleLoaderV2 } from '@deepseek-ai/cordis-plugin-loader'
|
||||
import Include from '@deepseek-ai/cordis-plugin-include'
|
||||
import LlmRuntime, { createMessage, createUserMessage, userAgent } from '@deepseek-ai/dsh-llm'
|
||||
import AuthorizationService from '@deepseek-ai/dsh-authorization'
|
||||
import LocalCredentialProvider from '@deepseek-ai/dsh-credentials-local'
|
||||
import { profileComposition } from '../../../settings/settings/tests/profile-composition.ts'
|
||||
import * as LlmPiAi from '@deepseek-ai/dsh-llm-pi-ai'
|
||||
@@ -50,6 +51,8 @@ async function loadComposition(): Promise<{ ctx: Context; settingsPath: string }
|
||||
' config:',
|
||||
` path: ${JSON.stringify(join(root, '.credentials.yaml'))}`,
|
||||
' debounceMs: 10',
|
||||
'- id: authorization',
|
||||
" name: '@deepseek-ai/dsh-authorization'",
|
||||
'- id: llm-pi-ai',
|
||||
" name: '@deepseek-ai/dsh-llm-pi-ai'",
|
||||
'',
|
||||
@@ -63,6 +66,7 @@ async function loadComposition(): Promise<{ ctx: Context; settingsPath: string }
|
||||
const modules = new Map<string, unknown>([
|
||||
['test-llm-service', LlmRuntime],
|
||||
['@deepseek-ai/dsh-credentials-local', LocalCredentialProvider],
|
||||
['@deepseek-ai/dsh-authorization', AuthorizationService],
|
||||
['@deepseek-ai/dsh-llm-pi-ai', LlmPiAi],
|
||||
])
|
||||
const internal: ModuleLoaderV2 = {
|
||||
@@ -110,6 +114,17 @@ describe('llm-pi-ai real dormant composition', () => {
|
||||
expect(server.headers[0]?.authorization).toBe('Bearer key-from-store')
|
||||
})
|
||||
|
||||
it('offers OpenAI sign-in by API key only, while other subscription logins stay', async () => {
|
||||
const { ctx } = await loadComposition()
|
||||
const methods = (provider: string): string[] | undefined => ctx.authorization.list()
|
||||
.find(entry => entry.key === LlmPiAi.recordKeyFor(provider))?.methods.map(method => method.id)
|
||||
|
||||
// pi-ai's Sign in with ChatGPT needs an installation ID the harness does
|
||||
// not supply, so the route offers only its key login.
|
||||
expect(methods('openai')).toEqual(['api-key'])
|
||||
expect(methods('anthropic')).toEqual(['oauth', 'api-key'])
|
||||
})
|
||||
|
||||
it('uses settings-only route headers for model discovery', async () => {
|
||||
vi.stubEnv('PI_COMPOSITION_KEY', '')
|
||||
const server = await mockServer([{ body: JSON.stringify({ data: [{ id: 'acme-private' }] }) }])
|
||||
|
||||
@@ -20,6 +20,7 @@ vi.mock('../src/models.ts', async importOriginal => ({
|
||||
}))
|
||||
|
||||
const { credentialStoreFrom, authContextFrom, recordKeyFor } = await import('../src/auth.ts')
|
||||
const { catalogProvider } = await import('../src/catalog.ts')
|
||||
const { registerPiAiFlows } = await import('../src/login.ts')
|
||||
|
||||
const CODEX = recordKeyFor('openai-codex')
|
||||
@@ -96,6 +97,11 @@ describe('pi-ai login flows', () => {
|
||||
// through its own prompt rather than leaving it to the settings form.
|
||||
expect(offered.find(entry => entry.key === recordKeyFor('deepseek'))?.methods.map(one => one.id))
|
||||
.toEqual(['api-key'])
|
||||
// pi-ai ships Sign in with ChatGPT for `openai`, which needs an
|
||||
// installation ID the harness does not supply; only the key login is offered.
|
||||
expect(catalogProvider('openai')?.auth.oauth?.loginLabel).toBe('Sign in with ChatGPT')
|
||||
expect(offered.find(entry => entry.key === recordKeyFor('openai'))?.methods.map(one => one.id))
|
||||
.toEqual(['api-key'])
|
||||
})
|
||||
|
||||
it('runs the pi-ai auth type the chosen method names', async () => {
|
||||
|
||||
@@ -32,7 +32,8 @@ export const textEvents = [
|
||||
/** Local provider stand-in: replays scripted behaviors per request. */
|
||||
export async function mockServer(script: {
|
||||
status?: number
|
||||
events?: string[]
|
||||
/** SSE frames: a string is sent as `data:` alone; a pair also names the frame's `event:`. */
|
||||
events?: (string | { event: string; data: string })[]
|
||||
body?: string
|
||||
delayMs?: number
|
||||
/** Keep the SSE response open after its scripted events until the client disconnects. */
|
||||
@@ -79,7 +80,7 @@ export async function mockServer(script: {
|
||||
if (!behavior.holdOpen) response.end()
|
||||
return
|
||||
}
|
||||
response.write(`data: ${event}\n\n`)
|
||||
response.write(typeof event === 'string' ? `data: ${event}\n\n` : `event: ${event.event}\ndata: ${event.data}\n\n`)
|
||||
if (behavior.delayMs === undefined) writeNext()
|
||||
else timer = setTimeout(writeNext, behavior.delayMs)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import type { AssistantMessageEvent, Model } from '@earendil-works/pi-ai'
|
||||
import { stream as streamAnthropic } from '@earendil-works/pi-ai/api/anthropic-messages'
|
||||
import { stream as streamCompletions } from '@earendil-works/pi-ai/api/openai-completions'
|
||||
import { stream as streamResponses } from '@earendil-works/pi-ai/api/openai-responses'
|
||||
import { normalizeContext } from '@earendil-works/pi-ai/utils/transcript'
|
||||
@@ -12,7 +13,7 @@ const args = { file_path: 'notes.md', content: 'x'.repeat(2048) }
|
||||
const argsJson = JSON.stringify(args)
|
||||
const fragments = argsJson.match(/.{1,7}/gs) ?? []
|
||||
|
||||
function model<A extends 'openai-completions' | 'openai-responses'>(api: A, baseUrl: string): Model<A> {
|
||||
function model<A extends 'anthropic-messages' | 'openai-completions' | 'openai-responses'>(api: A, baseUrl: string): Model<A> {
|
||||
return {
|
||||
id: 'm', name: 'm', api, provider: 'test', baseUrl, reasoning: false, input: ['text'],
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, contextWindow: 8192, maxTokens: 1024,
|
||||
@@ -61,6 +62,29 @@ describe('streamed tool-call arguments (patched pi-ai)', () => {
|
||||
expect(final).toEqual(args)
|
||||
})
|
||||
|
||||
it('anthropic-messages parses arguments once, at the end of the call', async () => {
|
||||
const frame = (data: Record<string, unknown>): { event: string; data: string } =>
|
||||
({ event: String(data['type']), data: JSON.stringify(data) })
|
||||
const server = await mockServer([{ events: [
|
||||
frame({ type: 'message_start', message: {
|
||||
id: 'msg_1', type: 'message', role: 'assistant', model: 'm', content: [],
|
||||
stop_reason: null, stop_sequence: null, usage: { input_tokens: 3, output_tokens: 1 },
|
||||
} }),
|
||||
frame({ type: 'content_block_start', index: 0, content_block: { type: 'tool_use', id: 'toolu_1', name: 'write', input: {} } }),
|
||||
...fragments.map(fragment => frame({
|
||||
type: 'content_block_delta', index: 0, delta: { type: 'input_json_delta', partial_json: fragment },
|
||||
})),
|
||||
frame({ type: 'content_block_stop', index: 0 }),
|
||||
frame({ type: 'message_delta', delta: { stop_reason: 'tool_use', stop_sequence: null }, usage: { output_tokens: 5 } }),
|
||||
frame({ type: 'message_stop' }),
|
||||
] }])
|
||||
const events = streamAnthropic(model('anthropic-messages', server.url), context, { apiKey: 'test-key' })
|
||||
const { partials, final } = await collect(events)
|
||||
expect(partials).toHaveLength(fragments.length)
|
||||
expect(partials.every(partial => JSON.stringify(partial) === '{}')).toBe(true)
|
||||
expect(final).toEqual(args)
|
||||
})
|
||||
|
||||
it('openai-responses parses arguments once, at the end of the call', async () => {
|
||||
const item = { type: 'function_call', call_id: 'call_1', id: 'fc_1', name: 'write' }
|
||||
const server = await mockServer([{ events: [
|
||||
|
||||
Reference in new issue
Block a user