tools.refine_prompt module

Iterative prompt refinement via Nemotron on OpenRouter.

async tools.refine_prompt.run(prompt, *, ctx=None)[source]

Iteratively refine a draft prompt through a multi-pass compilation pipeline.

Runs the input prompt through _ITERATIONS (3) successive passes against the Nemotron model on OpenRouter, each time feeding the previous pass’s output back in as the new draft, so the prompt is progressively hardened into a dense, structured, “compiled” directive. This is the entry point for the refine_prompt tool. Empty or whitespace-only input short-circuits with an error, and an empty model response on any pass leaves the prior text untouched rather than discarding progress.

It resolves the OpenRouter API key by preferring the caller’s own key (via tools.manage_api_keys.get_user_api_key, looked up against ctx.redis by ctx.user_id/ctx.channel_id) and otherwise falling back to the configured default key from ctx.config; when the default key is used it enforces a daily per-user quota through default_key_limit_applies/check_default_key_limit (limit 50) and, on success, records consumption via increment_default_key_usage (both keyed on ctx.user_id in Redis). The actual refinement work is delegated to OpenRouterClient.chat over HTTPS using _SYSTEM_PROMPT as the system message; missing-key and limit cases return structured errors built by missing_api_key_error/default_key_limit_error.

Called by the tool-execution framework rather than any direct caller: a grep for refine_prompt( finds no internal call sites, and tool_loader.py discovers this module-level run via getattr(module, "run") and registers it as the tool handler, so it is dispatched dynamically by name when the bot invokes the refine_prompt tool.

Parameters:
  • prompt (str) – The raw or draft prompt text to refine and optimize.

  • ctx (ToolContext | None) – Optional tool context supplying config (default OpenRouter key), redis (key lookup and quota bookkeeping), user_id and channel_id (per-user key resolution and rate limiting).

Returns:

On success, the fully compiled prompt from the final iteration. On failure, a JSON-encoded object with an error key (missing prompt, missing API key, or exceeded default-key limit); if a mid-pipeline iteration raises, the JSON also carries partial_result with the best prompt produced so far.

Return type:

str