0
0
Fork 0
mirror of https://github.com/discourse/discourse.git synced 2026-08-14 13:58:53 +08:00
discourse/plugins/discourse-ai/lib/completions/dialects/gemini.rb
Sam fa54f62348
FEATURE: extract text from document uploads for LLM prompts (#39634)
Document attachments (doc, docx, xls, xlsx, rtf, csv, md, txt) are now
converted to text before being included in LLM prompts, instead of
being forwarded as raw base64 payloads. PDFs remain the only format
sent as a raw upload, capped at 10MB.

New converters under lib/completions:

- DocToText shells out to antiword
- DocxToText parses OOXML directly with size and depth limits
- XlsToText shells out to xls2csv
- XlsxToText parses OOXML and shared strings into CSV-style text
- RtfToText is a custom RTF tokenizer with destination/group handling

Plain text formats (csv, md, txt) are read with a 1MB byte cap and
UTF-8 normalization. Extracted text is truncated to 100k characters,
with a preamble noting the original filename and size.

Dialect trimming now uses token-aware truncation against a per-message
budget so large extracted documents collapse cleanly under the prompt
limit, rather than the previous step-based slicing of raw content.

Other changes:

- LlmModel.normalize_attachment_types is shared with UploadEncoder and
  collapses "markdown" to "md" so the canonical extension is consistent
  across model config, UI defaults, and encoder output
- ai-llm-attachment-types adds csv, xls, xlsx to the default choices
- Locale strings clarify that vision controls images and
  allowed_attachment_types controls documents

---------

Co-authored-by: Rafael Silva <xfalcox@gmail.com>
2026-05-05 08:16:23 +10:00

237 lines
6.6 KiB
Ruby
Vendored

# frozen_string_literal: true
module DiscourseAi
module Completions
module Dialects
class Gemini < Dialect
class << self
def can_translate?(llm_model)
llm_model.provider == "google"
end
end
def strip_upload_markdown_mode
if llm_model.name.include?("image")
:all
else
:model_only
end
end
def native_tool_support?
!llm_model.lookup_custom_param("disable_native_tools")
end
def translate
# Gemini complains if we don't alternate model/user roles.
noop_model_response = { role: "model", parts: { text: "Ok." } }
messages = merge_tool_batches(super)
interleving_messages = []
previous_message = nil
system_instruction = nil
messages.each do |message|
if message[:role] == "system"
system_instruction = message[:content]
next
end
if previous_message
if (previous_message[:role] == "user" || previous_message[:role] == "function") &&
message[:role] == "user"
interleving_messages << noop_model_response.dup
end
end
interleving_messages << message
previous_message = message
end
if tool_choice == :none && interleving_messages.length > 0
interleving_messages << { role: "user", parts: { text: no_more_tool_calls_text_user } }
end
{ messages: interleving_messages, system_instruction: system_instruction }
end
def tools
return if prompt.tools.blank?
translated_tools =
prompt.tools.map do |t|
tool = { name: t.name, description: t.description }
tool[:parameters] = t.parameters_json_schema if t.parameters
tool
end
[{ function_declarations: translated_tools }]
end
def max_prompt_tokens
llm_model.max_prompt_tokens
end
protected
def calculate_message_token(context)
llm_model.tokenizer_class.size(context[:content].to_s + context[:name].to_s)
end
def beta_api?
@beta_api ||= !llm_model.name.start_with?("gemini-1.0")
end
def system_msg(msg)
content = msg[:content]
if !native_tool_support? && tools_dialect.instructions.present?
content = content.to_s + "\n\n#{tools_dialect.instructions}"
end
if beta_api?
{ role: "system", content: content }
else
{ role: "user", parts: { text: content } }
end
end
def model_msg(msg)
message_for_role("model", msg)
end
def user_msg(msg)
message_for_role("user", msg)
end
def message_for_role(role, msg)
content_array = []
content_array << "#{msg[:id]}: " if msg[:id]
content_array << msg[:content]
content_array.flatten!
content_array =
to_encoded_content_array(
content: content_array,
upload_encoder: ->(details) { upload_node(details) },
text_encoder: ->(text) { { text: text } },
allow_images: vision_support? && beta_api?,
allow_documents: true,
allowed_attachment_types: llm_model.allowed_attachment_types,
upload_filter: ->(encoded) { document_allowed?(encoded) },
)
if beta_api?
{ role:, parts: content_array }
else
{ role:, parts: content_array.first }
end
end
def image_node(details)
{ inlineData: { mimeType: details[:mime_type], data: details[:base64] } }
end
def upload_node(details)
return { text: details[:text] } if details[:text].present?
image_node(details)
end
def tool_call_msg(msg)
if native_tool_support?
call_details = JSON.parse(msg[:content], symbolize_names: true)
function_call = {
name: msg[:name] || call_details[:name],
args: call_details[:arguments],
}
part = { functionCall: function_call }
if (thought_sig = msg.dig(:provider_data, :thought_signature))
part[:thoughtSignature] = thought_sig
end
message =
if beta_api?
{ role: "model", parts: [part] }
else
{ role: "model", parts: part }
end
batch_id = msg.dig(:provider_data, :batch_id)
message[:batch_id] = batch_id if batch_id
message
else
super
end
end
def tool_msg(msg)
if native_tool_support?
part = {
functionResponse: {
name: msg[:name] || msg[:id],
response: {
content: msg[:content],
},
},
}
message =
if beta_api?
{ role: "function", parts: [part] }
else
{ role: "function", parts: part }
end
batch_id = msg.dig(:provider_data, :batch_id)
message[:batch_id] = batch_id if batch_id
message
else
super
end
end
def merge_tool_batches(messages)
merged = []
existing_batches = {}
messages.each do |message|
batch_id = message.delete(:batch_id)
parts = message[:parts]
if batch_id && parts
key = [batch_id, message[:role]]
normalized_parts = parts_array(parts)
if existing_batches[key]
existing_batches[key][:parts].concat(normalized_parts)
next
else
message[:parts] = normalized_parts
message[:_batch_id] = batch_id
existing_batches[key] = message
end
end
merged << message
end
merged.each do |message|
message.delete(:_batch_id)
next if beta_api?
if message[:parts].is_a?(Array) && message[:parts].length == 1
message[:parts] = message[:parts].first
end
end
merged
end
def parts_array(parts)
return parts if parts.is_a?(Array)
[parts]
end
end
end
end
end