Skip to content

fix(pr_agent/tools/pr_similar_issue.py): migrating embeddings to the openai v1 client - #2726

Merged
IsmaelMartinez merged 5 commits into
The-PR-Agent:mainfrom
dwin-gharibi:fix/similar-issue-openai-v1-api
Aug 30, 2026
Merged

IsmaelMartinez merged 5 commits into
The-PR-Agent:mainfrom
dwin-gharibi:fix/similar-issue-openai-v1-api

Conversation

@dwin-gharibi

Copy link
Copy Markdown
Contributor

Closes #2725.

Description

requirements.txt pins openai>=1.55.3 (installed: 2.54.0), but pr_similar_issue.py still calls openai.Embedding.create and sets openai.api_key — the v0 interface removed in openai 1.0.

Root cause

Nine call sites (lines 279, 283, 460, 463, 470, 556, 559, 655, 658, 665) use the openai v0
interface. openai.Embedding and module-level openai.api_key were removed in openai 1.0; the
replacement is OpenAI(api_key=...).embeddings.create(input=..., model=...) with attribute access
on the response (response.data[i].embedding) instead of subscripting.

The bare except: handlers around the indexing paths turn the hard failure into silent data
corruption, which is why the breakage has gone unnoticed.

The fix

  • A single _embed() helper builds an openai.OpenAI client and calls client.embeddings.create,
    returning [record.embedding for record in response.data].
  • The query path and all three indexing paths call it, so the v0 interface is gone from the module.
  • The bare except: handlers become except Exception, log the underlying error, and — when
    every item fails — raise instead of indexing an all-zero vector set. A partial failure still
    degrades to [0] * 1536 for the affected items only, as before.

Behaviour change

Before /similar_issue raises APIRemovedInV1; indexing silently stores all-zero vectors
After /similar_issue uses the pinned openai client; a total embedding failure raises instead of corrupting the index

Files changed

pr_agent/tools/pr_similar_issue.py | 72 +++++++++++++++++++++++---------------
 1 file changed, 43 insertions(+), 29 deletions(-)

Testing

New regression coverage in tests/unittest/test_similar_issue_embeddings.py — 4 tests, each written to fail
without the fix:

$ PYTHONPATH=. pytest tests/unittest/test_similar_issue_embeddings.py
4 passed

Proven to be a genuine regression test: with every changed pr_agent/ file reverted to its
origin/main version and the new test file left in place, the suite fails. It only passes
with the fix applied.

Full pipeline, reproduced locally exactly as .github/workflows/build-and-test.yaml runs it:

docker build -f docker/Dockerfile --target test .
docker run --rm <image> pytest -v tests/unittest
-> 1965 passed, 1 skipped, 1 xfailed

on python:3.12.13-slim — no failures.

Also checked:

  • pytest tests/unittest — no new failures vs main
  • ruff — no new findings vs main; isort — clean on every file touched
  • No new code comments authored

Risk / compatibility

The embedding request itself is unchanged (same model, same inputs). The only behaviour change
beyond the API migration is that a total embedding failure now raises rather than indexing
useless vectors — a failure that previously produced a silently broken index.

pinecone, pinecone-datasets and lancedb remain commented out of requirements.txt, so the
backends still have to be installed separately; that is out of scope for this fix.

Checklist

  • Focused on a single fix
  • Existing tests pass
  • New regression tests added, proven to fail without the fix
  • No new dependencies
  • Reviewed by a maintainer

Copilot AI lite review requested due to automatic review settings August 21, 2026 11:47

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@qodo-code-review

Copy link
Copy Markdown
Contributor

PR Summary by Qodo

Migrate similar-issue embeddings to OpenAI v1 client and guard against all-zero indexing

🐞 Bug fix 🧪 Tests 🕐 20-40 Minutes

Grey Divider

AI Description

• Replace removed OpenAI v0 embeddings API usage with a v1 client helper
• Improve embedding failure handling to avoid silently indexing all-zero vectors
• Add regression tests to prevent reintroduction of v0 API patterns
Diagram

graph TD
  A["PRSimilarIssue"] --> B["Issue query"] --> C["_embed()"] --> D{{"OpenAI v1 API"}}
  A --> E["Indexing paths"] --> C
  C --> F[("Vector stores")]
  T("Embedding tests") --> C
  subgraph Legend
    direction LR
    _svc["Service/module"] ~~~ _ext{{"External API"}} ~~~ _db[("Store")] ~~~ _test("Tests")
  end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Reuse a singleton OpenAI client
  • ➕ Avoids rebuilding the client repeatedly in tight loops
  • ➕ Central place to configure timeouts/retries once
  • ➖ Requires lifecycle management (module-global or injected dependency)
  • ➖ Harder to unit test if not injected cleanly
