Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

fix(otto): prevent breaking when failing to make api call (#9613)

Bentlyc1e329497c9a
diff --git a/autogpt_platform/backend/backend/server/v2/otto/routes.py b/autogpt_platform/backend/backend/server/v2/otto/routes.py
index eb63aacad5..6f409e9a6c 100644
--- a/autogpt_platform/backend/backend/server/v2/otto/routes.py
+++ b/autogpt_platform/backend/backend/server/v2/otto/routes.py
@@ -4,15 +4,11 @@ from autogpt_libs.auth.middleware import auth_middleware
from fastapi import APIRouter, Depends
from backend.server.utils import get_user_id
-from backend.util.settings import Settings
from .models import ApiResponse, ChatRequest
from .service import OttoService
logger = logging.getLogger(__name__)
-settings = Settings()
-
-OTTO_API_URL = settings.config.otto_api_url
router = APIRouter()
diff --git a/autogpt_platform/backend/backend/server/v2/otto/service.py b/autogpt_platform/backend/backend/server/v2/otto/service.py
index f8be312249..8efa4f642f 100644
--- a/autogpt_platform/backend/backend/server/v2/otto/service.py
+++ b/autogpt_platform/backend/backend/server/v2/otto/service.py
@@ -1,3 +1,4 @@
+import asyncio
import logging
from typing import Optional
@@ -67,6 +68,13 @@ class OttoService:
"""
Send request to Otto API and handle the response.
"""
+ # Check if Otto API URL is configured
+ if not OTTO_API_URL:
+ logger.error("Otto API URL is not configured")
+ raise HTTPException(
+ status_code=503, detail="Otto service is not configured"
+ )
+
try:
async with aiohttp.ClientSession() as session:
headers = {
@@ -94,7 +102,10 @@ class OttoService:
logger.debug(f"Request payload: {payload}")
async with session.post(
- OTTO_API_URL, json=payload, headers=headers
+ OTTO_API_URL,
+ json=payload,
+ headers=headers,
+ timeout=aiohttp.ClientTimeout(total=60),
) as response:
if response.status != 200:
error_text = await response.text()
@@ -115,6 +126,11 @@ class OttoService:
raise HTTPException(
status_code=503, detail="Failed to connect to Otto service"
)
+ except asyncio.TimeoutError:
+ logger.error("Timeout error connecting to Otto API after 60 seconds")
+ raise HTTPException(
+ status_code=504, detail="Request to Otto service timed out"
+ )
except Exception as e:
logger.error(f"Unexpected error in Otto API proxy: {str(e)}")
raise HTTPException(
diff --git a/autogpt_platform/frontend/src/app/build/actions.ts b/autogpt_platform/frontend/src/app/build/actions.ts
index 6c1ca0d505..16c577d16c 100644
--- a/autogpt_platform/frontend/src/app/build/actions.ts
+++ b/autogpt_platform/frontend/src/app/build/actions.ts
@@ -24,10 +24,14 @@ export async function askOtto(
try {
const response = await api.askOtto(ottoQuery);
- revalidatePath("/build");
return response;
} catch (error) {
console.error("Error in askOtto server action:", error);
- throw error;
+ return {
+ answer: error instanceof Error ? error.message : "Unknown error occurred",
+ documents: [],
+ success: false,
+ error: true,
+ };
}
}
diff --git a/autogpt_platform/frontend/src/components/OttoChatWidget.tsx b/autogpt_platform/frontend/src/components/OttoChatWidget.tsx
index efbb6d73cc..e03fcfbf62 100644
--- a/autogpt_platform/frontend/src/components/OttoChatWidget.tsx
+++ b/autogpt_platform/frontend/src/components/OttoChatWidget.tsx
@@ -56,29 +56,30 @@ const OttoChatWidget = () => {
// Add user message to chat
setMessages((prev) => [...prev, { type: "user", content: userMessage }]);
- try {
- // Add temporary processing message
- setMessages((prev) => [
- ...prev,
- { type: "assistant", content: "Processing your question..." },
- ]);
+ // Add temporary processing message
+ setMessages((prev) => [
+ ...prev,
+ { type: "assistant", content: "Processing your question..." },
+ ]);
- const conversationHistory = messages.reduce<
- { query: string; response: string }[]
- >((acc, msg, i, arr) => {
- if (
- msg.type === "user" &&
- i + 1 < arr.length &&
- arr[i + 1].type === "assistant"
- ) {
- acc.push({
- query: msg.content,
- response: arr[i + 1].content,
- });
- }
- return acc;
- }, []);
+ const conversationHistory = messages.reduce<
+ { query: string; response: string }[]
+ >((acc, msg, i, arr) => {
+ if (
+ msg.type === "user" &&
+ i + 1 < arr.length &&
+ arr[i + 1].type === "assistant" &&
+ arr[i + 1].content !== "Processing your question..."
+ ) {
+ acc.push({
+ query: msg.content,
+ response: arr[i + 1].content,
+ });
+ }
+ return acc;
+ }, []);
+ try {
const data = await askOtto(
userMessage,
conversationHistory,
@@ -86,34 +87,43 @@ const OttoChatWidget = () => {
flowID || undefined,
);
- // Remove processing message and add actual response
- setMessages((prev) => [
- ...prev.slice(0, -1),
- { type: "assistant", content: data.answer },
- ]);
- } catch (error) {
- console.error("Error calling API:", error);
- // Remove processing message and add error message
- const errorMessage =
- error instanceof Error && error.message === "Authentication required"
- ? "Please sign in to use the chat feature."
- : "Sorry, there was an error processing your message. Please try again.";
+ // Check if the response contains an error
+ if ("error" in data && data.error === true) {
+ // Handle different error types
+ let errorMessage =
+ "Sorry, there was an error processing your message. Please try again.";
+ if (data.answer === "Authentication required") {
+ errorMessage = "Please sign in to use the chat feature.";
+ } else if (data.answer === "Failed to connect to Otto service") {
+ errorMessage =
+ "Otto service is currently unavailable. Please try again later.";
+ } else if (data.answer.includes("timed out")) {
+ errorMessage = "Request timed out. Please try again later.";
+ }
+
+ // Remove processing message and add error message
+ setMessages((prev) => [
+ ...prev.slice(0, -1),
+ { type: "assistant", content: errorMessage },
+ ]);
+ } else {
+ // Remove processing message and add actual response
+ setMessages((prev) => [
+ ...prev.slice(0, -1),
+ { type: "assistant", content: data.answer },
+ ]);
+ }
+ } catch (error) {
+ console.error("Unexpected error in chat widget:", error);
setMessages((prev) => [
...prev.slice(0, -1),
- { type: "assistant", content: errorMessage },
+ {
+ type: "assistant",
+ content:
+ "An unexpected error occurred. Please refresh the page and try again.",
+ },
]);
-
- if (
- error instanceof Error &&
- error.message === "Authentication required"
- ) {
- toast({
- title: "Authentication Error",
- description: "Please sign in to use the chat feature.",
- variant: "destructive",
- });
- }
} finally {
setIsProcessing(false);
setIncludeGraphData(false);
diff --git a/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts b/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts
index a9995b377e..26561c889e 100644
--- a/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts
+++ b/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts
@@ -760,6 +760,7 @@ export interface OttoResponse {
answer: string;
documents: OttoDocument[];
success: boolean;
+ error: boolean;
}
export interface OttoQuery {