2023-11-23 10:58:54 -05:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module DiscourseAi
|
|
|
|
module Completions
|
|
|
|
module Dialects
|
2023-12-18 16:06:01 -05:00
|
|
|
class Claude < Dialect
|
|
|
|
class << self
|
|
|
|
def can_translate?(model_name)
|
|
|
|
%w[claude-instant-1 claude-2].include?(model_name)
|
|
|
|
end
|
|
|
|
|
|
|
|
def tokenizer
|
|
|
|
DiscourseAi::Tokenizer::AnthropicTokenizer
|
|
|
|
end
|
2023-11-23 10:58:54 -05:00
|
|
|
end
|
|
|
|
|
2023-12-18 16:06:01 -05:00
|
|
|
def translate
|
|
|
|
claude_prompt = +"Human: #{prompt[:insts]}\n"
|
2023-11-23 10:58:54 -05:00
|
|
|
|
2023-12-18 16:06:01 -05:00
|
|
|
claude_prompt << build_tools_prompt if prompt[:tools]
|
2023-11-23 10:58:54 -05:00
|
|
|
|
2023-12-18 16:06:01 -05:00
|
|
|
claude_prompt << build_examples(prompt[:examples]) if prompt[:examples]
|
2023-11-23 10:58:54 -05:00
|
|
|
|
2023-12-18 16:06:01 -05:00
|
|
|
claude_prompt << conversation_context if prompt[:conversation_context]
|
|
|
|
|
|
|
|
claude_prompt << "#{prompt[:input]}\n"
|
|
|
|
|
|
|
|
claude_prompt << "#{prompt[:post_insts]}\n" if prompt[:post_insts]
|
2023-11-23 10:58:54 -05:00
|
|
|
|
2023-12-18 20:04:15 -05:00
|
|
|
claude_prompt << "Assistant:"
|
|
|
|
claude_prompt << " #{prompt[:final_insts]}:" if prompt[:final_insts]
|
|
|
|
claude_prompt << "\n"
|
2023-11-23 10:58:54 -05:00
|
|
|
end
|
|
|
|
|
2023-12-18 16:06:01 -05:00
|
|
|
def max_prompt_tokens
|
|
|
|
50_000
|
|
|
|
end
|
|
|
|
|
|
|
|
def conversation_context
|
|
|
|
return "" if prompt[:conversation_context].blank?
|
|
|
|
|
2024-01-04 08:44:07 -05:00
|
|
|
clean_context = prompt[:conversation_context].select { |cc| cc[:type] != "tool_call" }
|
2024-01-04 16:15:34 -05:00
|
|
|
flattened_context = flatten_context(clean_context)
|
|
|
|
trimmed_context = trim_context(flattened_context)
|
2023-12-18 16:06:01 -05:00
|
|
|
|
|
|
|
trimmed_context
|
|
|
|
.reverse
|
|
|
|
.reduce(+"") do |memo, context|
|
|
|
|
memo << (context[:type] == "user" ? "Human:" : "Assistant:")
|
|
|
|
|
|
|
|
if context[:type] == "tool"
|
|
|
|
memo << <<~TEXT
|
|
|
|
|
|
|
|
<function_results>
|
|
|
|
<result>
|
|
|
|
<tool_name>#{context[:name]}</tool_name>
|
|
|
|
<json>
|
|
|
|
#{context[:content]}
|
|
|
|
</json>
|
|
|
|
</result>
|
|
|
|
</function_results>
|
|
|
|
TEXT
|
|
|
|
else
|
|
|
|
memo << " " << context[:content] << "\n"
|
|
|
|
end
|
|
|
|
|
|
|
|
memo
|
|
|
|
end
|
2023-11-23 10:58:54 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def build_examples(examples_arr)
|
|
|
|
examples_arr.reduce("") do |memo, example|
|
|
|
|
memo += "<example>\nH: #{example[0]}\nA: #{example[1]}\n</example>\n"
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|