2. Add explicit retry/backoff for partial embedding failures
  • ➕ Reduces zero-vector fallbacks under transient API/network issues
  • ➕ More predictable indexing quality
  • ➖ More complexity and longer indexing time
  • ➖ Needs careful tuning to avoid runaway retries
3. Fail fast on any embedding error during indexing
  • ➕ Never writes low-quality data to the index
  • ➕ Simplifies correctness reasoning
  • ➖ Less resilient; a single bad record can block indexing
  • ➖ Behavior change may be too strict for current users

Recommendation: The chosen approach (central _embed() using OpenAI v1, plus raising only when all embeddings fail) is a good balance of compatibility and resilience. Consider a follow-up to reuse a shared client and/or add controlled retries if indexing performance or transient failures become common.

Files changed (2) +107 / -29

Bug fix (1) +43 / -29
pr_similar_issue.pySwitch embeddings to OpenAI v1 client via shared helper and safer failures +43/-29

Switch embeddings to OpenAI v1 client via shared helper and safer failures

• Introduces a single _embed() helper using openai.OpenAI(...).embeddings.create() and updates query + indexing call sites to use it. Replaces bare except blocks with exception logging and adds a guard that raises when every embedding in a batch fails, preventing silent all-zero vector indexing.

pr_agent/tools/pr_similar_issue.py

Tests (1) +64 / -0
test_similar_issue_embeddings.pyAdd regression tests for v1 embeddings usage and all-zero indexing guard +64/-0

Add regression tests for v1 embeddings usage and all-zero indexing guard

• Adds unit tests that assert the module no longer references openai.Embedding.create or openai.api_key. Verifies _embed() uses the v1 client interface and raises on total embedding failure instead of allowing indexing to proceed with meaningless zero vectors.

tests/unittest/test_similar_issue_embeddings.py

@qodo-code-review

qodo-code-review Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. Single quotes in logger.error ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
Newly added logging code uses single-quoted string literals, violating the required double-quote
convention and likely causing style/lint failures.
Code

pr_agent/tools/pr_similar_issue.py[R469-470]

+            get_logger().error('Failed to embed entire list, embedding one by one...',
+                               artifact={'error': str(e)})
Relevance

●●● Strong

Recent reviews accepted double-quote corrections for newly added Python literals under this
convention.

PR-#2677
PR-#2703

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 2694657 requires double quotes for Python string literals; the added
get_logger().error(...) call uses single quotes for both the message and the artifact dict key.

Rule 2694657: Use double quotes for all Python string literals
pr_agent/tools/pr_similar_issue.py[469-470]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
New code uses single-quoted Python string literals (e.g., in `get_logger().error(...)` and `artifact={'error': ...}`), but the project requires double quotes for string literals.

## Issue Context
This is a style compliance rule and may trigger Ruff/formatting CI failures.

## Fix Focus Areas
- pr_agent/tools/pr_similar_issue.py[469-470]
- pr_agent/tools/pr_similar_issue.py[568-569]
- pr_agent/tools/pr_similar_issue.py[670-671]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. OpenAI client re-created repeatedly ✓ Resolved 🐞 Bug ➹ Performance
Description
_embed() constructs a new openai.OpenAI(...) client on every call, and the indexing fallback
loops call _embed([text]) per item, causing repeated client construction and connection setup
during degraded-path indexing. This can significantly slow indexing and increase resource usage when
batch embedding fails.
Code

pr_agent/tools/pr_similar_issue.py[R18-21]

+def _embed(texts: List[str]) -> List[List[float]]:
+    """Embed texts with the openai>=1.0 client that requirements.txt pins."""
+    client = openai.OpenAI(api_key=get_settings().openai.key)
+    response = client.embeddings.create(input=texts, model=MODEL)
Relevance

●● Moderate

Plausible performance issue, but no closely matching accepted or rejected precedent was found.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The helper _embed() unconditionally instantiates a new OpenAI client, and the fallback indexing
loop calls _embed([text]) for each text, multiplying client constructions in the degraded path.

pr_agent/tools/pr_similar_issue.py[18-22]
pr_agent/tools/pr_similar_issue.py[469-481]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`_embed()` creates a new `openai.OpenAI` client every time it’s called. In the one-by-one fallback loops, this means a new client is created per text item, which is a performance regression versus the prior v0 usage and can make indexing extremely slow under partial outage/rate-limit conditions.

### Issue Context
The PR introduces `_embed()` and replaces all embedding call sites with it. Indexing paths intentionally fall back to embedding one item at a time when the batch call fails; with the current helper, that fallback repeatedly constructs the OpenAI client.

### Fix Focus Areas
- pr_agent/tools/pr_similar_issue.py[18-22]
- pr_agent/tools/pr_similar_issue.py[469-481]
- pr_agent/tools/pr_similar_issue.py[567-580]
- pr_agent/tools/pr_similar_issue.py[669-682]

