Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhanced Ollama Response Handling with Retries and Streaming #305

Merged
merged 1 commit into from
Dec 20, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 28 additions & 6 deletions pdf2zh/translator.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,12 +216,34 @@ def translate(self, text):
print(len(self.prompt(text, self.prompttext)))
print(self.prompt(text, self.prompttext)[0])
print(self.prompt(text, self.prompttext)[1])
response = self.client.chat(
model=self.model,
options=self.options,
messages=self.prompt(text, self.prompttext),
)
return response["message"]["content"].strip()
maxlen = max(2000, len(text) * 3)
for model in self.model.split(";"):
for i in range(2):
if i:
print("[Retry]")
response = ""
try:
stream = self.client.chat(
model=model,
options=self.options,
messages=self.prompt(text, self.prompttext),
stream=True,
)
for chunk in stream:
chunk = chunk["message"]["content"]
print(chunk, end="", flush=True)
response += chunk
if len(response) > maxlen:
raise Exception("Response too long")
if not response.endswith("\n"):
print()
return response.strip()
except Exception as e:
print()
print(e)
print("[Aborted.]")
# if translation fails after multiple retries, return the original text to prevent hang-up
return text


class OpenAITranslator(BaseTranslator):
Expand Down
Loading