11local utils = require (" src.utils" )
22
33--- @class Chat Accumulating chat history and usage
4- --- @field _ai table
4+ --- @field ai table
55--- @field model string
66--- @field settings table ?
77--- @field usage table
@@ -12,20 +12,19 @@ Chat.__index = Chat
1212
1313--- @param ai table
1414--- @param model string
15- --- @param system_prompt string ?
16- --- @param settings table ?
17- function Chat .new (ai , model , system_prompt , settings )
15+ --- @param opts table ? Containing **settings** and or **system_prompt**
16+ function Chat .new (ai , model , opts )
1817 local self = setmetatable ({}, Chat )
1918
20- self ._ai = ai
19+ self .ai = ai
2120 self .model = model
22- self .settings = settings or {}
21+ self .settings = opts and opts . settings or {}
2322 self .usage = { input = 0 , output = 0 }
2423 self .history = {}
25- self .system_prompt = system_prompt
24+ self .system_prompt = opts and opts . system_prompt
2625
2726 -- insert system prompt into chat history at the start if provided
28- local system_message = self ._ai .provider .construct_system_message (self .system_prompt )
27+ local system_message = self .ai .provider .construct_system_message (self .system_prompt )
2928 if system_message then -- some providers use system message as top-level arg
3029 table.insert (self .history , system_message )
3130 end
3736--- @param user_prompt string
3837--- @return string reply Full response text whether streamed or not
3938function Chat :say (user_prompt )
40- table.insert (self .history , self ._ai .provider .construct_user_message (user_prompt ))
41- local reply , input_tokens , output_tokens = self ._ai :call (self )
42- table.insert (self .history , self ._ai .provider .construct_assistant_message (reply ))
39+ table.insert (self .history , self .ai .provider .construct_user_message (user_prompt ))
40+ local reply , input_tokens , output_tokens = self .ai :call (self )
41+ table.insert (self .history , self .ai .provider .construct_assistant_message (reply ))
4342 self .usage .input = self .usage .input + input_tokens
4443 self .usage .output = self .usage .output + output_tokens
4544 return reply
4645end
4746
47+ --- Caculate model pricing from input and output tokens in USD
48+ --- @return number
4849function Chat :get_cost ()
49- return utils .calc_token_cost (self .model , self .usage , self ._ai .provider .pricing )
50+ return utils .calc_token_cost (self .model , self .usage , self .ai .provider .pricing )
5051end
5152
5253return Chat
0 commit comments