### Suggested implementation direction
- Introduce a small cached client factory (e.g., `@lru_cache` keyed by API key) and have `_embed()` call it, or
- Construct a client once per indexing method and pass it into `_embed(client, texts)`.

Either approach ensures the fallback loop reuses a single client instance instead of creating one per text.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Informational

3. sk-test hard-coded in test ✓ Resolved 📘 Rule violation ⛨ Security
Description
The new test hard-codes a token-like API key value (sk-test), which appears to be a credential and
should not be committed in source.
Code

tests/unittest/test_similar_issue_embeddings.py[11]

+        key = "sk-test"
Relevance

● Weak

Similar test-only credential-like placeholders were rejected when clearly fake or redacted, not real
secrets.

PR-#2484

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 2694653 forbids committing secrets/credentials (including values that look like API
keys). The added test stub contains a hard-coded key-like value.

Rule 2694653: Do not store secrets or credentials in source code or config files
tests/unittest/test_similar_issue_embeddings.py[9-12]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A token-like API key value is hard-coded in the test (`key = "sk-test"`), which violates the rule against storing secrets/credentials in the repository.

## Issue Context
Even if intended as a stub, `sk-*` patterns commonly match secret scanners and can be treated as credentials.

## Fix Focus Areas
- tests/unittest/test_similar_issue_embeddings.py[9-12]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


  • Author self-review: I have reviewed the code review findings, and addressed the relevant ones.

Grey Divider

Context sources
✅ Compliance rules (platform): 34 rules
Review mode: 🚀 Fast: The latest push is a localized embedding-client caching change with limited call-site impact and focused regression tests, so one light review should confidently assess it.

Grey Divider

Tip of the day
💡 Did you know, you can enable the Remediation agent and Qodo fixes findings in a dedicated fix PR

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@qodo-code-review

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit da48d5f

Comment thread pr_agent/tools/pr_similar_issue.py Outdated
except Exception:
failures += 1
embeds.append([0] * 1536)
if failures == len(list_to_encode):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This block is identical at 489, 588 and 690, and nothing in the suite executes it. Lifting it up beside _embed fixes both at once:

def _embed_with_fallback(texts: List[str]) -> List[List[float]]:
    """Embed a list, falling back to one by one, and refuse to return an all-zero set."""
    try:
        return _embed(texts)
    except Exception as e:
        get_logger().error("Failed to embed entire list, embedding one by one...",
                           artifact={"error": str(e)})
        embeds = []
        failures = 0
        for text in texts:
            try:
                embeds.append(_embed([text])[0])
            except Exception:
                failures += 1
                embeds.append([0] * 1536)
        if failures == len(texts):
            raise RuntimeError(
                "Failed to embed any issue text; refusing to index all-zero vectors") from e
        return embeds

Each of the three sites then reads embeds = _embed_with_fallback(list_to_encode). I applied exactly this and the merged suite stayed at 2042 passed.

assert calls["model"] == psi.MODEL


def test_a_total_embedding_failure_raises_instead_of_indexing_zero_vectors(monkeypatch):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This asserts that _embed propagates a client-construction error, not the indexing guard the name describes. That guard never executes in the suite. With the helper above it becomes two short tests, both of which I ran green: a total failure raises, and a partial failure zeroes only the failing item.

@IsmaelMartinez
IsmaelMartinez dismissed their stale review August 30, 2026 21:00

pushing the changes myself

@qodo-code-review

qodo-code-review Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Code Review by Qodo

Grey Divider

Sorry, something went wrong

We weren't able to complete the code review on our side. Please try again manually by commenting /agentic_review on this PR.

Grey Divider

Qodo Logo

@IsmaelMartinez IsmaelMartinez left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the diagnosis here, and sorry it sat.

Rather than leave a live breakage waiting on a round trip, I pushed the lift itself as ff572e34. _embed_with_fallback now sits beside _embed, so the three byte-identical blocks at 477, 576 and 678 each read one line. Your all-zero guard is unchanged, just in one place instead of three. The test at line 58 became two, because it was asserting that _embed propagates a client-construction error rather than the indexing guard its name described: one case for a total failure raising, one for a partial failure zeroing only the item that failed.

Your commit is still an ancestor and it went up as a fast-forward, so nothing of yours was rewritten. 2763 passed against 2757 on main, ruff clean, and all six error out on revert.

Merging, which closes #2725. The breakage was real: main still calls openai.Embedding.create at line 279 against an openai>=1.55.3 pin.

@IsmaelMartinez
IsmaelMartinez merged commit 739ea8a into The-PR-Agent:main Aug 30, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

/similar_issue is entirely broken — it calls the OpenAI v0 API removed in openai 1.0

4 participants