# Pull Request Template ## Description we were getting 403, 401 errors on `translate_query` on langfuse and sentry This happened because, we use the customer's openai key if they have BYOK But translation is something they never opt in so we should not use their quota for it. This PR addresses the issue. ## Type of change - [x] Bug fix (non-breaking change which fixes an issue) ## How Has This Been Tested? Please describe the tests that you ran to verify your changes. Provide instructions so we can reproduce. Please also list any relevant details for your test configuration. locally ## Checklist: - [x] My code follows the style guidelines of this project - [x] I have performed a self-review of my code - [x] I have commented on my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [x] My changes generate no new warnings - [x] I have added tests that prove my fix is effective or that my feature works - [x] New and existing unit tests pass locally with my changes - [x] Any dependent changes have been merged and published in downstream modules
56 lines
1.5 KiB
Ruby
56 lines
1.5 KiB
Ruby
class Captain::Llm::TranslateQueryService < Captain::BaseTaskService
|
|
MODEL = 'gpt-4.1-nano'.freeze
|
|
|
|
pattr_initialize [:account!]
|
|
|
|
def translate(query, target_language:)
|
|
return query if query_in_target_language?(query)
|
|
|
|
messages = [
|
|
{ role: 'system', content: system_prompt(target_language) },
|
|
{ role: 'user', content: query }
|
|
]
|
|
|
|
response = make_api_call(model: MODEL, messages: messages)
|
|
return query if response[:error]
|
|
|
|
response[:message].strip
|
|
rescue StandardError => e
|
|
Rails.logger.warn "TranslateQueryService failed: #{e.message}, falling back to original query"
|
|
query
|
|
end
|
|
|
|
private
|
|
|
|
def event_name
|
|
'translate_query'
|
|
end
|
|
|
|
# Translation is an internal operation, not customer-initiated.
|
|
# Prefer the system key; fall back to the account's hook key for self-hosted setups without one.
|
|
def api_key
|
|
@api_key ||= system_api_key.presence || openai_hook&.settings&.dig('api_key')
|
|
end
|
|
|
|
def query_in_target_language?(query)
|
|
detector = CLD3::NNetLanguageIdentifier.new(0, 1000)
|
|
result = detector.find_language(query)
|
|
|
|
result.reliable? && result.language == account_language_code
|
|
rescue StandardError
|
|
false
|
|
end
|
|
|
|
def account_language_code
|
|
account.locale&.split('_')&.first
|
|
end
|
|
|
|
def system_prompt(target_language)
|
|
<<~SYSTEM_PROMPT_MESSAGE
|
|
You are a helpful assistant that translates queries from one language to another.
|
|
Translate the query to #{target_language}.
|
|
Return just the translated query, no other text.
|
|
SYSTEM_PROMPT_MESSAGE
|
|
end
|
|
end
|