ronantakizawa/codereview-bench huggingface dataset:
Repository: leptos-rs/leptos
File: server_fn/src/response/generic.rs (Rust)

Code before:

    fn try_from_stream(
        content_type: &str,
        data: impl Stream<Item = Result<Bytes, Bytes>> + Send + 'static,
    ) -> Result<Self, E> {
        let builder = http::Response::builder();
        builder
            .status(200)
            .header(http::header::CONTENT_TYPE, content_type)
            .body(Body::Async(Box::pin(
                data.map_err(|e| ServerFnErrorWrapper(E::de(e)))
                    .map_err(Error::from),
            )))
            .map_err(|e| {
                ServerFnErrorErr::Response(e.to_string()).into_app_error()
            })
    }
}

impl Res for Response<Body> {
    fn error_response(path: &str, err: ServerFnErrorResponseParts) -> Self {
        Response::builder()
            .status(http::StatusCode::INTERNAL_SERVER_ERROR)
            .header(SERVER_FN_ERROR_HEADER, path)
            .header(header::CONTENT_TYPE, err.content_type)
            .body(err.body.into())
            .unwrap()
    }

    fn redirect(&mut self, path: &str) {
        if let Ok(path) = HeaderValue::from_str(path) {
            self.headers_mut().insert(header::LOCATION, path);
            *self.status_mut() = StatusCode::FOUND;
        }
    }
}


Review comment (suggestion):
This is another of those things where it isn't necessarily your changes but as we add more things to the error response I wonder if we should be using `.unwrap()` here. Perhaps this is better as an fallible method in the `TryRes` trait or we need to add additional traits or a default response returned here instead of a panic

Code after:

    fn try_from_stream(
        content_type: &str,
        data: impl Stream<Item = Result<Bytes, Bytes>> + Send + 'static,
    ) -> Result<Self, E> {
        let builder = http::Response::builder();
        builder
            .status(200)
            .header(http::header::CONTENT_TYPE, content_type)
            .body(Body::Async(Box::pin(
                data.map_err(|e| ServerFnErrorWrapper(E::de(e)))
                    .map_err(Error::from),
            )))
            .map_err(|e| {
                ServerFnErrorErr::Response(e.to_string()).into_app_error()
            })
    }
}

impl Res for Response<Body> {
    fn error_response(path: &str, err: Bytes) -> Self {
        Response::builder()
            .status(http::StatusCode::INTERNAL_SERVER_ERROR)
            .header(SERVER_FN_ERROR_HEADER, path)
            .body(err.into())
            .unwrap()
    }

    fn content_type(&mut self, content_type: &str) {
        if let Ok(content_type) = HeaderValue::from_str(content_type) {
            self.headers_mut()
                .insert(header::CONTENT_TYPE, content_type);
        }
    }

    fn redirect(&mut self, path: &str) {
        if let Ok(path) = HeaderValue::from_str(path) {
            self.headers_mut().insert(header::LOCATION, path);
            *self.status_mut() = StatusCode::FOUND;
        }
    }
}
Repository: leptos-rs/leptos
File: reactive_graph/src/computed/async_derived/mod.rs (Rust)

Code before:
            diagnostics: false,
            fut,
        }
    }

    #[doc(hidden)]
    #[track_caller]
    pub fn new_untracked_with_diagnostics(fut: Fut) -> Self {
        let owner = Owner::current().unwrap_or_default();
        Self {
            owner,
            observer: None,
            diagnostics: true,
            fut,
        }
    }
}

impl<Fut: Future> Future for ScopedFuture<Fut> {
    type Output = Fut::Output;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.project();
        this.owner.with(|| {
            this.observer.with_observer(|| {
                #[cfg(debug_assertions)]
                let _maybe_guard = if *this.diagnostics {
                    None
                } else {
                    Some(crate::diagnostics::SpecialNonReactiveZone::enter())
                };
                this.fut.poll(cx)
            })
        })
    }
}

/// Utilities used to track whether asynchronous computeds are currently loading.
pub mod suspense {
    use crate::{
        signal::ArcRwSignal,
        traits::{Update, Write},
    };
    use futures::channel::oneshot::Sender;
    use or_poisoned::OrPoisoned;
    use slotmap::{DefaultKey, SlotMap};
    use std::sync::{Arc, Mutex};

