ronantakizawa/codereview-bench huggingface dataset:
Repository: Significant-Gravitas/Auto-GPT
File: autogpt_platform/backend/backend/blocks/http.py (Python)

Code before:
                data=body if not input_data.json_format else None,
            )
            result = response.json() if input_data.json_format else response.text

            if response.status_code // 100 == 2:
                yield "response", result
            elif response.status_code // 100 == 4:
                yield "client_error", result
            elif response.status_code // 100 == 5:
                yield "server_error", result
            else:
                raise ValueError(f"Unexpected status code: {response.status_code}")
        except Exception as e:
            # Check if this is an HTTP error with a response attribute
            if hasattr(e, "response") and hasattr(e.response, "status_code"):  # type: ignore
                status_code = e.response.status_code  # type: ignore

                if status_code // 100 == 4:
                    result = e.response.json() if input_data.json_format and hasattr(e.response, "json") else str(e)  # type: ignore
                    yield "client_error", result
                elif status_code // 100 == 5:
                    result = e.response.json() if input_data.json_format and hasattr(e.response, "json") else str(e)  # type: ignore
                    yield "server_error", result
                else:
                    yield "error", str(e)
            else:
                # Handle non-HTTP exceptions
                yield "error", str(e)


Review comment (suggestion):
edit to go with the suggestion above:
```suggestion
        except Exception as e:
```

Code after:
            response = requests.request(
                input_data.method.value,
                input_data.url,
                headers=input_data.headers,
                json=body if input_data.json_format else None,
                data=body if not input_data.json_format else None,
            )
            result = response.json() if input_data.json_format else response.text
            yield "response", result

        except HTTPError as e:
            # Handle error responses
            try:
                result = e.response.json() if input_data.json_format else str(e)
            except json.JSONDecodeError:
                result = str(e)

            if 400 <= e.response.status_code < 500:
                yield "client_error", result
            elif 500 <= e.response.status_code < 600:
                yield "server_error", result
            else:
                error_msg = (
                    "Unexpected status code "
                    f"{e.response.status_code} '{e.response.reason}'"
                )
                logger.warning(error_msg)
                yield "error", error_msg

        except RequestException as e:
            # Handle other request-related exceptions
            yield "error", str(e)

        except Exception as e:
            # Catch any other unexpected exceptions
            yield "error", str(e)
Repository: Significant-Gravitas/Auto-GPT
File: autogpt_platform/backend/backend/blocks/http.py (Python)

Code before:
import json
import logging
from enum import Enum
from typing import Any

import requests as req  # Import standard requests to access exception types

from backend.data.block import Block, BlockCategory, BlockOutput, BlockSchema
from backend.data.model import SchemaField
from backend.util.request import requests

logger = logging.getLogger(name=__name__)


class HttpMethod(Enum):
    GET = "GET"
    POST = "POST"
    PUT = "PUT"
    DELETE = "DELETE"
    PATCH = "PATCH"
    OPTIONS = "OPTIONS"
    HEAD = "HEAD"


