I was need to use a custom injection script via LiteLLM in order to use Qwen models in Discourse. If it is possible to you, I can share it.
@singi2016cn Here you go, it is scoped to their translate models. Note it was vibe-coded and I hope you understand it and can improve and adapt it to your actual use-case:
import json
import logging
from litellm.integrations.custom_logger import CustomLogger
QWEN_MT_MODEL_NAMES = {"qwen-translate"}
def extract_translation_request(messages):
"""
discourse-ai sends multi-turn few-shot examples followed by the real
request as the LAST user message, JSON-encoded as:
{"content": "<text to translate>", "target_locale": "<code>"}
Returns (text_to_translate, target_locale) or (None, None) if not found.
"""
user_messages = [m for m in messages if m.get("role") == "user"]
if not user_messages:
return None, None
last = user_messages[-1]
content = last.get("content", "")
try:
parsed = json.loads(content)
text = parsed.get("content")
locale = parsed.get("target_locale")
if text and locale:
return text, locale
except (json.JSONDecodeError, TypeError):
pass
return None, None
class QwenMTHook(CustomLogger):
async def async_pre_call_hook(self, user_api_key_dict, cache, data, call_type):
model = data.get("model", "")
if model not in QWEN_MT_MODEL_NAMES:
return data
messages = data.get("messages", [])
text, target_locale = extract_translation_request(messages)
if text is None:
logging.warning(
"[QwenMT] could not extract translation request, passing through unmodified"
)
return data
# Qwen-MT: exactly one user message, no system/few-shot examples
data["messages"] = [{"role": "user", "content": text}]
# Strip response_format — Qwen-MT can't honor it, and DashScope
# rejects json_object mode unless "json" appears in the prompt
data.pop("response_format", None)
extra_body = data.get("extra_body") or {}
extra_body["translation_options"] = {
"source_lang": "auto",
"target_lang": target_locale,
}
data["extra_body"] = extra_body
# Flag for post-call hook so we know to wrap the plain response
metadata = data.get("metadata") or {}
metadata["qwen_mt_wrap_output"] = True
data["metadata"] = metadata
logging.warning(
"[QwenMT] translating to=%s text=%.80s",
target_locale,
text,
)
return data
async def async_post_call_success_hook(self, data, user_api_key_dict, response):
metadata = data.get("metadata") or {}
if not metadata.get("qwen_mt_wrap_output"):
return response
try:
translated_text = response.choices[0].message.content
wrapped = json.dumps({"output": translated_text})
response.choices[0].message.content = wrapped
logging.warning("[QwenMT] wrapped output=%.80s", wrapped)
except (AttributeError, IndexError) as e:
logging.warning("[QwenMT] failed to wrap response: %s", e)
return response
proxy_handler_instance = QwenMTHook()