    /// Sends a one-time notification that the resource being read from is "local only," i.e.,
    /// that it will only run on the client, not the server.
    #[derive(Clone, Debug)]

Review comment (bug):
Should this be `#[cfg(any(debug_assertions, leptos_debuginfo))]`?

Code after:
    }

    #[doc(hidden)]
    #[track_caller]
    pub fn new_untracked_with_diagnostics(
        fut: Fut,
    ) -> ScopedFutureUntrackedWithDiagnostics<Fut> {
        let owner = Owner::current().unwrap_or_default();
        ScopedFutureUntrackedWithDiagnostics {
            owner,
            observer: None,
            fut,
        }
    }
}

impl<Fut: Future> Future for ScopedFuture<Fut> {
    type Output = Fut::Output;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.project();
        this.owner.with(|| {
            #[cfg(debug_assertions)]
            let _maybe_guard = if this.observer.is_none() {
                Some(crate::diagnostics::SpecialNonReactiveZone::enter())
            } else {
                None
            };
            this.observer.with_observer(|| this.fut.poll(cx))
        })
    }
}

pin_project! {
    /// A [`Future`] wrapper that sets the [`Owner`] and [`Observer`] before polling the inner
    /// `Future`, output of [`ScopedFuture::new_untracked_with_diagnostics`].
    ///
    /// In leptos 0.9 this will be replaced with `ScopedFuture` itself.
    #[derive(Clone)]
    pub struct ScopedFutureUntrackedWithDiagnostics<Fut> {
        owner: Owner,
        observer: Option<AnySubscriber>,
        #[pin]
        fut: Fut,
    }
}

impl<Fut: Future> Future for ScopedFutureUntrackedWithDiagnostics<Fut> {
    type Output = Fut::Output;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
Repository: leptos-rs/leptos
File: tachys/src/html/directive.rs (Rust)

Code before:
    D: IntoDirective<T, P>,
    P: Clone + 'static,
    T: 'static,
{
    type Output = <Self as AddAnyAttr>::Output<Directive<T, D, P>>;

    fn directive(self, handler: D, param: P) -> Self::Output {
        self.add_any_attr(directive(handler, param))
    }
}

/// Adds a directive to the element, which runs some custom logic in the browser when the element
/// is created or hydrated.
#[inline(always)]
pub fn directive<T, P, D>(handler: D, param: P) -> Directive<T, D, P>
where
    D: IntoDirective<T, P>,
{
    Directive(Some(SendWrapper::new(DirectiveInner {
        handler,
        param,
        t: PhantomData,
    })))
}

/// Custom logic that runs in the browser when the element is created or hydrated.
#[derive(Debug)]
pub struct Directive<T, D, P>(Option<SendWrapper<DirectiveInner<T, D, P>>>);

impl<T, D, P> Clone for Directive<T, D, P>
where
    P: Clone + 'static,
    D: Clone,
{
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

#[derive(Debug)]
struct DirectiveInner<T, D, P> {
    handler: D,
    param: P,
    t: PhantomData<T>,
}

impl<T, D, P> Clone for DirectiveInner<T, D, P>
where
    P: Clone + 'static,
    D: Clone,
{

Review comment (suggestion):
I wonder if it would make sense to have a `const fn is_ssr() -> bool { cfg!(feature = "ssr") }` which would let things like this be `is_ssr().not().then(|| …)`?  I would personally find that more readable at least.

Code after:
    D: IntoDirective<T, P>,
    P: Clone + 'static,
    T: 'static,
{
    type Output = <Self as AddAnyAttr>::Output<Directive<T, D, P>>;

    fn directive(self, handler: D, param: P) -> Self::Output {
        self.add_any_attr(directive(handler, param))
    }
}

/// Adds a directive to the element, which runs some custom logic in the browser when the element
/// is created or hydrated.
#[inline(always)]
pub fn directive<T, P, D>(handler: D, param: P) -> Directive<T, D, P>
where
    D: IntoDirective<T, P>,
{
    Directive((!cfg!(feature = "ssr")).then(|| {
        SendWrapper::new(DirectiveInner {
            handler,
            param,
            t: PhantomData,
        })
    }))
}

/// Custom logic that runs in the browser when the element is created or hydrated.
#[derive(Debug)]
pub struct Directive<T, D, P>(Option<SendWrapper<DirectiveInner<T, D, P>>>);

impl<T, D, P> Clone for Directive<T, D, P>
where
    P: Clone + 'static,
    D: Clone,
{
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

#[derive(Debug)]
struct DirectiveInner<T, D, P> {
    handler: D,
    param: P,
    t: PhantomData<T>,
}

impl<T, D, P> Clone for DirectiveInner<T, D, P>
where
    P: Clone + 'static,
Repository: mckaywrigley/chatbot-ui
File: components/ui/chat-settings-form.tsx (TypeScript)

Code before:
          />
        </div>
      )}
    </div>
  )
}

