Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add TokenCount #80

Merged
merged 1 commit into from
Jul 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions ai.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,13 @@ type ChatStream interface {
Close() error
}

type TokenCount struct {
Prompt int
Result int
Total int
}

type ChatResponse interface {
Results() []string
TokenCount() TokenCount
}
16 changes: 16 additions & 0 deletions chatgpt/chatgpt.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,22 @@ func (resp *ChatResponse[Response]) Results() (res []string) {
return
}

func (resp *ChatResponse[Response]) TokenCount() (res ai.TokenCount) {
switch v := any(resp.resp).(type) {
case openai.ChatCompletionResponse:
res.Prompt = v.Usage.PromptTokens
res.Result = v.Usage.CompletionTokens
res.Total = v.Usage.TotalTokens
case openai.ChatCompletionStreamResponse:
if usage := v.Usage; usage != nil {
res.Prompt = usage.PromptTokens
res.Result = usage.CompletionTokens
res.Total = usage.TotalTokens
}
}
return
}

func (resp *ChatResponse[Response]) String() string {
if res := resp.Results(); len(res) > 0 {
return res[0]
Expand Down
9 changes: 9 additions & 0 deletions gemini/gemini.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,15 @@ func (resp *ChatResponse) Results() (res []string) {
return
}

func (resp *ChatResponse) TokenCount() (res ai.TokenCount) {
if usage := resp.UsageMetadata; usage != nil {
res.Prompt = int(usage.PromptTokenCount)
res.Result = int(usage.CandidatesTokenCount)
res.Total = int(usage.TotalTokenCount)
}
return
}

func (resp *ChatResponse) String() string {
if res := resp.Results(); len(res) > 0 {
return res[0]
Expand Down