Skip to content

Commit

Permalink
Add token usage data to RunCompleted event
Browse files Browse the repository at this point in the history
  • Loading branch information
jwilger committed Feb 22, 2024
1 parent c31231f commit 8d82ed9
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 4 deletions.
7 changes: 5 additions & 2 deletions lib/gpt_agent.ex
Original file line number Diff line number Diff line change
Expand Up @@ -359,7 +359,7 @@ defmodule GptAgent do
handle_run_status(status, id, response, state)
end

defp handle_run_status("completed", id, _response, %__MODULE__{} = state) do
defp handle_run_status("completed", id, response, %__MODULE__{} = state) do
log("Run ID #{inspect(id)} completed")

state
Expand All @@ -368,7 +368,10 @@ defmodule GptAgent do
RunCompleted.new!(
id: id,
thread_id: state.thread_id,
assistant_id: state.assistant_id
assistant_id: state.assistant_id,
prompt_tokens: response |> Map.get("usage", %{}) |> Map.get("prompt_tokens", 0),
completion_tokens: response |> Map.get("usage", %{}) |> Map.get("completion_tokens", 0),
total_tokens: response |> Map.get("usage", %{}) |> Map.get("total_tokens", 0)
)
)
|> noreply({:continue, :read_messages})
Expand Down
3 changes: 3 additions & 0 deletions lib/gpt_agent/events/run_completed.ex
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,8 @@ defmodule GptAgent.Events.RunCompleted do
field :id, Types.run_id()
field :thread_id, Types.thread_id()
field :assistant_id, Types.assistant_id()
field :prompt_tokens, non_neg_integer()
field :completion_tokens, non_neg_integer()
field :total_tokens, non_neg_integer()
end
end
12 changes: 10 additions & 2 deletions test/gpt_agent_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -632,7 +632,12 @@ defmodule GptAgentTest do
"instructions" => nil,
"tools" => [],
"file_ids" => [],
"metadata" => %{}
"metadata" => %{},
"usage" => %{
"prompt_tokens" => 1,
"completion_tokens" => 2,
"total_tokens" => 3
}
})
)
end)
Expand All @@ -643,7 +648,10 @@ defmodule GptAgentTest do
%RunCompleted{
id: ^run_id,
thread_id: ^thread_id,
assistant_id: ^assistant_id
assistant_id: ^assistant_id,
prompt_tokens: 1,
completion_tokens: 2,
total_tokens: 3
}},
5_000
end
Expand Down

0 comments on commit 8d82ed9

Please sign in to comment.