interface AdvancedContentProps {
  chatSettings: ChatSettings
  onChangeChatSettings: (value: ChatSettings) => void
  showTooltip: boolean
}

const AdvancedContent: FC<AdvancedContentProps> = ({
  chatSettings,
  onChangeChatSettings,
  showTooltip
}) => {
  const {
    profile,
    selectedWorkspace,
    availableOpenRouterModels,
    selectedAssistant
  } = useContext(ChatbotUIContext)

  function findOpenRouterModel(modelId: string): any {
    return availableOpenRouterModels.find(model => model.modelId === modelId)
  }

  const MODEL_LIMITS = CHAT_SETTING_LIMITS[chatSettings.model] || {
    MIN_TEMPERATURE: 0,
    MAX_TEMPERATURE: 1,
    MAX_CONTEXT_LENGTH:
      findOpenRouterModel(chatSettings.model)?.maxContext || 4096
  }

  return (
    <div className="mt-5">
      <div className="space-y-3">
        <Label className="flex items-center space-x-1">
          <div>Temperature:</div>

          <div>{chatSettings.temperature}</div>
        </Label>

        <Slider
          value={[chatSettings.temperature]}
          onValueChange={temperature => {
            onChangeChatSettings({
              ...chatSettings,
              temperature: temperature[0]

Review comment (suggestion):
I noticed that you are using the type 'any.' Is it possible for you to implement specific types for it?

interface OpenRouterModel {
  modelId: string;
}

function findOpenRouterModel(modelId: string): OpenRouterModel | undefined 

Code after:
          />
        </div>
      )}
    </div>
  )
}

interface AdvancedContentProps {
  chatSettings: ChatSettings
  onChangeChatSettings: (value: ChatSettings) => void
  showTooltip: boolean
}

const AdvancedContent: FC<AdvancedContentProps> = ({
  chatSettings,
  onChangeChatSettings,
  showTooltip
}) => {
  const {
    profile,
    selectedWorkspace,
    availableOpenRouterModels,
    selectedAssistant
  } = useContext(ChatbotUIContext)

  function findOpenRouterModel(modelId: string) {
    return availableOpenRouterModels.find(model => model.modelId === modelId)
  }

  const MODEL_LIMITS = CHAT_SETTING_LIMITS[chatSettings.model] || {
    MIN_TEMPERATURE: 0,
    MAX_TEMPERATURE: 1,
    MAX_CONTEXT_LENGTH:
      findOpenRouterModel(chatSettings.model)?.maxContext || 4096
  }

  return (
    <div className="mt-5">
      <div className="space-y-3">
        <Label className="flex items-center space-x-1">
          <div>Temperature:</div>

          <div>{chatSettings.temperature}</div>
        </Label>

        <Slider
          value={[chatSettings.temperature]}
          onValueChange={temperature => {
            onChangeChatSettings({
              ...chatSettings,
              temperature: temperature[0]
Repository: microsoft/TypeChat
File: examples/music/src/main.ts (TypeScript)

Code before:
  if (remainingSeconds < 10) {
    return `${minutes}:0${remainingSeconds}`;
  } else {
    return `${minutes}:${remainingSeconds}`;
  }
}

const pauseSymbol = "\u{23F8}";
const playSymbol = "\u{25B6}";

function chalkStatus(status: SpotifyApi.CurrentPlaybackResponse) {
  if (status.item) {
    let timePart = msToElapsedMinSec(status.item.duration_ms);
    if (status.progress_ms) {
      timePart = `${msToElapsedMinSec(status.progress_ms)}/${timePart}`;
    }
    let symbol = status.is_playing ? playSymbol : pauseSymbol;
    console.log(`${symbol}  ${timePart}  ${chalk.cyanBright(status.item.name)}`);
    if (status.item.type === "track") {
      let artists = "   Artists: ";
      status.item.artists.forEach((artist, index) => {
        if (index > 0) {
          artists += ", ";
        }
        artists += chalk.green(artist.name);
      });
      console.log(artists);
    }
  }
}

async function handleCall(
  func: string,
  args: unknown[],
  clientContext: IClientContext
): Promise<unknown> {
  let result: SpotifyApi.TrackObjectFull[] | undefined = undefined;
  switch (func) {
    case "getLastTrackList": {
      if (clientContext) {
        result = clientContext.lastTrackList;
      }
      break;
    }
    case "pause": {
      if (clientContext.deviceId) {
        await pause(clientContext.service, clientContext.deviceId);
      }
      break;
    }
    case "play": {

Review comment (suggestion):
```suggestion
      const artists = "   Artists: " +
        status.item.artists.map(artist => chalk.green(artist.name)).join(", ");
```

Code after:
  // add leading zero if needed
  if (remainingSeconds < 10) {
    return `${minutes}:0${remainingSeconds}`;
  } else {
    return `${minutes}:${remainingSeconds}`;
  }
}

const pauseSymbol = "\u{23F8}";
const playSymbol = "\u{25B6}";

function chalkStatus(status: SpotifyApi.CurrentPlaybackResponse) {
  if (status.item) {
    let timePart = msToElapsedMinSec(status.item.duration_ms);
    if (status.progress_ms) {
      timePart = `${msToElapsedMinSec(status.progress_ms)}/${timePart}`;
    }
    let symbol = status.is_playing ? playSymbol : pauseSymbol;
    console.log(`${symbol}  ${timePart}  ${chalk.cyanBright(status.item.name)}`);
    if (status.item.type === "track") {
      const artists = "   Artists: " +
        status.item.artists.map(artist => chalk.green(artist.name)).join(", ");
      console.log(artists);
    }
  }
}

async function handleCall(
  func: string,
  args: unknown[],
  clientContext: IClientContext
): Promise<unknown> {
  let result: SpotifyApi.TrackObjectFull[] | undefined = undefined;
  switch (func) {
    case "getLastTrackList": {
      if (clientContext) {
        result = clientContext.lastTrackList;
      }
      break;
    }
    case "pause": {
      if (clientContext.deviceId) {
        await pause(clientContext.service, clientContext.deviceId);
      }
      break;
    }
    case "play": {
      const input = args[0] as SpotifyApi.TrackObjectFull[];
      if (input && input.length > 0) {
        let count = 1;
        let offset = 0;
Repository: microsoft/TypeChat
File: python/examples/multiSchema/router.py (Python)

Code before:
from typing import Any, Callable, Awaitable, Dict
from typechat import Failure, TypeChatValidator, TypeChatModel
from translator import TextClassiferTranslator, TextClassification, ClassificationItem


class TextRequestRouter:
    _current_agents: Dict[str, ClassificationItem]
    _validator: TypeChatValidator[TextClassification]
    _translator: TextClassiferTranslator[TextClassification]

    def __init__(self, model: TypeChatModel):
        super().__init__()
        self._validator = TypeChatValidator(TextClassification)
        self._translator = TextClassiferTranslator(model, self._validator, TextClassification)

        self._current_agents = {}

    def register_agent(self, name: str, description: str, handler: Callable[[str], Awaitable[Any]]):
        agent = ClassificationItem(name=name, description=description, handler=handler)
        self._current_agents[name] = agent
        self._translator.classes.append(agent)

    async def route_request(self, line: str):
        result = await self._translator.translate(line)
        if isinstance(result, Failure):
            print("Translation Failed ❌")

Review comment (suggestion):
```suggestion
from typing import Any, Callable, Awaitable
```

Code after:
import json
from textwrap import indent
from typing_extensions import Any, Callable, Awaitable, TypedDict, Annotated
from typechat import Failure, TypeChatValidator, TypeChatModel, TypeChatTranslator


class AgentInfo(TypedDict):
    name: str
    description: str
    handler: Callable[[str], Awaitable[Any]]


class TaskClassification(TypedDict):
    task_kind: Annotated[str, "Describe the kind of task to perform."]


class TextRequestRouter:
    _current_agents: dict[str, AgentInfo]
    _validator: TypeChatValidator[TaskClassification]
    _translator: TypeChatTranslator[TaskClassification]

    def __init__(self, model: TypeChatModel):
        super().__init__()
        self._validator = TypeChatValidator(TaskClassification)
        self._translator = TypeChatTranslator(model, self._validator, TaskClassification)
        self._current_agents = {}
Repository: microsoft/TypeChat
File: python/examples/multiSchema/router.py (Python)

Code before:
from typing import Any, Callable, Awaitable, Dict
from typechat import Failure, TypeChatValidator, TypeChatModel
from translator import TextClassiferTranslator, TextClassification, ClassificationItem


class TextRequestRouter:
    _current_agents: Dict[str, ClassificationItem]
    _validator: TypeChatValidator[TextClassification]
    _translator: TextClassiferTranslator[TextClassification]

    def __init__(self, model: TypeChatModel):
        super().__init__()
        self._validator = TypeChatValidator(TextClassification)
        self._translator = TextClassiferTranslator(model, self._validator, TextClassification)

        self._current_agents = {}

    def register_agent(self, name: str, description: str, handler: Callable[[str], Awaitable[Any]]):
        agent = ClassificationItem(name=name, description=description, handler=handler)
        self._current_agents[name] = agent
        self._translator.classes.append(agent)

    async def route_request(self, line: str):
        result = await self._translator.translate(line)
        if isinstance(result, Failure):
            print("Translation Failed ❌")
            print(f"Context: {result.message}")
        else:
            result = result.value
            print("Translation Succeeded! ✅\n")
            print(f"The target class is {result['class']}")
            target = self._current_agents[result["class"]]

Review comment (suggestion):
```suggestion
    _current_agents: dict[str, ClassificationItem]
```

Code after:
import json
from textwrap import indent
from typing_extensions import Any, Callable, Awaitable, TypedDict, Annotated
from typechat import Failure, TypeChatValidator, TypeChatModel, TypeChatTranslator


class AgentInfo(TypedDict):
    name: str
    description: str
    handler: Callable[[str], Awaitable[Any]]


class TaskClassification(TypedDict):
    task_kind: Annotated[str, "Describe the kind of task to perform."]


class TextRequestRouter:
    _current_agents: dict[str, AgentInfo]
    _validator: TypeChatValidator[TaskClassification]
    _translator: TypeChatTranslator[TaskClassification]

    def __init__(self, model: TypeChatModel):
        super().__init__()
        self._validator = TypeChatValidator(TaskClassification)
        self._translator = TypeChatTranslator(model, self._validator, TaskClassification)
        self._current_agents = {}

    def register_agent(self, name: str, description: str, handler: Callable[[str], Awaitable[Any]]):
        agent = AgentInfo(name=name, description=description, handler=handler)
        self._current_agents[name] = agent

    async def route_request(self, line: str):
Repository: microsoft/TypeChat
File: python/examples/multiSchema/agents.py (Python)

Code before:
import os
import sys

examples_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
if examples_path not in sys.path:
    sys.path.append(examples_path)

import json

from typing import TypeVar, Generic
from typechat import Failure, TypeChatTranslator, TypeChatValidator, TypeChatModel

import examples.math.schema as math_schema
from examples.math.program import TypeChatProgramTranslator, TypeChatProgramValidator, evaluate_json_program, JsonProgram

import examples.music.schema as music_schema
from examples.music.client import ClientContext, handle_call, get_client_context

T = TypeVar("T", covariant=True)

class JsonPrintAgent(Generic[T]):
    _validator: TypeChatValidator[T]
    _translator: TypeChatTranslator[T]

    def __init__(self, model: TypeChatModel, target_type: type[T]):
        super().__init__()
        self._validator = TypeChatValidator(target_type)

Review comment (suggestion):
Will be good to has a base Agent class that all the agents inherit from. The base class can have members like handle_request, _validator, _translator, agent_name etc. 

Code after:
import os
import sys

examples_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
if examples_path not in sys.path:
    sys.path.append(examples_path)

import json

from typing_extensions import TypeVar, Generic
from typechat import Failure, TypeChatTranslator, TypeChatValidator, TypeChatModel

import examples.math.schema as math_schema
from examples.math.program import (
    TypeChatProgramTranslator,
    TypeChatProgramValidator,
    evaluate_json_program,
    JsonProgram,
)

import examples.music.schema as music_schema
from examples.music.client import ClientContext, handle_call, get_client_context

T = TypeVar("T", covariant=True)


class JsonPrintAgent(Generic[T]):