index.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { Anthropic } from "@anthropic-ai/sdk"
  2. import { ApiConfiguration, ApiModelId, ModelInfo } from "../shared/api"
  3. import { AnthropicHandler } from "./anthropic"
  4. import { AwsBedrockHandler } from "./bedrock"
  5. import { OpenRouterHandler } from "./openrouter"
  6. export interface ApiHandler {
  7. createMessage(
  8. systemPrompt: string,
  9. messages: Anthropic.Messages.MessageParam[],
  10. tools: Anthropic.Messages.Tool[]
  11. ): Promise<Anthropic.Messages.Message>
  12. createUserReadableRequest(
  13. userContent: Array<
  14. | Anthropic.TextBlockParam
  15. | Anthropic.ImageBlockParam
  16. | Anthropic.ToolUseBlockParam
  17. | Anthropic.ToolResultBlockParam
  18. >
  19. ): any
  20. getModel(): { id: ApiModelId; info: ModelInfo }
  21. }
  22. export function buildApiHandler(configuration: ApiConfiguration): ApiHandler {
  23. const { apiProvider, ...options } = configuration
  24. switch (apiProvider) {
  25. case "anthropic":
  26. return new AnthropicHandler(options)
  27. case "openrouter":
  28. return new OpenRouterHandler(options)
  29. case "bedrock":
  30. return new AwsBedrockHandler(options)
  31. default:
  32. return new AnthropicHandler(options)
  33. }
  34. }
  35. export function withoutImageData(
  36. userContent: Array<
  37. | Anthropic.TextBlockParam
  38. | Anthropic.ImageBlockParam
  39. | Anthropic.ToolUseBlockParam
  40. | Anthropic.ToolResultBlockParam
  41. >
  42. ): Array<
  43. Anthropic.TextBlockParam | Anthropic.ImageBlockParam | Anthropic.ToolUseBlockParam | Anthropic.ToolResultBlockParam
  44. > {
  45. return userContent.map((part) => {
  46. if (part.type === "image") {
  47. return { ...part, source: { ...part.source, data: "..." } }
  48. } else if (part.type === "tool_result" && typeof part.content !== "string") {
  49. return {
  50. ...part,
  51. content: part.content?.map((contentPart) => {
  52. if (contentPart.type === "image") {
  53. return { ...contentPart, source: { ...contentPart.source, data: "..." } }
  54. }
  55. return contentPart
  56. }),
  57. }
  58. }
  59. return part
  60. })
  61. }