@stacksjs/ai 0.75.674 → 0.75.685
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/complete.js
CHANGED
|
@@ -11,4 +11,4 @@ ${document}`:document;return{kind,before,after,context,maxTokens,messages:[{role
|
|
|
11
11
|
`);if(truncated&&text.includes(`
|
|
12
12
|
`))text=text.slice(0,text.lastIndexOf(`
|
|
13
13
|
`));if(/[ \t]$/.test(before))text=text.replace(/^[ \t]+/,"");text=text.replace(/[ \t]+$/gm,"").replace(/\n+$/,"");const maxChars=Math.min(2000,maxTokens*8);if(text.length>maxChars){const cut=text.slice(0,maxChars);const newline=cut.lastIndexOf(`
|
|
14
|
-
`);text=newline>0?cut.slice(0,newline):cut}return text.trim()?text:""}function firstSentence(text){const pattern=/[.!?]["')\]”’]*(?=\s|$)/g;let match;while((match=pattern.exec(text))!==null){const end=match.index+match[0].length;const upto=text.slice(0,match.index);if(match[0][0]==="."&&ABBREVIATIONS.test(upto))continue;return text.slice(0,end)}return text}async function resolveConfig(runtime){if(runtime.config)return runtime.config;const{ai}=await import("@stacksjs/config");return ai??{}}function throwIfAborted(signal){if(signal?.aborted)throw abortReason(signal)}export async function complete(input,runtime={}){throwIfAborted(input.signal);if(!String(input.before??"").trim())return{completion:""};const config=await resolveConfig(runtime);const injected=Boolean(runtime.generate);const status=injected?{available:config.completion?.enabled!==false,provider:input.driver??config.completion?.driver??config.default??"openai",model:undefined}:completionStatus(config,input.driver);if(!status.available||!status.provider)return{completion:""};const provider=status.provider;const model=completionModel(config,provider,input.model);const prepared=prepare(input,config);const key=cacheKey({provider,model:model??"",kind:prepared.kind,context:prepared.context,before:prepared.before,after:prepared.after});const useCache=runtime.cache!==false;if(useCache){const hit=cacheGet(key);if(hit!==undefined)return{completion:hit}}const options={system:prepared.system,model,maxTokens:prepared.maxTokens,
|
|
14
|
+
`);text=newline>0?cut.slice(0,newline):cut}return text.trim()?text:""}function firstSentence(text){const pattern=/[.!?]["')\]”’]*(?=\s|$)/g;let match;while((match=pattern.exec(text))!==null){const end=match.index+match[0].length;const upto=text.slice(0,match.index);if(match[0][0]==="."&&ABBREVIATIONS.test(upto))continue;return text.slice(0,end)}return text}async function resolveConfig(runtime){if(runtime.config)return runtime.config;const{ai}=await import("@stacksjs/config");return ai??{}}function throwIfAborted(signal){if(signal?.aborted)throw abortReason(signal)}export async function complete(input,runtime={}){throwIfAborted(input.signal);if(!String(input.before??"").trim())return{completion:""};const config=await resolveConfig(runtime);const injected=Boolean(runtime.generate);const status=injected?{available:config.completion?.enabled!==false,provider:input.driver??config.completion?.driver??config.default??"openai",model:undefined}:completionStatus(config,input.driver);if(!status.available||!status.provider)return{completion:""};const provider=status.provider;const model=completionModel(config,provider,input.model);const prepared=prepare(input,config);const key=cacheKey({provider,model:model??"",kind:prepared.kind,context:prepared.context,before:prepared.before,after:prepared.after});const useCache=runtime.cache!==false;if(useCache){const hit=cacheGet(key);if(hit!==undefined)return{completion:hit}}const options={system:prepared.system,model,maxTokens:prepared.maxTokens,signal:input.signal,maxRetries:0,usageMetadata:{feature:"completion",kind:prepared.kind}};const generate=runtime.generate??createAIClient(config,provider).generate;const result=await raceAbort(Promise.resolve(generate(prepared.messages,options)),input.signal);throwIfAborted(input.signal);const completion=postProcessCompletion(result.content,{before:prepared.before,after:prepared.after,kind:prepared.kind,maxTokens:prepared.maxTokens,truncated:LENGTH_STOPS.has(String(result.finishReason??""))});if(useCache)cacheSet(key,completion);return{completion}}function driverStream(provider){switch(provider){case"anthropic":return anthropic.streamChatEvents;case"bedrock":return bedrock.streamChatEvents;case"openai":return(messages,options)=>openai.streamChatEvents(withSystem(messages,options.system),options);default:return(messages,options)=>ollama.streamChatEvents(withSystem(messages,options.system),options)}}function withSystem(messages,system){return system?[{role:"system",content:system},...messages]:messages}export async function*completeStream(input,runtime={}){throwIfAborted(input.signal);if(!String(input.before??"").trim())return;const config=await resolveConfig(runtime);const status=runtime.stream?{available:config.completion?.enabled!==false,provider:input.driver??config.completion?.driver??config.default??"openai"}:completionStatus(config,input.driver);if(!status.available||!status.provider)return;const provider=status.provider;const model=completionModel(config,provider,input.model);const prepared=prepare(input,config);const key=cacheKey({provider,model:model??"",kind:prepared.kind,context:prepared.context,before:prepared.before,after:prepared.after});const useCache=runtime.cache!==false;if(useCache){const hit=cacheGet(key);if(hit!==undefined){yield{completion:hit};return}}if(!runtime.stream)createAIClient(config,provider);const stream=runtime.stream??driverStream(provider);const options={system:prepared.system,model,maxTokens:prepared.maxTokens,signal:input.signal,maxRetries:0,usageMetadata:{feature:"completion",kind:prepared.kind}};let raw="";let last="";let finishReason;for await(const event of stream(prepared.messages,options)){throwIfAborted(input.signal);if(event.type==="text"){raw+=event.text;const next=postProcessCompletion(raw,{before:prepared.before,after:prepared.after,kind:prepared.kind,maxTokens:prepared.maxTokens,final:false});if(next!==last&&next.startsWith(last)){last=next;yield{completion:next}}}else if(event.type==="done"){finishReason=event.result.finishReason}}const final=postProcessCompletion(raw,{before:prepared.before,after:prepared.after,kind:prepared.kind,maxTokens:prepared.maxTokens,truncated:LENGTH_STOPS.has(String(finishReason??""))});if(useCache)cacheSet(key,final);if(final!==last)yield{completion:final}}
|
|
@@ -25,13 +25,21 @@ export declare function createAnthropicDriver(config: AnthropicDriverConfig): AI
|
|
|
25
25
|
* output via `responseFormat` (stacksjs/stacks#1878 A-1).
|
|
26
26
|
*/
|
|
27
27
|
export declare function chat(messages: AIMessage[], options?: ChatCompletionOptions & { system?: string }): Promise<AIResult>;
|
|
28
|
+
/**
|
|
29
|
+
* A JSON Schema in the form `output_config.format` accepts: every object
|
|
30
|
+
* closed with `additionalProperties: false` unless it says otherwise, and the
|
|
31
|
+
* numeric and length constraints the API does not support left out. The
|
|
32
|
+
* caller's schema is not changed. `generateObject()` still validates the
|
|
33
|
+
* answer against the full schema, constraints included.
|
|
34
|
+
*/
|
|
35
|
+
export declare function anthropicJsonSchema(schema: unknown): Record<string, unknown>;
|
|
28
36
|
/**
|
|
29
37
|
* A streamed chat completion, as events: text as it is written, each tool
|
|
30
38
|
* call once its arguments have streamed, then the whole result.
|
|
31
39
|
*
|
|
32
40
|
* A `tool_use` block streams its input as `input_json_delta` fragments, so a
|
|
33
|
-
* call is reported at its `content_block_stop`, whole.
|
|
34
|
-
*
|
|
41
|
+
* call is reported at its `content_block_stop`, whole. Structured output is
|
|
42
|
+
* text, so its JSON streams as text. An `error`
|
|
35
43
|
* event (an overload mid-stream) throws rather than ending the stream as if
|
|
36
44
|
* the model had finished.
|
|
37
45
|
*/
|
|
@@ -1 +1,3 @@
|
|
|
1
|
-
import{fetchWithRetry}from"../../utils/retry";import{sseJson,streamText}from"../../utils/stream";import{parseToolArguments}from"../../utils/tools";import{recordUsage}from"../../utils/usage";import{normalizeMessagesForProvider}from"../../utils/vision";import{DEFAULT_ANTHROPIC_MODEL}from"../../models";const DEFAULT_MODEL=DEFAULT_ANTHROPIC_MODEL;const DEFAULT_MAX_TOKENS=4096;const DEFAULT_VERSION="2023-06-01";const BASE_URL="https://api.anthropic.com/v1";let globalConfig=null;export function anthropicApiVersion(override){return override||globalConfig?.anthropicVersion||DEFAULT_VERSION}export function configure(config){globalConfig=config}function getConfig(config){const merged={...globalConfig,...config};if(!merged.apiKey){merged.apiKey=process.env.ANTHROPIC_API_KEY||""}return merged}export function createAnthropicDriver(config){const{apiKey,model=DEFAULT_MODEL,maxTokens=DEFAULT_MAX_TOKENS,anthropicVersion=DEFAULT_VERSION}=config;return{name:"Claude API",async process(command,systemPrompt,history){if(!apiKey){throw new Error("Anthropic API key not set. Configure your API key in settings.")}const response=await fetchWithRetry(`${BASE_URL}/messages`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":apiKey,"anthropic-version":anthropicVersion},body:JSON.stringify({model,max_tokens:maxTokens,system:systemPrompt,messages:[...history,{role:"user",content:command}]})});if(!response.ok){const error=await response.text();throw new Error(`Claude API error: ${error}`)}const data=await response.json();if(!data.content||data.content.length===0){throw new Error("Claude API returned empty content")}return data.content[0].text},async*stream(command,systemPrompt,history){if(!apiKey){throw new Error("Anthropic API key not set. Configure your API key in settings.")}const response=await fetchWithRetry(`${BASE_URL}/messages`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":apiKey,"anthropic-version":anthropicVersion},body:JSON.stringify({model,max_tokens:maxTokens,system:systemPrompt,stream:true,messages:[...history,{role:"user",content:command}]})});if(!response.ok){const error=await response.text();throw new Error(`Claude API error: ${error}`)}if(!response.body)throw new Error("No response body");for await(const event of sseJson(response.body,"Claude API")){if(event.type==="error"){const msg=event.error?.message??JSON.stringify(event.error??event);throw new Error(`[anthropic/stream] mid-stream error: ${msg}`)}if(event.type==="content_block_delta"&&event.delta?.text)yield event.delta.text}}}}function messagesRequest(messages,options){const{model=DEFAULT_MODEL,maxTokens=DEFAULT_MAX_TOKENS,temperature,topP,stop,system,tools,toolChoice,responseFormat}=options;const body={model,max_tokens:maxTokens,temperature,top_p:topP,stop_sequences:stop?Array.isArray(stop)?stop:[stop]:undefined,system,messages:normalizeMessagesForProvider(messages,"anthropic")};if(tools&&tools.length>0){body.tools=tools.map((t)=>({name:t.name,description:t.description,input_schema:t.parameters??{type:"object",properties:{}}}));if(toolChoice!==undefined)body.tool_choice=mapAnthropicToolChoice(toolChoice)}if(responseFormat
|
|
1
|
+
import{fetchWithRetry}from"../../utils/retry";import{sseJson,streamText}from"../../utils/stream";import{parseToolArguments}from"../../utils/tools";import{recordUsage}from"../../utils/usage";import{normalizeMessagesForProvider}from"../../utils/vision";import{DEFAULT_ANTHROPIC_MODEL}from"../../models";const DEFAULT_MODEL=DEFAULT_ANTHROPIC_MODEL;const DEFAULT_MAX_TOKENS=4096;const DEFAULT_VERSION="2023-06-01";const BASE_URL="https://api.anthropic.com/v1";let globalConfig=null;export function anthropicApiVersion(override){return override||globalConfig?.anthropicVersion||DEFAULT_VERSION}export function configure(config){globalConfig=config}function getConfig(config){const merged={...globalConfig,...config};if(!merged.apiKey){merged.apiKey=process.env.ANTHROPIC_API_KEY||""}return merged}export function createAnthropicDriver(config){const{apiKey,model=DEFAULT_MODEL,maxTokens=DEFAULT_MAX_TOKENS,anthropicVersion=DEFAULT_VERSION}=config;return{name:"Claude API",async process(command,systemPrompt,history){if(!apiKey){throw new Error("Anthropic API key not set. Configure your API key in settings.")}const response=await fetchWithRetry(`${BASE_URL}/messages`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":apiKey,"anthropic-version":anthropicVersion},body:JSON.stringify({model,max_tokens:maxTokens,system:systemPrompt,messages:[...history,{role:"user",content:command}]})});if(!response.ok){const error=await response.text();throw new Error(`Claude API error: ${error}`)}const data=await response.json();if(!data.content||data.content.length===0){throw new Error("Claude API returned empty content")}return data.content[0].text},async*stream(command,systemPrompt,history){if(!apiKey){throw new Error("Anthropic API key not set. Configure your API key in settings.")}const response=await fetchWithRetry(`${BASE_URL}/messages`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":apiKey,"anthropic-version":anthropicVersion},body:JSON.stringify({model,max_tokens:maxTokens,system:systemPrompt,stream:true,messages:[...history,{role:"user",content:command}]})});if(!response.ok){const error=await response.text();throw new Error(`Claude API error: ${error}`)}if(!response.body)throw new Error("No response body");for await(const event of sseJson(response.body,"Claude API")){if(event.type==="error"){const msg=event.error?.message??JSON.stringify(event.error??event);throw new Error(`[anthropic/stream] mid-stream error: ${msg}`)}if(event.type==="content_block_delta"&&event.delta?.text)yield event.delta.text}}}}function messagesRequest(messages,options){const{model=DEFAULT_MODEL,maxTokens=DEFAULT_MAX_TOKENS,temperature,topP,stop,system,tools,toolChoice,responseFormat}=options;const body={model,max_tokens:maxTokens,temperature,top_p:topP,stop_sequences:stop?Array.isArray(stop)?stop:[stop]:undefined,system:responseFormat?.type==="json_object"?withJsonObjectInstruction(system):system,messages:normalizeMessagesForProvider(messages,"anthropic")};if(tools&&tools.length>0){body.tools=tools.map((t)=>({name:t.name,description:t.description,input_schema:t.parameters??{type:"object",properties:{}}}));if(toolChoice!==undefined)body.tool_choice=mapAnthropicToolChoice(toolChoice)}if(responseFormat?.type==="json_schema")body.output_config={format:{type:"json_schema",schema:anthropicJsonSchema(responseFormat.json_schema.schema)}};return body}function postMessages(body,options={}){const config=getConfig();return fetchWithRetry(`${BASE_URL}/messages`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":config.apiKey,"anthropic-version":anthropicApiVersion(config.anthropicVersion)},body:JSON.stringify(body),...options.signal?{signal:options.signal}:{}},options.maxRetries===undefined?{}:{maxRetries:options.maxRetries})}export async function chat(messages,options={}){const startedAt=Date.now();const body=messagesRequest(messages,options);const response=await postMessages(body,options);if(!response.ok){const error=await response.text();throw new Error(`Claude API error: ${error}`)}const data=await response.json();if(!data.content||data.content.length===0){throw new Error("Claude API returned empty content")}const blocks=data.content;const toolCalls=blocks.filter((b)=>b.type==="tool_use").map((b)=>({id:b.id??"",name:b.name??"",arguments:b.input??{}}));const content=blocks.filter((b)=>b.type==="text").map((b)=>b.text??"").join("");const result={content,...toolCalls.length>0?{toolCalls}:{},model:data.model,usage:{promptTokens:data.usage?.input_tokens||0,completionTokens:data.usage?.output_tokens||0,totalTokens:(data.usage?.input_tokens||0)+(data.usage?.output_tokens||0)},finishReason:data.stop_reason};recordUsage({provider:"anthropic",model:data.model,promptTokens:result.usage.promptTokens,completionTokens:result.usage.completionTokens,totalTokens:result.usage.totalTokens,durationMs:Date.now()-startedAt,timestamp:Date.now(),...options.usageMetadata?{metadata:options.usageMetadata}:{}});return result}function mapAnthropicToolChoice(choice){if(choice==="auto")return{type:"auto"};if(choice==="required")return{type:"any"};if(choice==="none")return{type:"none"};return{type:"tool",name:choice.name}}const JSON_OBJECT_INSTRUCTION="Reply with a single JSON object and nothing else: no prose and no code fence.";function withJsonObjectInstruction(system){return system?`${system}
|
|
2
|
+
|
|
3
|
+
${JSON_OBJECT_INSTRUCTION}`:JSON_OBJECT_INSTRUCTION}const UNSUPPORTED_SCHEMA_KEYWORDS=new Set(["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minLength","maxLength"]);export function anthropicJsonSchema(schema){return closeSchema(schema)}function closeSchema(node){if(Array.isArray(node))return node.map(closeSchema);if(!node||typeof node!=="object")return node;const out={};for(const[key,value]of Object.entries(node)){if(UNSUPPORTED_SCHEMA_KEYWORDS.has(key))continue;if(key==="properties"||key==="$defs"||key==="definitions")out[key]=Object.fromEntries(Object.entries(value??{}).map(([name,sub])=>[name,closeSchema(sub)]));else if(key==="items"||key==="anyOf"||key==="allOf"||key==="oneOf"||key==="not")out[key]=closeSchema(value);else out[key]=value}const isObject=out.type==="object"||Array.isArray(out.type)&&out.type.includes("object")||"properties"in out;if(isObject&&!("additionalProperties"in out))out.additionalProperties=false;return out}export async function*streamChatEvents(messages,options={}){const startedAt=Date.now();const body=messagesRequest(messages,options);const response=await postMessages({...body,stream:true},options);if(!response.ok){const error=await response.text();throw new Error(`Claude API error: ${error}`)}if(!response.body)throw new Error("No response body");const toolBlocks=new Map;const toolCalls=[];let content="";let model=String(body.model);let promptTokens=0;let completionTokens=0;let finishReason;for await(const event of sseJson(response.body,"Claude API")){switch(event.type){case"message_start":model=event.message.model||model;promptTokens=event.message.usage?.input_tokens??0;completionTokens=event.message.usage?.output_tokens??0;break;case"content_block_start":if(event.content_block.type==="tool_use"){toolBlocks.set(event.index,{id:event.content_block.id??"",name:event.content_block.name??"",json:""})}break;case"content_block_delta":{const delta=event.delta;if("text"in delta&&delta.type==="text_delta"){content+=delta.text;yield{type:"text",text:delta.text}}else if("partial_json"in delta&&delta.type==="input_json_delta"){const block=toolBlocks.get(event.index);if(!block)break;block.json+=delta.partial_json}break}case"content_block_stop":{const block=toolBlocks.get(event.index);if(block){const call={id:block.id,name:block.name,arguments:parseToolArguments(block.json,block.name)};toolCalls.push(call);yield{type:"tool_call",call}}break}case"message_delta":finishReason=event.delta.stop_reason??finishReason;completionTokens=event.usage?.output_tokens??completionTokens;break;case"error":throw new Error(`Claude API error: ${event.error.type}: ${event.error.message}`)}}const result={content,...toolCalls.length>0?{toolCalls}:{},model,usage:{promptTokens,completionTokens,totalTokens:promptTokens+completionTokens},...finishReason?{finishReason}:{}};recordUsage({provider:"anthropic",model,promptTokens,completionTokens,totalTokens:promptTokens+completionTokens,durationMs:Date.now()-startedAt,timestamp:Date.now(),...options.usageMetadata?{metadata:options.usageMetadata}:{}});yield{type:"done",result}}export function streamChat(messages,options={}){return streamText(streamChatEvents(messages,options))}export async function prompt(text,options={}){const result=await chat([{role:"user",content:text}],options);return result.content}export function estimateTokens(text){return Math.ceil(text.length/4)}export const anthropicDriver={create:createAnthropicDriver};export const anthropic={configure,chat,streamChat,streamChatEvents,prompt,estimateTokens,createDriver:createAnthropicDriver};export default anthropic;
|
package/dist/types.d.ts
CHANGED
|
@@ -229,9 +229,10 @@ export declare interface ConfiguredAIClient {
|
|
|
229
229
|
) => Promise<{ data: T, result: AIResult }>
|
|
230
230
|
}
|
|
231
231
|
/**
|
|
232
|
-
* Structured-output / JSON-mode response format
|
|
233
|
-
*
|
|
234
|
-
*
|
|
232
|
+
* Structured-output / JSON-mode response format, modeled after OpenAI's
|
|
233
|
+
* `response_format`. The Anthropic driver sends `json_schema` as the Messages
|
|
234
|
+
* API's own JSON mode (`output_config.format`) and `json_object` as a system
|
|
235
|
+
* instruction; the JSON comes back as text either way (stacksjs/stacks#3380).
|
|
235
236
|
*/
|
|
236
237
|
export type AIResponseFormat = | { type: 'text' }
|
|
237
238
|
| { type: 'json_object' }
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/ai",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.75.
|
|
5
|
+
"version": "0.75.685",
|
|
6
6
|
"description": "Stacks Artificial Intelligence.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -65,12 +65,12 @@
|
|
|
65
65
|
"prepublishOnly": "bun run build"
|
|
66
66
|
},
|
|
67
67
|
"dependencies": {
|
|
68
|
-
"@stacksjs/cli": "0.75.
|
|
69
|
-
"@stacksjs/config": "0.75.
|
|
70
|
-
"@stacksjs/path": "0.75.
|
|
71
|
-
"@stacksjs/router": "0.75.
|
|
72
|
-
"@stacksjs/security": "0.75.
|
|
73
|
-
"@stacksjs/storage": "0.75.
|
|
68
|
+
"@stacksjs/cli": "0.75.685",
|
|
69
|
+
"@stacksjs/config": "0.75.685",
|
|
70
|
+
"@stacksjs/path": "0.75.685",
|
|
71
|
+
"@stacksjs/router": "0.75.685",
|
|
72
|
+
"@stacksjs/security": "0.75.685",
|
|
73
|
+
"@stacksjs/storage": "0.75.685",
|
|
74
74
|
"@stacksjs/ts-cloud": "^0.16.144"
|
|
75
75
|
},
|
|
76
76
|
"peerDependencies": {
|