summaryrefslogtreecommitdiff
path: root/src/claude.ts
blob: 377316e8b29a285e3b81abf179d223a92051fd71 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
import Claude from "@anthropic-ai/sdk";
import { RESPONSE_LENGTH } from "./logic/constants";
import type { AResult, ChatMessage, OChoice, OChunk, OMessage } from "./types";
import { BOOKWORM_SYS } from "./prompts";

type Message = Claude.Messages.MessageParam;

export default class Conversation {
  private tokenizer: (text: string) => number;
  private maxTokens: number;
  model: string = "claude-3-5-sonnet-20241022";
  constructor(
    maxTokens = 200_000,
    tokenizer: (text: string) => number = (text) => text.length / 3,
  ) {
    this.maxTokens = maxTokens;
    this.tokenizer = tokenizer;
  }
  public setModel(model: string) {
    this.model = model;
  }
  private mapMessages(input: ChatMessage[]): Message[] {
    return input.map((m) => {
      const role = m.author === "claude" ? "assistant" : "user";
      return { role, content: m.text };
    });
  }

  private mapMessagesR1(input: ChatMessage[]): Message[] {
    return input.reduce((acc: Message[], m, i) => {
      const prev = acc[i - 1];
      const role: any = m.author === "claude" ? "assistant" : "user";
      const msg = { role, content: m.text };
      if (prev?.role === role) acc[i - 1] = msg;
      else acc = [...acc, msg];
      return acc;
    }, []);
  }

  public async send(sys: string, input: ChatMessage[]) {
    const messages = this.mapMessages(input);
    const truncated = this.truncateHistory(messages);
    const res = await this.apiCall(sys, truncated);
    return res;
  }

  public async sendR1(input: ChatMessage[]) {
    const messages = this.mapMessagesR1(input);
    const truncated = this.truncateHistory(messages);
    const res = await this.apiCall("", truncated, true);
    return res;
  }
  public async sendDoc(data: string) {
    const sys = BOOKWORM_SYS;
    const msg: Message = {
      role: "user",
      content: [
        {
          type: "document",
          source: { type: "base64", data, media_type: "application/pdf" },
        },
        {
          type: "text",
          text: "Please analyze this according to your system prompt. Be thorough.",
        },
      ],
    };
    const res = await this.apiCall(sys, [msg]);
    return res;
  }

  public async stream(
    sys: string,
    input: ChatMessage[],
    handle: (c: any) => void,
  ) {
    const messages = this.mapMessages(input);
    const truncated = this.truncateHistory(messages);
    await this.apiCallStream(sys, truncated, handle);
  }

  public async streamR1(input: ChatMessage[], handle: (c: any) => void) {
    const messages = this.mapMessagesR1(input);
    const truncated = this.truncateHistory(messages);
    await this.apiCallStream("", truncated, handle, true);
  }

  private truncateHistory(messages: Message[]): Message[] {
    const totalTokens = messages.reduce((total, message) => {
      return total + this.tokenizer(message.content as string);
    }, 0);
    while (totalTokens > this.maxTokens && messages.length > 1) {
      messages.splice(0, 1);
    }
    return messages;
  }

  // TODO
  // https://docs.anthropic.com/en/api/messages-examples#putting-words-in-claudes-mouth
  private async apiCall(
    system: string,
    messages: Message[],
    isR1: boolean = false,
  ): Promise<AResult<string[]>> {
    try {
      const claud = new Claude();
      // const list = await claud.models.list();
      // console.log(list.data);
      const res = await claud.messages.create({
        model: this.model,
        max_tokens: RESPONSE_LENGTH,
        system,
        messages,
      });
      return {
        ok: res.content.reduce((acc: string[], item) => {
          if (item.type === "tool_use") return acc;
          else return [...acc, item.text];
        }, []),
      };
    } catch (e) {
      console.log(e, "error in claude api");
      return { error: `${e}` };
    }
  }

  private async apiCallStream(
    system: string,
    messages: Message[],
    handle: (c: any) => void,
    isR1: boolean = false,
  ): Promise<void> {
    try {
      const claud = new Claude();
      const stream = await claud.messages.create({
        model: this.model,
        max_tokens: RESPONSE_LENGTH,
        system,
        messages,
        stream: true,
      });

      for await (const part of stream) {
        if (part.type === "message_start") continue;
        if (part.type === "content_block_start") continue;
        if (part.type === "content_block_delta") {
          console.log("delta", part.delta);
          const delta: any = part.delta;
          handle(delta.text);
        }
      }
    } catch (e) {
      console.log(e, "error in claude api");
      handle(`Error streaming Claude, ${e}`);
    }
  }
}