class SendWebRequestBlock(Block):
    class Input(BlockSchema):
        url: str = SchemaField(
            description="The URL to send the request to",
            placeholder="https://api.example.com",
        )
        method: HttpMethod = SchemaField(

Review comment (suggestion):
excessive import
```suggestion
from requests.exceptions import HTTPError, RequestException
```

Code after:
import json
import logging
from enum import Enum
from typing import Any

from requests.exceptions import HTTPError, RequestException

from backend.data.block import Block, BlockCategory, BlockOutput, BlockSchema
from backend.data.model import SchemaField
from backend.util.request import requests

logger = logging.getLogger(name=__name__)


class HttpMethod(Enum):
    GET = "GET"
    POST = "POST"
    PUT = "PUT"
    DELETE = "DELETE"
    PATCH = "PATCH"
    OPTIONS = "OPTIONS"
    HEAD = "HEAD"


class SendWebRequestBlock(Block):
    class Input(BlockSchema):
        url: str = SchemaField(
            description="The URL to send the request to",
            placeholder="https://api.example.com",
        )
        method: HttpMethod = SchemaField(
Repository: Significant-Gravitas/Auto-GPT
File: autogpt_platform/backend/backend/blocks/http.py (Python)

Code before:
            if response.ok:
                yield "response", result
            elif 400 <= response.status_code < 500:
                yield "client_error", result
            elif 500 <= response.status_code < 600:
                yield "server_error", result
            else:
                logger.warning(f"Unexpected status code: {response.status_code}")
                yield "error", f"Unexpected status code: {response.status_code}"

        except req.exceptions.HTTPError as e:
            # Handle HTTP errors from raise_for_status()
            if e.response:
                status_code = e.response.status_code

                if 400 <= status_code < 500:
                    result = (
                        e.response.json()
                        if input_data.json_format and hasattr(e.response, "json")
                        else str(e)
                    )
                    yield "client_error", result
                elif 500 <= status_code < 600:
                    result = (
                        e.response.json()
                        if input_data.json_format and hasattr(e.response, "json")
                        else str(e)
                    )
                    yield "server_error", result
                else:
                    yield "error", str(e)

        except req.exceptions.RequestException as e:
            # Handle other request-related exceptions
            yield "error", str(e)

        except Exception as e:
            # Catch any other unexpected exceptions
            yield "error", str(e)


Review comment (suggestion):
if the `if e.response:` above is removed:
```suggestion
                        if input_data.json_format and e.response
```

Code after:

        except HTTPError as e:
            # Handle error responses
            try:
                result = e.response.json() if input_data.json_format else str(e)
            except json.JSONDecodeError:
                result = str(e)

            if 400 <= e.response.status_code < 500:
                yield "client_error", result
            elif 500 <= e.response.status_code < 600:
                yield "server_error", result
            else:
                error_msg = (
                    "Unexpected status code "
                    f"{e.response.status_code} '{e.response.reason}'"
                )
                logger.warning(error_msg)
                yield "error", error_msg

        except RequestException as e:
            # Handle other request-related exceptions
            yield "error", str(e)

        except Exception as e:
            # Catch any other unexpected exceptions
            yield "error", str(e)
Repository: Significant-Gravitas/Auto-GPT
File: autogpt_platform/frontend/src/components/agents/agent-run-draft-view.tsx (TypeScript)

Code before:
  const openInputPopout = useCallback(
    (key: string) => {
      setTempInputValue(inputValues[key] || "");
      setExpandedInputKey(key);
    },
    [inputValues],
  );

  const closeInputPopout = useCallback(() => {
    setExpandedInputKey(null);
  }, []);

  const saveAndCloseInputPopout = useCallback(() => {
    if (!expandedInputKey) return;

    setInputValues((obj) => ({ ...obj, [expandedInputKey]: tempInputValue }));
    closeInputPopout();
  }, [expandedInputKey, tempInputValue, closeInputPopout]);

  const doRun = useCallback(
    () =>
      toastOnFail("execute agent", () =>
        api
          .executeGraph(graph.id, graph.version, inputValues)
          .then((newRun) => onRun(newRun.graph_exec_id)),
      ),
    [api, graph, inputValues, onRun, toastOnFail],
  );

  const runActions: ButtonAction[] = useMemo(
    () => [
      {
        label: (
          <>
            <IconPlay className="mr-2 size-5" />
            Run
          </>
        ),
        variant: "accent",
        callback: doRun,
      },
    ],
    [doRun],
  );

  return (
    <div className="agpt-div flex gap-6">
      <div className="flex flex-1 flex-col gap-4">
        <Card className="agpt-box">
          <CardHeader>
            <CardTitle className="font-poppins text-lg">Input</CardTitle>

Review comment (bug):
Why the wrapping construction?
```suggestion
      api
        .executeGraph(graph.id, graph.version, inputValues)
          .then((newRun) => onRun(newRun.graph_exec_id)),
          .catch(toastOnFail("execute agent")),
```

Code after:
  const openInputPopout = useCallback(
    (key: string) => {
      setTempInputValue(inputValues[key] || "");
      setExpandedInputKey(key);
    },
    [inputValues],
  );

  const closeInputPopout = useCallback(() => {
    setExpandedInputKey(null);
  }, []);

  const saveAndCloseInputPopout = useCallback(() => {
    if (!expandedInputKey) return;

    setInputValues((obj) => ({ ...obj, [expandedInputKey]: tempInputValue }));
    closeInputPopout();
  }, [expandedInputKey, tempInputValue, closeInputPopout]);

  const doRun = useCallback(
    () =>
      api
        .executeGraph(graph.id, graph.version, inputValues)
        .then((newRun) => onRun(newRun.graph_exec_id))
        .catch(toastOnFail("execute agent")),
    [api, graph, inputValues, onRun, toastOnFail],
  );

  const runActions: ButtonAction[] = useMemo(
    () => [
      {
        label: (
          <>
            <IconPlay className="mr-2 size-5" />
            Run
          </>
        ),
        variant: "accent",
        callback: doRun,
      },
    ],
    [doRun],
  );

  return (
    <div className="agpt-div flex gap-6">
      <div className="flex flex-1 flex-col gap-4">
        <Card className="agpt-box">
          <CardHeader>
            <CardTitle className="font-poppins text-lg">Input</CardTitle>
          </CardHeader>
Repository: Significant-Gravitas/Auto-GPT
File: autogpt_platform/autogpt_libs/autogpt_libs/utils/cache.py (Python)

Code before:
import inspect
import threading
from typing import Any, Awaitable, Callable, ParamSpec, TypeVar, Union, cast, overload

P = ParamSpec("P")
R = TypeVar("R")


@overload
def thread_cached(func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[R]]: ...


@overload
def thread_cached(func: Callable[P, R]) -> Callable[P, R]: ...


def thread_cached(
    func: Union[Callable[P, R], Callable[P, Awaitable[R]]],
) -> Union[Callable[P, R], Callable[P, Awaitable[R]]]:
    thread_local = threading.local()

    if inspect.iscoroutinefunction(func):

        async def async_wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
            cache = getattr(thread_local, "cache", None)
            if cache is None:
                cache = thread_local.cache = {}
            key = (args, tuple(sorted(kwargs.items())))
            if key not in cache:
                cache[key] = await cast(Callable[P, Awaitable[R]], func)(
                    *args, **kwargs
                )
            return cache[key]

        return async_wrapper
    else:

        def sync_wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
            cache = getattr(thread_local, "cache", None)
            if cache is None:
                cache = thread_local.cache = {}
            key = (args, tuple(sorted(kwargs.items())))
            if key not in cache:
                cache[key] = func(*args, **kwargs)

Review comment (suggestion):
```suggestion
    func: Callable[P, R] | Callable[P, Awaitable[R]],
) -> Callable[P, R] | Callable[P, Awaitable[R]]:
```

Code after:
import inspect
import threading
from typing import Any, Awaitable, Callable, ParamSpec, TypeVar, cast, overload

P = ParamSpec("P")
R = TypeVar("R")


@overload
def thread_cached(func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[R]]: ...


@overload
def thread_cached(func: Callable[P, R]) -> Callable[P, R]: ...


def thread_cached(
    func: Callable[P, R] | Callable[P, Awaitable[R]],
) -> Callable[P, R] | Callable[P, Awaitable[R]]:
    thread_local = threading.local()

    if inspect.iscoroutinefunction(func):

        async def async_wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
            cache = getattr(thread_local, "cache", None)
            if cache is None:
                cache = thread_local.cache = {}
            key = (func, args, tuple(sorted(kwargs.items())))
            if key not in cache:
                cache[key] = await cast(Callable[P, Awaitable[R]], func)(
                    *args, **kwargs
                )
            return cache[key]

        return async_wrapper
    else:

        def sync_wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
            cache = getattr(thread_local, "cache", None)
            if cache is None:
                cache = thread_local.cache = {}
            # Include function in the key to prevent collisions between different functions
            key = (func, args, tuple(sorted(kwargs.items())))
            if key not in cache:
Repository: Significant-Gravitas/Auto-GPT
File: autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts (TypeScript)

Code before:
    return this._get(`/library/agents/${id}`);
  }

  addMarketplaceAgentToLibrary(
    storeListingVersionID: string,
  ): Promise<LibraryAgent> {
    return this._request("POST", "/library/agents", {
      store_listing_version_id: storeListingVersionID,
    });
  }

  async updateLibraryAgent(
    libraryAgentId: LibraryAgentID,
    params: {
      auto_update_version?: boolean;
      is_favorite?: boolean;
      is_archived?: boolean;
      is_deleted?: boolean;
    },
  ): Promise<void> {
    await this._request("PUT", `/library/agents/${libraryAgentId}`, params);
  }

  /**
   * Clone Library Agent and its underyling graph&nodes.
   * User must own
   */
  deepCloneLibraryAgent(libraryAgentId: LibraryAgentID): Promise<LibraryAgent> {
    return this._request("POST", `/library/agents/${libraryAgentId}/clone`);
  }

  listLibraryAgentPresets(params?: {
    page?: number;
    page_size?: number;
  }): Promise<LibraryAgentPresetResponse> {
    return this._get("/library/presets", params);
  }

  getLibraryAgentPreset(presetId: string): Promise<LibraryAgentPreset> {
    return this._get(`/library/presets/${presetId}`);
  }

  createLibraryAgentPreset(
    preset: CreateLibraryAgentPresetRequest,
  ): Promise<LibraryAgentPreset> {
    return this._request("POST", "/library/presets", preset);
  }

  updateLibraryAgentPreset(
    presetId: string,
    preset: CreateLibraryAgentPresetRequest,

Review comment (suggestion):
```suggestion
   * User must own the underlying graph for this to succeed.
```


Code after:
    return this._get(`/library/agents/${id}`);
  }

  addMarketplaceAgentToLibrary(
    storeListingVersionID: string,
  ): Promise<LibraryAgent> {
    return this._request("POST", "/library/agents", {
      store_listing_version_id: storeListingVersionID,
    });
  }

  async updateLibraryAgent(
    libraryAgentId: LibraryAgentID,
    params: {
      auto_update_version?: boolean;
      is_favorite?: boolean;
      is_archived?: boolean;
      is_deleted?: boolean;
    },
  ): Promise<void> {
    await this._request("PUT", `/library/agents/${libraryAgentId}`, params);
  }

  forkLibraryAgent(libraryAgentId: LibraryAgentID): Promise<LibraryAgent> {
    return this._request("POST", `/library/agents/${libraryAgentId}/fork`);
  }

  listLibraryAgentPresets(params?: {
    page?: number;
    page_size?: number;
  }): Promise<LibraryAgentPresetResponse> {
    return this._get("/library/presets", params);
  }

  getLibraryAgentPreset(presetId: string): Promise<LibraryAgentPreset> {
    return this._get(`/library/presets/${presetId}`);
  }

  createLibraryAgentPreset(
    preset: CreateLibraryAgentPresetRequest,
  ): Promise<LibraryAgentPreset> {
    return this._request("POST", "/library/presets", preset);
  }

  updateLibraryAgentPreset(
    presetId: string,
    preset: CreateLibraryAgentPresetRequest,
  ): Promise<LibraryAgentPreset> {
    return this._request("PUT", `/library/presets/${presetId}`, preset);
  }
Repository: Significant-Gravitas/Auto-GPT
File: autogpt_platform/frontend/src/components/_new/Text/Text.stories.tsx (TypeScript)

Code before:
      <Text variant="large-medium">Large Medium</Text>
      <Text variant="large-semibold">Large Semibold</Text>
      <Text variant="body">Body</Text>
      <Text variant="body-medium">Body Medium</Text>
      <Text variant="small">Small</Text>
      <Text variant="small-medium">Small Medium</Text>
      <Text variant="subtle">Subtle</Text>
    </div>
  );
}

//=============================================================================
// Interactive Playground
//=============================================================================
export const Playground: Story = {
  args: {
    variant: "body",
    children:
      "Edit this text and try different variants via the controls below",
  },
  parameters: {
    controls: { include: ["variant", "as", "children"] },
  },
  render: () => (
    <div className="space-y-8">
      <Text variant="h2" as="h2">
        Use the controls below to try different variants
      </Text>
    </div>
  ),
};

//=============================================================================
// Custom Element
//=============================================================================
export function CustomElement() {
  return (
    <div className="space-y-8">
      <Text variant="h3" as="div">
        H3 size rendered as div
      </Text>
      <Text variant="body" as="h2">
        Body size rendered as h2
      </Text>
    </div>
  );
}


Review comment (suggestion):
This looks like it doesn't use the interactive controls:

Should it be something like this?

`<Text variant={args.variant} as={args.as}>{args.children}</Text>` 

Code after:
      <Text variant="large-medium">Large Medium</Text>
      <Text variant="large-semibold">Large Semibold</Text>
      <Text variant="body">Body</Text>
      <Text variant="body-medium">Body Medium</Text>
      <Text variant="small">Small</Text>
      <Text variant="small-medium">Small Medium</Text>
      <Text variant="subtle">Subtle</Text>
    </div>
  );
}

