-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
12 changed files
with
250 additions
and
34 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
publish |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
# @novachat/plugin-anthropic | ||
|
||
NovaChat Anthropic Plugin. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
{ | ||
"name": "@novachat/plugin-anthropic", | ||
"keywords": [ | ||
"novachat", | ||
"novachat-plugin" | ||
], | ||
"version": "0.1.0", | ||
"license": "MIT", | ||
"type": "module", | ||
"files": [ | ||
"publish" | ||
], | ||
"scripts": { | ||
"setup": "pnpm build", | ||
"build": "novachat", | ||
"dev": "pnpm build --watch" | ||
}, | ||
"sideEffects": false, | ||
"devDependencies": { | ||
"@anthropic-ai/sdk": "^0.28.0", | ||
"@novachat/cli": "workspace:*", | ||
"typescript": "^5.3.3", | ||
"vitest": "^1.2.2", | ||
"@novachat/plugin": "workspace:*" | ||
}, | ||
"publishConfig": { | ||
"access": "public", | ||
"registry": "https://registry.npmjs.org/" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,133 @@ | ||
import * as novachat from '@novachat/plugin' | ||
import type AnthropicTypes from '@anthropic-ai/sdk' | ||
import { Anthropic } from '@anthropic-ai/sdk' | ||
import { getImageAsBase64 } from './utils/base64' | ||
|
||
async function convertMessages( | ||
messages: novachat.QueryRequest['messages'], | ||
): Promise<AnthropicTypes.MessageCreateParamsNonStreaming['messages']> { | ||
return Promise.all( | ||
messages.map(async (it) => { | ||
if (!it.content) { | ||
throw new Error('content is required') | ||
} | ||
if (!it.attachments) { | ||
return { | ||
role: it.role, | ||
content: it.content, | ||
} as AnthropicTypes.MessageParam | ||
} | ||
return { | ||
role: it.role, | ||
content: [ | ||
{ | ||
type: 'text', | ||
text: it.content, | ||
}, | ||
...(await Promise.all( | ||
it.attachments.map(async (it) => { | ||
return { | ||
type: 'image', | ||
source: { | ||
type: 'base64', | ||
...(await getImageAsBase64(it.url)), | ||
}, | ||
} as AnthropicTypes.ImageBlockParam | ||
}), | ||
)), | ||
], | ||
} as AnthropicTypes.MessageParam | ||
}), | ||
) | ||
} | ||
|
||
function getModelMaxTokens(model: string): number { | ||
if (model.startsWith('claude-3-5')) { | ||
return 4096 | ||
} | ||
return 8192 | ||
} | ||
|
||
async function parseReq( | ||
req: novachat.QueryRequest, | ||
stream: boolean, | ||
): Promise<AnthropicTypes.MessageCreateParams> { | ||
return { | ||
messages: await convertMessages( | ||
req.messages.filter((it) => | ||
( | ||
[ | ||
'user', | ||
'assistant', | ||
] as novachat.QueryRequest['messages'][number]['role'][] | ||
).includes(it.role), | ||
), | ||
), | ||
max_tokens: getModelMaxTokens(req.model), | ||
stream, | ||
model: req.model, | ||
system: req.messages.find((it) => it.role === 'system')?.content, | ||
} as AnthropicTypes.MessageCreateParamsNonStreaming | ||
} | ||
|
||
function parseResponse( | ||
resp: AnthropicTypes.Messages.Message, | ||
): novachat.QueryResponse { | ||
if (resp.content.length !== 1) { | ||
console.error('Unsupported response', resp.content) | ||
throw new Error('Unsupported response') | ||
} | ||
return { | ||
content: (resp.content[0] as AnthropicTypes.TextBlock).text, | ||
} | ||
} | ||
|
||
export async function activate(context: novachat.PluginContext) { | ||
const createClient = async () => { | ||
return new Anthropic({ | ||
apiKey: await novachat.setting.get('anthropic.apiKey'), | ||
defaultHeaders: { | ||
'anthropic-dangerous-direct-browser-access': 'true', | ||
}, | ||
}) | ||
} | ||
await novachat.model.registerProvider({ | ||
name: 'Anthropic', | ||
models: [ | ||
{ id: 'claude-3-5-sonnet-20240620', name: 'Claude 3.5 Sonnet' }, | ||
{ id: 'claude-3-opus-20240229', name: 'Claude 3 Opus' }, | ||
{ id: 'claude-3-sonnet-20240229', name: 'Claude 3 Sonnet' }, | ||
{ id: 'claude-3-haiku-20240307', name: 'Claude 3 Haiku' }, | ||
], | ||
async invoke(query) { | ||
const client = await createClient() | ||
return parseResponse( | ||
await client.messages.create( | ||
(await parseReq( | ||
query, | ||
false, | ||
)) as AnthropicTypes.MessageCreateParamsNonStreaming, | ||
), | ||
) | ||
}, | ||
async *stream(query) { | ||
const client = await createClient() | ||
const stream = await client.messages.create( | ||
(await parseReq( | ||
query, | ||
true, | ||
)) as AnthropicTypes.MessageCreateParamsStreaming, | ||
) | ||
for await (const it of stream) { | ||
if (it.type === 'content_block_delta') { | ||
if (it.delta.type !== 'text_delta') { | ||
throw new Error('Unsupported delta type') | ||
} | ||
yield { | ||
content: it.delta.text, | ||
} | ||
} | ||
} | ||
}, | ||
}) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
{ | ||
"id": "novachat.anthropic", | ||
"name": "Anthropic", | ||
"description": "Anthropic Provider", | ||
"version": "0.1.0", | ||
"author": "NovaChat", | ||
"configuration": { | ||
"title": "Anthropic", | ||
"properties": { | ||
"anthropic.apiKey": { | ||
"type": "string", | ||
"description": "Anthropic API Key", | ||
"default": "" | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
function arrayBufferToBase64(buffer: ArrayBuffer): string { | ||
let binary = '' | ||
const bytes = new Uint8Array(buffer) | ||
for (let i = 0; i < bytes.byteLength; i++) { | ||
binary += String.fromCharCode(bytes[i]) | ||
} | ||
return btoa(binary) | ||
} | ||
|
||
export async function getImageAsBase64(imageUrl: string): Promise<{ | ||
media_type: string | ||
data: string | ||
}> { | ||
// 检查是否已经是 data URL | ||
if (imageUrl.startsWith('data:')) { | ||
const [header, data] = imageUrl.split(',') | ||
const media_type = header.split(':')[1].split(';')[0] | ||
return { media_type, data } | ||
} | ||
// 如果不是 data URL,则按原方法处理 | ||
const response = await fetch(imageUrl) | ||
const arrayBuffer = await response.arrayBuffer() | ||
// 将 ArrayBuffer 转换为 base64 | ||
const base64 = arrayBufferToBase64(arrayBuffer) | ||
return { | ||
media_type: response.headers.get('content-type') || 'image/jpeg', | ||
data: base64, | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
{ | ||
"compilerOptions": { | ||
"target": "ESNext", | ||
"lib": ["ESNext"], | ||
"outDir": "./dist", | ||
"skipLibCheck": true, | ||
"esModuleInterop": true, | ||
"strict": true, | ||
"module": "ESNext", | ||
"moduleResolution": "bundler", | ||
"sourceMap": true, | ||
"declaration": true, | ||
"declarationMap": true | ||
}, | ||
"include": ["src"] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters