|
| 1 | +import logging |
| 2 | +from typing import override |
| 3 | + |
| 4 | +import openai |
| 5 | +from openai.types.chat import ChatCompletion |
| 6 | +from pydantic import BaseModel, Field |
| 7 | + |
| 8 | +from vectorcode.cli_utils import Config |
| 9 | +from vectorcode.rewriter.base import RewriterBase |
| 10 | + |
| 11 | +logger = logging.getLogger(name=__name__) |
| 12 | + |
| 13 | + |
| 14 | +class _NewQuery(BaseModel): |
| 15 | + keywords: list[str] = Field( |
| 16 | + description="Orthogonal keywords for the vector search." |
| 17 | + ) |
| 18 | + |
| 19 | + |
| 20 | +class OpenAIRewriter(RewriterBase): |
| 21 | + def __init__(self, config: Config) -> None: |
| 22 | + super().__init__(config) |
| 23 | + self.client = openai.Client( |
| 24 | + **self.config.rewriter_params.get("client_kwargs", {}) |
| 25 | + ) |
| 26 | + self.system_prompt = """ |
| 27 | +Role: |
| 28 | + You are a code-aware rewriter that improves technical queries/docs for retrieval. Never assume a programming language unless the input explicitly includes syntax, APIs, or error messages from one. |
| 29 | +Rules: |
| 30 | +
|
| 31 | + For Queries: |
| 32 | +
|
| 33 | + Fix unambiguous typos (e.g., "Pytoch" → "PyTorch"). |
| 34 | + |
| 35 | + Omit langauge-specific keywords (e.g., "async def foo():" → "foo") |
| 36 | +
|
| 37 | + For Docs/Code: |
| 38 | +
|
| 39 | + Clarify ambiguous terms only with explicit context. |
| 40 | +
|
| 41 | + Never modify code logic or variable names. |
| 42 | +
|
| 43 | +Anti-Goals: |
| 44 | +
|
| 45 | + No language assumptions. |
| 46 | +
|
| 47 | + No code changes. |
| 48 | +
|
| 49 | + No hallucinations. |
| 50 | +""" |
| 51 | + |
| 52 | + @override |
| 53 | + async def rewrite(self, original_query: list[str]): |
| 54 | + comp: ChatCompletion = self.client.beta.chat.completions.parse( |
| 55 | + messages=[ |
| 56 | + {"role": "system", "content": self.system_prompt}, |
| 57 | + {"role": "user", "content": " ".join(original_query)}, |
| 58 | + ], |
| 59 | + response_format=_NewQuery, |
| 60 | + **self.config.rewriter_params.get("completion_kwargs", {}), |
| 61 | + ) |
| 62 | + if comp is None or len(comp.choices) == 0: |
| 63 | + logger.info("Recieved no rewritten query. Fallingback to original_query.") |
| 64 | + return original_query |
| 65 | + choice = comp.choices[0].message |
| 66 | + if choice and choice.parsed: |
| 67 | + print(choice.parsed) |
| 68 | + logger.debug(f"Rewritten queries to: {choice.parsed}") |
| 69 | + return choice.parsed.keywords |
| 70 | + else: |
| 71 | + logger.warning( |
| 72 | + f"Failed to parse structured output: {choice.refusal}. Fallingback to original_query." |
| 73 | + ) |
| 74 | + return original_query |
0 commit comments