//=============================================================================
// Interactive Playground
//=============================================================================
export const Playground: Story = {
  args: {
    variant: "body",
    children:
      "Edit this text and try different variants via the controls below",
  },
  parameters: {
    controls: { include: ["variant", "as", "children"] },
  },
  render: (args) => (
    <div className="space-y-8">
      <Text {...args} />
    </div>
  ),
};

//=============================================================================
// Custom Element
//=============================================================================
export function CustomElement() {
  return (
    <div className="space-y-8">
      <Text variant="h3" as="div">
        H3 size rendered as div
      </Text>
      <Text variant="body" as="h2">
        Body size rendered as h2
      </Text>
    </div>
  );
}
Repository: Significant-Gravitas/Auto-GPT
File: autogpt_platform/frontend/src/app/api/proxy/[...path]/route.ts (TypeScript)

Code before:
import { NextRequest, NextResponse } from "next/server";
import {
  makeAuthenticatedRequest,
  makeAuthenticatedFileUpload,
} from "@/lib/autogpt-server-api/helpers";

const BACKEND_BASE_URL =
  process.env.NEXT_PUBLIC_AGPT_SERVER_BASE_URL || "http://localhost:8006";

/**
 * Builds the backend URL from the request path and query string
 */
function buildBackendUrl(path: string[], queryString: string): string {
  const backendPath = path.join("/");
  return `${BACKEND_BASE_URL}/${backendPath}${queryString}`;
}

