-
Notifications
You must be signed in to change notification settings - Fork 70
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
Add Retry Logic to http requests #151
Merged
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
91cfb63
Adds retry logic to backend via tenacity
bLopata 0399118
Adds python metadata directory to ignore.
bLopata d11677d
Merge branch 'main' into ben/dev-69
bLopata 645f602
Adds sentry logging
bLopata 5b272da
Move retry logic from API into Bloom client.
bLopata 318cdc7
Cleanup messagebox params and page component loading.
bLopata f7e0cb1
Removes tenacity from /api/ deps.
bLopata 84ff08c
Fix code scanning alert no. 10: Information exposure through an excep…
bLopata c044b58
Background task encapsulation for honcho SDK operations
bLopata 42f503c
Wraps honcho operations in promise handling.
bLopata dc76011
Merge branch 'main' into ben/dev-69
bLopata File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -12,6 +12,7 @@ __pycache__/ | |
*.pyc | ||
*.pyo | ||
.python-version | ||
api/api.egg-info/* | ||
|
||
# Visual Studio Code | ||
.vscode/ | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2,9 +2,7 @@ | |
name = "api" | ||
version = "0.6.0" | ||
description = "The REST API Implementation of Tutor-GPT" | ||
authors = [ | ||
{name = "Plastic Labs", email = "[email protected]"}, | ||
] | ||
authors = [{ name = "Plastic Labs", email = "[email protected]" }] | ||
requires-python = ">=3.11" | ||
dependencies = [ | ||
"fastapi[standard]>=0.112.2", | ||
|
@@ -16,4 +14,4 @@ dependencies = [ | |
|
||
[tool.uv.sources] | ||
# agent = { path = "../agent", editable = true } | ||
agent = {workspace=true} | ||
agent = { workspace = true } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,128 +1,130 @@ | ||
from typing import Optional | ||
from fastapi import APIRouter, HTTPException, Body | ||
from fastapi.responses import StreamingResponse | ||
from pydantic import BaseModel | ||
from fastapi import APIRouter, HTTPException | ||
from fastapi.responses import StreamingResponse, JSONResponse | ||
|
||
from api import schemas | ||
from api.dependencies import app, honcho | ||
|
||
from agent.chain import ThinkCall, RespondCall | ||
|
||
import logging | ||
|
||
router = APIRouter(prefix="/api", tags=["chat"]) | ||
|
||
|
||
@router.post("/stream") | ||
async def stream( | ||
inp: schemas.ConversationInput, | ||
async def stream(inp: schemas.ConversationInput): | ||
try: | ||
user = honcho.apps.users.get_or_create(app_id=app.id, name=inp.user_id) | ||
|
||
async def convo_turn(): | ||
thought = "" | ||
response = "" | ||
try: | ||
thought_stream = ThinkCall( | ||
user_input=inp.message, | ||
app_id=app.id, | ||
user_id=user.id, | ||
session_id=str(inp.conversation_id), | ||
honcho=honcho, | ||
).stream() | ||
for chunk in thought_stream: | ||
thought += chunk | ||
yield chunk | ||
|
||
yield "❀" | ||
response_stream = RespondCall( | ||
user_input=inp.message, | ||
thought=thought, | ||
app_id=app.id, | ||
user_id=user.id, | ||
session_id=str(inp.conversation_id), | ||
honcho=honcho, | ||
).stream() | ||
for chunk in response_stream: | ||
response += chunk | ||
yield chunk | ||
yield "❀" | ||
except Exception as e: | ||
logging.error(f"Error during streaming: {str(e)}") | ||
yield f"Error: {str(e)}" | ||
return | ||
|
||
await create_messages_and_metamessages( | ||
app.id, user.id, inp.conversation_id, inp.message, thought, response | ||
) | ||
|
||
return StreamingResponse(convo_turn()) | ||
except Exception as e: | ||
logging.error(f"An error occurred: {str(e)}") | ||
if "rate limit" in str(e).lower(): | ||
return JSONResponse( | ||
status_code=429, | ||
content={ | ||
"error": "rate_limit_exceeded", | ||
"message": "Rate limit exceeded. Please try again later.", | ||
}, | ||
) | ||
else: | ||
return JSONResponse( | ||
status_code=500, | ||
content={ | ||
"error": "internal_server_error", | ||
"message": "An internal server error has occurred.", | ||
}, | ||
) | ||
|
||
|
||
async def create_messages_and_metamessages( | ||
app_id, user_id, conversation_id, user_message, thought, ai_response | ||
): | ||
"""Stream the response too the user, currently only used by the Web UI and has integration to be able to use Honcho is not anonymous""" | ||
user = honcho.apps.users.get_or_create(app_id=app.id, name=inp.user_id) | ||
|
||
def convo_turn(): | ||
thought_stream = ThinkCall( | ||
user_input=inp.message, | ||
app_id=app.id, | ||
user_id=user.id, | ||
session_id=str(inp.conversation_id), | ||
honcho=honcho, | ||
).stream() | ||
thought = "" | ||
for chunk in thought_stream: | ||
thought += chunk | ||
yield chunk | ||
|
||
yield "❀" | ||
response_stream = RespondCall( | ||
user_input=inp.message, | ||
thought=thought, | ||
app_id=app.id, | ||
user_id=user.id, | ||
session_id=str(inp.conversation_id), | ||
honcho=honcho, | ||
).stream() | ||
response = "" | ||
for chunk in response_stream: | ||
response += chunk | ||
yield chunk | ||
yield "❀" | ||
|
||
honcho.apps.users.sessions.messages.create( | ||
try: | ||
# These operations will use the DB layer's built-in retry logic | ||
await honcho.apps.users.sessions.messages.create( | ||
is_user=True, | ||
session_id=str(inp.conversation_id), | ||
app_id=app.id, | ||
user_id=user.id, | ||
content=inp.message, | ||
session_id=str(conversation_id), | ||
app_id=app_id, | ||
user_id=user_id, | ||
content=user_message, | ||
) | ||
new_ai_message = honcho.apps.users.sessions.messages.create( | ||
new_ai_message = await honcho.apps.users.sessions.messages.create( | ||
is_user=False, | ||
session_id=str(inp.conversation_id), | ||
app_id=app.id, | ||
user_id=user.id, | ||
content=response, | ||
session_id=str(conversation_id), | ||
app_id=app_id, | ||
user_id=user_id, | ||
content=ai_response, | ||
) | ||
honcho.apps.users.sessions.metamessages.create( | ||
app_id=app.id, | ||
session_id=str(inp.conversation_id), | ||
user_id=user.id, | ||
await honcho.apps.users.sessions.metamessages.create( | ||
app_id=app_id, | ||
session_id=str(conversation_id), | ||
user_id=user_id, | ||
message_id=new_ai_message.id, | ||
metamessage_type="thought", | ||
content=thought, | ||
) | ||
return StreamingResponse(convo_turn()) | ||
except Exception as e: | ||
logging.error(f"Error in create_messages_and_metamessages: {str(e)}") | ||
raise # Re-raise the exception to be handled by the caller | ||
|
||
|
||
@router.get("/thought/{message_id}") | ||
async def get_thought(conversation_id: str, message_id: str, user_id: str): | ||
user = honcho.apps.users.get_or_create(app_id=app.id, name=user_id) | ||
thought = honcho.apps.users.sessions.metamessages.list( | ||
session_id=conversation_id, | ||
app_id=app.id, | ||
user_id=user.id, | ||
message_id=message_id, | ||
metamessage_type="thought" | ||
) | ||
# In practice, there should only be one thought per message | ||
return {"thought": thought.items[0].content if thought.items else None} | ||
|
||
class ReactionBody(BaseModel): | ||
reaction: Optional[str] = None | ||
|
||
@router.post("/reaction/{message_id}") | ||
async def add_or_remove_reaction( | ||
conversation_id: str, | ||
message_id: str, | ||
user_id: str, | ||
body: ReactionBody | ||
): | ||
reaction = body.reaction | ||
|
||
if reaction is not None and reaction not in ["thumbs_up", "thumbs_down"]: | ||
raise HTTPException(status_code=400, detail="Invalid reaction type") | ||
|
||
user = honcho.apps.users.get_or_create(app_id=app.id, name=user_id) | ||
|
||
message = honcho.apps.users.sessions.messages.get( | ||
app_id=app.id, | ||
session_id=conversation_id, | ||
user_id=user.id, | ||
message_id=message_id | ||
) | ||
|
||
if not message: | ||
raise HTTPException(status_code=404, detail="Message not found") | ||
|
||
metadata = message.metadata or {} | ||
|
||
if reaction is None: | ||
metadata.pop('reaction', None) | ||
else: | ||
metadata['reaction'] = reaction | ||
|
||
honcho.apps.users.sessions.messages.update( | ||
app_id=app.id, | ||
session_id=conversation_id, | ||
user_id=user.id, | ||
message_id=message_id, | ||
metadata=metadata | ||
) | ||
|
||
return {"status": "Reaction updated successfully"} | ||
try: | ||
user = honcho.apps.users.get_or_create(app_id=app.id, name=user_id) | ||
thought = honcho.apps.users.sessions.metamessages.list( | ||
session_id=conversation_id, | ||
app_id=app.id, | ||
user_id=user.id, | ||
message_id=message_id, | ||
metamessage_type="thought", | ||
) | ||
# In practice, there should only be one thought per message | ||
return {"thought": thought.items[0].content if thought.items else None} | ||
except Exception as e: | ||
logging.error(f"An error occurred: {str(e)}") | ||
return JSONResponse( | ||
status_code=500, | ||
content={ | ||
"error": "internal_server_error", | ||
"message": "An internal server error has occurred.", | ||
}, | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Might just be I don't know how these work, but is there a change that one of these errors could occur after the generator is finished and the messages and metamessages are created?
Unclear on the relationship between the try catch block and the Streaming Response method . If there is an error in the middle of the stream what happens?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Very good questions! My latest commit employs a background process for the honcho calls to separately handle/log any potential errors while (ideally) not interfering with the
StreamingResponse
. I think in the case of say a network interruption or rate limit error, it would hit this exception and return an error to the client which would (read: should) handle this interruption gracefully - see more.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
My worry with this approach is that if there is an error while saving a message to honcho then that is not propagated to the front-end / user. Meaning it will look like their message sent and the conversation is fine, but if they reload the messages will be gone without any indication of an error occurring.
It might make sense to make separate try catch blocks or separate Exceptions for the different types of errors that the LLM vs the honcho calls are making and report them to the user differently, without using the background tasks