/**
 * Handles JSON content type requests
 */
async function handleJsonRequest(
  req: NextRequest,
  method: string,
  backendUrl: string,
): Promise<any> {
  const payload = await req.json();
  return await makeAuthenticatedRequest(
    method,
    backendUrl,
    payload,
    "application/json",
  );
}

/**
 * Handles multipart/form-data content type requests
 */
async function handleFormDataRequest(

Review comment (suggestion):
```suggestion

function buildBackendUrl(path: string[], queryString: string): string {
```

Code after:
import { NextRequest, NextResponse } from "next/server";
import {
  makeAuthenticatedRequest,
  makeAuthenticatedFileUpload,
} from "@/lib/autogpt-server-api/helpers";

const BACKEND_BASE_URL =
  process.env.NEXT_PUBLIC_AGPT_SERVER_BASE_URL || "http://localhost:8006";

function buildBackendUrl(path: string[], queryString: string): string {
  const backendPath = path.join("/");
  return `${BACKEND_BASE_URL}/${backendPath}${queryString}`;
}

async function handleJsonRequest(
  req: NextRequest,
  method: string,
  backendUrl: string,
): Promise<any> {
  const payload = await req.json();
  return await makeAuthenticatedRequest(
    method,
    backendUrl,
    payload,
    "application/json",
  );
}

async function handleFormDataRequest(
  req: NextRequest,
  backendUrl: string,
): Promise<any> {
  const formData = await req.formData();
  return await makeAuthenticatedFileUpload(backendUrl, formData);
}

async function handleUrlEncodedRequest(
  req: NextRequest,