before_code
stringlengths
30
149k
reviewer_comment
stringlengths
16
20.6k
after_code
stringlengths
30
163k
diff_context
stringlengths
0
22.4k
file_path
stringlengths
6
155
comment_line
int64
0
26
language
stringclasses
19 values
quality_score
float64
0.07
1
comment_type
stringclasses
9 values
comment_length
int64
16
20.6k
before_lines
int64
2
4.61k
after_lines
int64
2
4.4k
is_negative
bool
2 classes
pr_title
stringlengths
7
140
pr_number
int64
18
61.2k
repo_name
stringclasses
29 values
repo_stars
int64
321
56k
repo_language
stringclasses
14 values
reviewer_username
stringclasses
378 values
author_username
stringclasses
739 values
user
stringlengths
361
200k
assistant
stringlengths
16
20.6k
system
stringclasses
1 value
return ( <FormControl ref={containerRef}> <Menu placement="auto"> <MenuButton as={Button} pr="3" rightIcon={<Cog />} size="lg" width="100%"> {activePluginIndex > -1 && plugins[activePluginIndex]?.enabled ? ( <Box display="flex" justifyContent="flex-start" gap={2}> ...
Can you revert this? Already fixed in my PR
return ( <FormControl ref={containerRef}> <Menu placement="auto"> <MenuButton as={Button} pr="3" rightIcon={<Cog />} size="lg" width="100%"> {activePluginIndex > -1 && plugins[activePluginIndex]?.enabled ? ( <Box display="flex" justifyContent="flex-start" gap={2}> ...
@@ -130,8 +130,8 @@ export const PluginsChooser = ({ plugins }: { plugins: PluginEntry[] }) => { </Box> )} </MenuButton> - <Box position="fixed" zIndex="1"> - <MenuList left="-150px" position="absolute" w="280px"> + <Box position="fixed" zIndex="2"> + <Me...
website/src/components/Chat/PluginsChooser.tsx
26
TypeScript
0.071
suggestion
43
51
51
false
Plugins fixes
3,070
LAION-AI/Open-Assistant
29,137
Python
notmd
draganjovanovich
Review this pull request change. Language: TypeScript File: website/src/components/Chat/PluginsChooser.tsx PR Title: Plugins fixes BEFORE CODE: return ( <FormControl ref={containerRef}> <Menu placement="auto"> <MenuButton as={Button} pr="3" rightIcon={<Cog />} size="lg" width="100%"> {...
Can you revert this? Already fixed in my PR
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
"--anonymizer-seed", type=int, help="Seed for the anonymizer. If not specified, no anonymization will be performed.", ) parser.add_argument( "--from-date", type=parse_date, help="Only export chats created on or after this date. Format: YYYY-MM-DD", ) parse...
We could just call this `--scored` for simplicity
help="Seed for the anonymizer. If not specified, no anonymization will be performed.", ) parser.add_argument( "--from-date", type=parse_date, help="Only export chats created on or after this date. Format: YYYY-MM-DD", ) parser.add_argument( "--to-date", ty...
@@ -219,19 +228,68 @@ def parse_args() -> argparse.Namespace: type=int, help="Seed for the anonymizer. If not specified, no anonymization will be performed.", ) - # TODO: filters: reported, score, user ID, chat ID, etc - # TODO: date range? + parser.add_argument( + "--from-date", ...
inference/server/export.py
26
Python
0.286
suggestion
49
51
51
false
Improve inference export script
3,071
LAION-AI/Open-Assistant
29,137
Python
olliestanley
simonusher
Review this pull request change. Language: Python File: inference/server/export.py PR Title: Improve inference export script BEFORE CODE: "--anonymizer-seed", type=int, help="Seed for the anonymizer. If not specified, no anonymization will be performed.", ) parser.add_argument( ...
We could just call this `--scored` for simplicity
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
if not file: raise RuntimeError("File name must be specified when using compression.") out_buff = gzip.open(file, "wt", encoding="UTF-8") else: out_buff = smart_open(file) with out_buff as f: for chat in chats: if write_trees: export_chat ...
This isn't really to do with your PR, but could you also add `not_(DbChat.deleted)` here? I forgot to include it when originally developing this script
if not file: raise RuntimeError("File name must be specified when using compression.") out_buff = gzip.open(file, "wt", encoding="UTF-8") else: out_buff = smart_open(file) with out_buff as f: for chat in chats: if write_trees: export_chat ...
@@ -163,13 +164,16 @@ def write_messages_to_file( f.write("\n") -async def fetch_eligible_chats(session_generator) -> list[DbChat]: - """Fetch chats which are not opted out of data collection.""" +async def fetch_eligible_chats( + session_generator, filters: list[sqlalchemy.sql.elements.B...
inference/server/export.py
26
Python
0.571
suggestion
151
51
51
false
Improve inference export script
3,071
LAION-AI/Open-Assistant
29,137
Python
olliestanley
simonusher
Review this pull request change. Language: Python File: inference/server/export.py PR Title: Improve inference export script BEFORE CODE: if not file: raise RuntimeError("File name must be specified when using compression.") out_buff = gzip.open(file, "wt", encoding="UTF-8") else: ...
This isn't really to do with your PR, but could you also add `not_(DbChat.deleted)` here? I forgot to include it when originally developing this script
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
type=parse_date, help="Only export chats created on or after this date. Format: YYYY-MM-DD", ) parser.add_argument( "--to-date", type=parse_date, help="Only export chats created on or before this date. Format: YYYY-MM-DD", ) parser.add_argument( "--user-id...
Could we use `action="store_true"` for these filters? Would just keep it consistent with other boolean args for this and other scripts
type=parse_date, help="Only export chats created on or after this date. Format: YYYY-MM-DD", ) parser.add_argument( "--to-date", type=parse_date, help="Only export chats created on or before this date. Format: YYYY-MM-DD", ) parser.add_argument( "--user-id...
@@ -219,19 +226,68 @@ def parse_args() -> argparse.Namespace: type=int, help="Seed for the anonymizer. If not specified, no anonymization will be performed.", ) - # TODO: filters: reported, score, user ID, chat ID, etc - # TODO: date range? + parser.add_argument( + "--from-date", ...
inference/server/export.py
26
Python
0.571
suggestion
134
51
51
false
Improve inference export script
3,071
LAION-AI/Open-Assistant
29,137
Python
olliestanley
simonusher
Review this pull request change. Language: Python File: inference/server/export.py PR Title: Improve inference export script BEFORE CODE: type=parse_date, help="Only export chats created on or after this date. Format: YYYY-MM-DD", ) parser.add_argument( "--to-date", type=pars...
Could we use `action="store_true"` for these filters? Would just keep it consistent with other boolean args for this and other scripts
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
gap="1" height="full" minH="0" display="flex" flexDirection="column" bg="whiteAlpha.400" _dark={{ bg: "blackAlpha.400", }} {...props} > <Flex> <CreateChatButton py="5" leftIcon={<Plus size="16px" />} variant="o...
Can you make it a selection instead? So user can select visible chat, hidden chat, trainable chat, and maybe shared chat in the future
flexDirection="column" bg="whiteAlpha.400" _dark={{ bg: "blackAlpha.400", }} {...props} > <Flex flexDirection={["column", "row"]} alignItems="stretch" p="2" gap="3"> <CreateChatButton leftIcon={<Plus size="16px" />} variant="outline" ...
@@ -78,19 +80,22 @@ export const ChatListBase = memo(function ChatListBase({ }} {...props} > - <CreateChatButton - py="5" - leftIcon={<Plus size="16px"></Plus>} - variant="outline" - justifyContent="start" - colorScheme="blue" - borderRadius="lg" - ...
website/src/components/Chat/ChatListBase.tsx
26
TypeScript
0.429
suggestion
134
49
45
false
Show hidden chats in chat list
3,075
LAION-AI/Open-Assistant
29,137
Python
notmd
AbdBarho
Review this pull request change. Language: TypeScript File: website/src/components/Chat/ChatListBase.tsx PR Title: Show hidden chats in chat list BEFORE CODE: gap="1" height="full" minH="0" display="flex" flexDirection="column" bg="whiteAlpha.400" _dark={{ bg: "blac...
Can you make it a selection instead? So user can select visible chat, hidden chat, trainable chat, and maybe shared chat in the future
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import { Box } from "@chakra-ui/react"; import { useTranslation } from "next-i18next"; import { memo, ReactNode } from "react"; import SimpleBar from "simplebar-react"; export const ChatConfigDesktop = memo(function ChatConfigDesktop({ children }: { children: ReactNode }) { const { t } = useTranslation("chat"); re...
if min and max are the same, can we just use `w`?
import { Box } from "@chakra-ui/react"; import { useTranslation } from "next-i18next"; import { memo, ReactNode } from "react"; export const ChatConfigDesktop = memo(function ChatConfigDesktop({ children }: { children: ReactNode }) { const { t } = useTranslation("chat"); return ( <Box py="4" pl="4"...
@@ -14,6 +13,7 @@ export const ChatConfigDesktop = memo(function ChatConfigDesktop({ children }: { minH="0" flexDirection="column" minW="270px" + maxW="270px"
website/src/components/Chat/ChatConfigDesktop.tsx
16
TypeScript
0.286
question
49
37
29
false
Allow to save custom preset
3,079
LAION-AI/Open-Assistant
29,137
Python
AbdBarho
notmd
Review this pull request change. Language: TypeScript File: website/src/components/Chat/ChatConfigDesktop.tsx PR Title: Allow to save custom preset BEFORE CODE: import { Box } from "@chakra-ui/react"; import { useTranslation } from "next-i18next"; import { memo, ReactNode } from "react"; import SimpleBar from "simp...
if min and max are the same, can we just use `w`?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
""" @managed_tx_function(CommitMode.COMMIT) def emoji_tx(session: deps.Session): pr = PromptRepository(session, api_client, client_user=request.user) return pr.handle_message_emoji(message_id, request.op, request.emoji) return utils.prepare_message(emoji_tx()) @router.get("/search", ...
Can you merge this to the /cursor endpoint?
from datetime import datetime from typing import Optional from uuid import UUID from fastapi import APIRouter, Depends, Query from loguru import logger from oasst_backend.api import deps from oasst_backend.api.v1 import utils from oasst_backend.models import ApiClient, MessageTreeState from oasst_backend.prompt_reposi...
@@ -354,3 +354,21 @@ def emoji_tx(session: deps.Session): return pr.handle_message_emoji(message_id, request.op, request.emoji) return utils.prepare_message(emoji_tx()) + + +@router.get("/search", response_model=list[protocol.Message]) +def search_messages( + *, + query: str, + lang: str, + ...
backend/oasst_backend/api/v1/messages.py
26
Python
0.071
question
43
27
359
false
Backend support for message search
3,080
LAION-AI/Open-Assistant
29,137
Python
notmd
olliestanley
Review this pull request change. Language: Python File: backend/oasst_backend/api/v1/messages.py PR Title: Backend support for message search BEFORE CODE: """ @managed_tx_function(CommitMode.COMMIT) def emoji_tx(session: deps.Session): pr = PromptRepository(session, api_client, client_user=requ...
Can you merge this to the /cursor endpoint?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
@app.task(name="hf_feature_extraction") def hf_feature_extraction(text, message_id, api_client): try: with default_session_factory() as session: model_name: str = HfEmbeddingModel.MINILM.value url: str = HfUrl.HUGGINGFACE_FEATURE_EXTRACTION.value embedding = async_to_sync...
Should we limit the messages returned from db here? On the first run, it will load about 160k messages at once, which might break the server
@app.task(name="hf_feature_extraction") def hf_feature_extraction(text, message_id, api_client): try: with default_session_factory() as session: model_name: str = HfEmbeddingModel.MINILM.value url: str = HfUrl.HUGGINGFACE_FEATURE_EXTRACTION.value embedding = async_to_sync...
@@ -67,6 +69,23 @@ def hf_feature_extraction(text, message_id, api_client): logger.error(f"Could not extract embedding for text reply to {message_id=} with {text=} by.error {str(e)}") +@shared_task(name="update_search_vectors") +def update_search_vectors(batch_size: int) -> None: + logger.info("update_s...
backend/oasst_backend/scheduled_tasks.py
26
Python
0.429
question
140
51
51
false
Backend support for message search
3,080
LAION-AI/Open-Assistant
29,137
Python
notmd
olliestanley
Review this pull request change. Language: Python File: backend/oasst_backend/scheduled_tasks.py PR Title: Backend support for message search BEFORE CODE: @app.task(name="hf_feature_extraction") def hf_feature_extraction(text, message_id, api_client): try: with default_session_factory() as session: ...
Should we limit the messages returned from db here? On the first run, it will load about 160k messages at once, which might break the server
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
from enum import IntEnum from functools import wraps from http import HTTPStatus from typing import Callable from loguru import logger from oasst_backend.config import settings from oasst_backend.database import engine from oasst_shared.exceptions import OasstError, OasstErrorCode from psycopg2.errors import DeadlockD...
The front end recently has a few new translation langs, can you check it?
from enum import IntEnum from functools import wraps from http import HTTPStatus from typing import Callable from loguru import logger from oasst_backend.config import settings from oasst_backend.database import engine from oasst_shared.exceptions import OasstError, OasstErrorCode from psycopg2.errors import DeadlockD...
@@ -15,6 +15,37 @@ Error Handling Reference: https://www.postgresql.org/docs/15/mvcc-serialization-failure-handling.html """ +TEXT_SEARCH_LANGUAGE_MAPPING: dict[str, str] = {
backend/oasst_backend/utils/database_utils.py
18
Python
0.214
question
73
43
43
false
Backend support for message search
3,080
LAION-AI/Open-Assistant
29,137
Python
notmd
olliestanley
Review this pull request change. Language: Python File: backend/oasst_backend/utils/database_utils.py PR Title: Backend support for message search BEFORE CODE: from enum import IntEnum from functools import wraps from http import HTTPStatus from typing import Callable from loguru import logger from oasst_backend.c...
The front end recently has a few new translation langs, can you check it?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
FlaggedMessage, Message, MessageEmbedding, MessageEmoji, MessageReaction, MessageToxicity, MessageTreeState, Task, TextLabels, User, message_tree_state, ) from oasst_backend.models.payload_column_type import PayloadContainer from oasst_backend.task_repository import TaskRepos...
I don't think we should have random TODOs like this, if we want to embark on adding docstrings throughout the code we should raise a GitHub issue for it instead
FlaggedMessage, Message, MessageEmbedding, MessageEmoji, MessageReaction, MessageRevision, MessageToxicity, MessageTreeState, Task, TextLabels, User, message_tree_state, ) from oasst_backend.models.payload_column_type import PayloadContainer from oasst_backend.task_reposi...
@@ -39,6 +39,9 @@ from sqlalchemy.orm.attributes import flag_modified from sqlmodel import JSON, Session, and_, func, literal_column, not_, or_, text, update +# TODO: Add doc string to all methods and classes.
backend/oasst_backend/prompt_repository.py
26
Python
0.429
suggestion
160
51
51
false
Make send report message from discord a celery task.
3,089
LAION-AI/Open-Assistant
29,137
Python
olliestanley
espoirMur
Review this pull request change. Language: Python File: backend/oasst_backend/prompt_repository.py PR Title: Make send report message from discord a celery task. BEFORE CODE: FlaggedMessage, Message, MessageEmbedding, MessageEmoji, MessageReaction, MessageToxicity, MessageTreeState, ...
I don't think we should have random TODOs like this, if we want to embark on adding docstrings throughout the code we should raise a GitHub issue for it instead
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
from __future__ import absolute_import, unicode_literals from datetime import datetime from typing import Any, Dict, List from asgiref.sync import async_to_sync from celery import shared_task from loguru import logger from oasst_backend.celery_worker import app as celery_app from oasst_backend.models import ApiClient...
I also don't think this should be a TODO, for now we have very few tasks so one file is file and probably will be for a long time
from __future__ import absolute_import, unicode_literals from datetime import timedelta from typing import Any, Dict, List from asgiref.sync import async_to_sync from celery import shared_task from loguru import logger from oasst_backend.celery_worker import app from oasst_backend.models import ApiClient, Message, Us...
@@ -15,6 +15,8 @@ from oasst_shared.utils import utcnow from sqlmodel import select +# TODO: move each task to a separate file in the future to avoid cluttering this file
backend/oasst_backend/scheduled_tasks.py
18
Python
0.429
suggestion
129
43
43
false
Make send report message from discord a celery task.
3,089
LAION-AI/Open-Assistant
29,137
Python
olliestanley
espoirMur
Review this pull request change. Language: Python File: backend/oasst_backend/scheduled_tasks.py PR Title: Make send report message from discord a celery task. BEFORE CODE: from __future__ import absolute_import, unicode_literals from datetime import datetime from typing import Any, Dict, List from asgiref.sync i...
I also don't think this should be a TODO, for now we have very few tasks so one file is file and probably will be for a long time
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
OasstErrorCode.TEXT_LABELS_DUPLICATE_TASK_REPLY, ) message.review_count += 1 self.db.add(message) self.db.add(model) return model, task, message def fetch_random_message_tree( self, require_role: str = Non...
So I think what we want to do here is add this to a queue (maybe in the backend Redis) and then run the Celery task on a timer, which will send all recently flagged messages as a single Discord message, this way we can avoid spamming Discord with API calls on every flag
if not task.collective: task.done = True self.db.add(task) logger.debug(f"inserting TextLabels for {message_id=}, {text_labels_id=}") model = TextLabels( id=text_labels_id, api_client_id=self.api_client.id, message_id=messa...
@@ -547,7 +549,7 @@ def store_text_labels(self, text_labels: protocol_schema.TextLabels) -> tuple[Te message_id, protocol_schema.EmojiOp.add, protocol_schema.EmojiCode.red_flag ) - discord.send_new_report_message(message=message, label_text=text_labels....
backend/oasst_backend/prompt_repository.py
26
Python
0.5
suggestion
270
51
51
false
Make send report message from discord a celery task.
3,089
LAION-AI/Open-Assistant
29,137
Python
olliestanley
espoirMur
Review this pull request change. Language: Python File: backend/oasst_backend/prompt_repository.py PR Title: Make send report message from discord a celery task. BEFORE CODE: OasstErrorCode.TEXT_LABELS_DUPLICATE_TASK_REPLY, ) message.review_count += 1 ...
So I think what we want to do here is add this to a queue (maybe in the backend Redis) and then run the Celery task on a timer, which will send all recently flagged messages as a single Discord message, this way we can avoid spamming Discord with API calls on every flag
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
logger.warning(f"JSON is still not valid, trying to fix it with LLM {fixed_json}") # if it's still not valid, try with LLM fixer prompt = f"""{V2_PROMPTER_PREFIX}Below is malformed JSON object string: -------------- {json_str} -------------- Parsing error: -------------- {e} RULES: ...
This code could just be something like: ``` best_match, best_similarity = max( ((tool, similarity(tool.name, tool_name)) for tool in tools), key=lambda x: x[1], default=(None, 0), ) ```
logger.warning(f"JSON is still not valid, trying to fix it with LLM {fixed_json}") # if it's still not valid, try with LLM fixer prompt = f"""{V2_PROMPTER_PREFIX}Below is malformed JSON object string: -------------- {json_str} -------------- Parsing error: -------------- {e} RULES: ...
@@ -162,12 +162,17 @@ def prepare_json(json_str: str) -> str: def use_tool(tool_name: str, tool_input: str, tools: list) -> str: + best_match = None
inference/worker/chat_chain_utils.py
26
Python
0.857
suggestion
227
51
51
false
Use the tool with the highest similarity instead of the first one over 75%
3,100
LAION-AI/Open-Assistant
29,137
Python
olliestanley
someone13574
Review this pull request change. Language: Python File: inference/worker/chat_chain_utils.py PR Title: Use the tool with the highest similarity instead of the first one over 75% BEFORE CODE: logger.warning(f"JSON is still not valid, trying to fix it with LLM {fixed_json}") # if it's still no...
This code could just be something like: ``` best_match, best_similarity = max( ((tool, similarity(tool.name, tool_name)) for tool in tools), key=lambda x: x[1], default=(None, 0), ) ```
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
const useAutoScroll = (messages: InferenceMessage[], streamedResponse: string | null) => { const enableAutoScroll = useRef(true); const messagesEndRef = useRef<HTMLDivElement>(null); const chatContainerRef = useRef<HTMLDivElement>(null); const updateEnableAutoScroll = useCallback(() => { const container = c...
Does this happen on submit? or does it run always?
<ChatWarning /> </Box> ); }); const useAutoScroll = (messages: InferenceMessage[], streamedResponse: string | null) => { const enableAutoScroll = useRef(true); const messagesEndRef = useRef<HTMLDivElement>(null); const chatContainerRef = useRef<HTMLDivElement>(null); const updateEnableAutoScroll = ...
@@ -327,7 +327,12 @@ const useAutoScroll = (messages: InferenceMessage[], streamedResponse: string | } messagesEndRef.current?.scrollIntoView({ behavior: "smooth" }); - }, [messages, streamedResponse]); + }, [streamedResponse]); + + useEffect(() => { + messagesEndRef.current?.scrollIntoView({ behavior...
website/src/components/Chat/ChatConversation.tsx
26
TypeScript
0.214
question
50
46
51
false
Scroll to end of chat on submit
3,189
LAION-AI/Open-Assistant
29,137
Python
AbdBarho
someone13574
Review this pull request change. Language: TypeScript File: website/src/components/Chat/ChatConversation.tsx PR Title: Scroll to end of chat on submit BEFORE CODE: const useAutoScroll = (messages: InferenceMessage[], streamedResponse: string | null) => { const enableAutoScroll = useRef(true); const messagesEndR...
Does this happen on submit? or does it run always?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
error_message: str | None = None status: Literal["success", "failure"] class PluginUsed(pydantic.BaseModel): name: str | None = None url: str | None = None trusted: bool | None = None execution_details: PluginExecutionDetails def make_seed() -> int: return random.randint(0, 0xFFFF_FFFF_F...
```suggestion plugin_max_depth: int = 4 ``` maybe use the same default everywhere?
error_message: str | None = None status: Literal["success", "failure"] class PluginUsed(pydantic.BaseModel): name: str | None = None url: str | None = None trusted: bool | None = None execution_details: PluginExecutionDetails def make_seed() -> int: return random.randint(0, 0xFFFF_FFFF_F...
@@ -201,6 +201,7 @@ class WorkParameters(pydantic.BaseModel): default_factory=make_seed, ) plugins: list[PluginEntry] = pydantic.Field(default_factory=list[PluginEntry]) + plugin_max_depth: int = 6
oasst-shared/oasst_shared/schemas/inference.py
26
Python
0.643
question
89
51
51
false
Add inference server setting to control max depth of plugins
3,227
LAION-AI/Open-Assistant
29,137
Python
andreaskoepf
olliestanley
Review this pull request change. Language: Python File: oasst-shared/oasst_shared/schemas/inference.py PR Title: Add inference server setting to control max depth of plugins BEFORE CODE: error_message: str | None = None status: Literal["success", "failure"] class PluginUsed(pydantic.BaseModel): name: ...
```suggestion plugin_max_depth: int = 4 ``` maybe use the same default everywhere?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
await handle_generated_text_response( work_request_map=work_request_map, response=worker_response, ) await _update_session(worker_response.metrics) ...
This should probably just be "plugin_intermediate" to match others
await handle_generated_text_response( work_request_map=work_request_map, response=worker_response, ) await _update_session(worker_response.metrics) ...
@@ -218,6 +218,12 @@ def _add_receive(ftrs: set): response=worker_response, work_request_map=work_request_map, ) + case "plugin_intermediate_response":
inference/server/oasst_inference_server/routes/workers.py
26
Python
0.286
suggestion
66
51
51
false
Plugins intermediate steps reporting
3,238
LAION-AI/Open-Assistant
29,137
Python
olliestanley
draganjovanovich
Review this pull request change. Language: Python File: inference/server/oasst_inference_server/routes/workers.py PR Title: Plugins intermediate steps reporting BEFORE CODE: await handle_generated_text_response( work_request_map=work_request_map, ...
This should probably just be "plugin_intermediate" to match others
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
inner_monologue.append("In: " + str(init_prompt)) inner_monologue.append("Out: " + str(chain_response)) current_action_thought = "" if THOUGHT_SEQ in chain_response: current_action_thought = chain_response.split(THOUGHT_SEQ)[1].split("\n")[0] # Tool name/assistant prefix, Tool input/assist...
This seems to have been a bad merge with main - `MAX_DEPTH` constant doesn't exist anymore, should be using the `plugin_max_depth` parameter
inner_monologue.append("In: " + str(init_prompt)) inner_monologue.append("Out: " + str(chain_response)) current_action_thought = "" if THOUGHT_SEQ in chain_response: current_action_thought = chain_response.split(THOUGHT_SEQ)[1].split("\n")[0] # Tool name/assistant prefix, Tool input/assist...
@@ -142,18 +145,47 @@ def handle_plugin_usage( tokenizer, worker_config, parameters, prompt_template, memory, tool_names, language, action_input_format ) + # send "thinking..." intermediate step to UI (This will discard queue position 0) immediately + utils.send_response( + ws, + inf...
inference/worker/chat_chain.py
26
Python
0.571
suggestion
140
51
51
false
Plugins intermediate steps reporting
3,238
LAION-AI/Open-Assistant
29,137
Python
olliestanley
draganjovanovich
Review this pull request change. Language: Python File: inference/worker/chat_chain.py PR Title: Plugins intermediate steps reporting BEFORE CODE: inner_monologue.append("In: " + str(init_prompt)) inner_monologue.append("Out: " + str(chain_response)) current_action_thought = "" if THOUGHT_SEQ in ch...
This seems to have been a bad merge with main - `MAX_DEPTH` constant doesn't exist anymore, should be using the `plugin_max_depth` parameter
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
await onToken(tokens); } else if (chunk.event_type === "message") { // final message return chunk.message; } else if (chunk.event_type === "error") { // handle error await onError(chunk.error); return chunk.message; } else { console.error("Unexpe...
Why do we need to change to log? I think error will make more sense here
} else if (event === "ping") { continue; } try { const chunk: InferenceEvent = JSON.parse(data); if (chunk.event_type === "pending") { await onPending({ queuePosition: chunk.queue_position, queueSize: chunk.queue_size }); } else if (chunk.event_type === "token") { tok...
@@ -39,8 +48,15 @@ export async function handleChatEventStream({ // handle error await onError(chunk.error); return chunk.message; + } else if (chunk.event_type === "plugin_intermediate") { + await onPluginIntermediateResponse({ + currentPluginThought: chunk.current_plugi...
website/src/lib/chat_stream.ts
26
TypeScript
0.429
question
72
51
51
false
Plugins intermediate steps reporting
3,238
LAION-AI/Open-Assistant
29,137
Python
notmd
draganjovanovich
Review this pull request change. Language: TypeScript File: website/src/lib/chat_stream.ts PR Title: Plugins intermediate steps reporting BEFORE CODE: await onToken(tokens); } else if (chunk.event_type === "message") { // final message return chunk.message; } else if (chunk.event...
Why do we need to change to log? I think error will make more sense here
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
const messagesEndRef = useRef<HTMLDivElement>(null); const chatContainerRef = useRef<HTMLDivElement>(null); const updateEnableAutoScroll = useCallback(() => { const container = chatContainerRef.current; if (!container) { return; } const isEnable = container.scrollHeight - container.scrollTo...
Have you check UI in the light mode?
<Box position="absolute" bottom="0" left="50%" transform="translate(-50%)" display="flex" flexDirection="row" gap="1" justifyContent="center" alignItems="center" > <Box ...
@@ -305,6 +313,33 @@ export const ChatConversation = memo(function ChatConversation({ chatId, getConf {t("queue_info", queueInfo)} </Badge> )} + {pluginIntermediateResponse && pluginIntermediateResponse.currentPluginThought && ( + <Box + position="absolute" + ...
website/src/components/Chat/ChatConversation.tsx
26
TypeScript
0.071
question
36
44
51
false
Plugins intermediate steps reporting
3,238
LAION-AI/Open-Assistant
29,137
Python
notmd
draganjovanovich
Review this pull request change. Language: TypeScript File: website/src/components/Chat/ChatConversation.tsx PR Title: Plugins intermediate steps reporting BEFORE CODE: const messagesEndRef = useRef<HTMLDivElement>(null); const chatContainerRef = useRef<HTMLDivElement>(null); const updateEnableAutoScroll = us...
Have you check UI in the light mode?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
return limited_images def truncate_paragraphs(paragraphs, max_length): truncated_paragraphs = [] current_length = 0 for paragraph in paragraphs: if current_length + len(paragraph) <= max_length: truncated_paragraphs.append(paragraph) current_length += len(paragraph) ...
Is there a reason we need to use `httpx` over `aiohttp` here? The server already depends on `aiohttp` so we could reduce dependencies by using it, if possible
current_length += url_length return limited_images def truncate_paragraphs(paragraphs, max_length): truncated_paragraphs = [] current_length = 0 for paragraph in paragraphs: if len(paragraph) == 0: continue paragraph = paragraph.strip() if current_length +...
@@ -0,0 +1,253 @@ +import codecs +import io +import json +import re +from pathlib import Path + +import httpx +import PyPDF2 +import yaml +from bs4 import BeautifulSoup +from fastapi import FastAPI, Query, Request, Response +from fastapi.middleware.cors import CORSMiddleware +from fastapi.openapi.utils import get_opena...
inference/server/oasst_inference_server/plugins/web_retriever/main.py
26
Python
0.571
suggestion
158
51
51
false
Add Dragan's web retriever plugin
3,277
LAION-AI/Open-Assistant
29,137
Python
olliestanley
andreaskoepf
Review this pull request change. Language: Python File: inference/server/oasst_inference_server/plugins/web_retriever/main.py PR Title: Add Dragan's web retriever plugin BEFORE CODE: return limited_images def truncate_paragraphs(paragraphs, max_length): truncated_paragraphs = [] current_length = 0 ...
Is there a reason we need to use `httpx` over `aiohttp` here? The server already depends on `aiohttp` so we could reduce dependencies by using it, if possible
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
text_yaml = f"text_content: {MULTILINE_SYM}\n" for line in text.split("\n"): text_yaml += f" {line}\n" images_yaml = "images:\n" if len(images) > 0 else "" for image in images: images_yaml += f"- {image}\n" yaml_text = f"{text_yaml}\n{images_yaml}" ...
would it be simpler to: ```py from starlette.responses import FileResponse @app.get("/icon.png", include_in_schema=False) async def api_icon(): return FileResponse(folder_path / "icon.png") ```
error_message = f"Sorry, unsupported content type '{content_type}' at {url}.\nYou should report this message to the user!" return JSONResponse(content={"error": error_message}, status_code=500) images = [f"http:{url}" if url.startswith("//") else url for url in images] images = ...
@@ -0,0 +1,253 @@ +import codecs +import io +import json +import re +from pathlib import Path + +import httpx +import PyPDF2 +import yaml +from bs4 import BeautifulSoup +from fastapi import FastAPI, Query, Request, Response +from fastapi.middleware.cors import CORSMiddleware +from fastapi.openapi.utils import get_opena...
inference/server/oasst_inference_server/plugins/web_retriever/main.py
26
Python
0.786
suggestion
208
51
51
false
Add Dragan's web retriever plugin
3,277
LAION-AI/Open-Assistant
29,137
Python
AbdBarho
andreaskoepf
Review this pull request change. Language: Python File: inference/server/oasst_inference_server/plugins/web_retriever/main.py PR Title: Add Dragan's web retriever plugin BEFORE CODE: text_yaml = f"text_content: {MULTILINE_SYM}\n" for line in text.split("\n"): text_yaml += f" {line}\n" ...
would it be simpler to: ```py from starlette.responses import FileResponse @app.get("/icon.png", include_in_schema=False) async def api_icon(): return FileResponse(folder_path / "icon.png") ```
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
@router.delete("/{message_id}", status_code=HTTP_204_NO_CONTENT) def mark_message_deleted( *, message_id: UUID, frontend_user: deps.FrontendUserId = Depends(deps.get_frontend_user_id), api_client: ApiClient = Depends(deps.get_trusted_api_client), db: Session = Depends(deps.get_db), ): pr = Prom...
nit: I think this should be 200, since it is processed immediately.
@router.delete("/{message_id}", status_code=HTTP_204_NO_CONTENT) def mark_message_deleted( *, message_id: UUID, frontend_user: deps.FrontendUserId = Depends(deps.get_frontend_user_id), api_client: ApiClient = Depends(deps.get_trusted_api_client), db: Session = Depends(deps.get_db), ): pr = Prom...
@@ -339,6 +339,18 @@ def undelete_message( pr.undelete_deleted_message(message_id) +@router.post("/{message_id}/edit", status_code=HTTP_202_ACCEPTED)
backend/oasst_backend/api/v1/messages.py
26
Python
0.286
suggestion
67
51
51
false
Moderator Message Editing
3,280
LAION-AI/Open-Assistant
29,137
Python
AbdBarho
someone13574
Review this pull request change. Language: Python File: backend/oasst_backend/api/v1/messages.py PR Title: Moderator Message Editing BEFORE CODE: @router.delete("/{message_id}", status_code=HTTP_204_NO_CONTENT) def mark_message_deleted( *, message_id: UUID, frontend_user: deps.FrontendUserId = Depends(...
nit: I think this should be 200, since it is processed immediately.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
from datetime import datetime from typing import Optional from uuid import UUID, uuid4 import sqlalchemy as sa import sqlalchemy.dialects.postgresql as pg from sqlmodel import Field, SQLModel from .payload_column_type import PayloadContainer, payload_column_type class MessageRevision(SQLModel, table=True): __ta...
would it be possible to use uuid7?
from datetime import datetime from typing import Optional from uuid import UUID import sqlalchemy as sa import sqlalchemy.dialects.postgresql as pg from sqlmodel import Field, SQLModel from uuid_extensions import uuid7 from .payload_column_type import PayloadContainer, payload_column_type class MessageRevision(SQLM...
@@ -0,0 +1,31 @@ +from datetime import datetime +from typing import Optional +from uuid import UUID, uuid4
backend/oasst_backend/models/message_revision.py
3
Python
0.143
question
34
28
26
false
Moderator Message Editing
3,280
LAION-AI/Open-Assistant
29,137
Python
AbdBarho
someone13574
Review this pull request change. Language: Python File: backend/oasst_backend/models/message_revision.py PR Title: Moderator Message Editing BEFORE CODE: from datetime import datetime from typing import Optional from uuid import UUID, uuid4 import sqlalchemy as sa import sqlalchemy.dialects.postgresql as pg from s...
would it be possible to use uuid7?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import sqlalchemy.dialects.postgresql as pg from sqlmodel import Field, SQLModel from .payload_column_type import PayloadContainer, payload_column_type class MessageRevision(SQLModel, table=True): __tablename__ = "message_revision" id: UUID = Field( sa_column=sa.Column( pg.UUID(as_uuid=T...
could this be null if there are no previous revisions?
from datetime import datetime from typing import Optional from uuid import UUID import sqlalchemy as sa import sqlalchemy.dialects.postgresql as pg from sqlmodel import Field, SQLModel from uuid_extensions import uuid7 from .payload_column_type import PayloadContainer, payload_column_type class MessageRevision(SQLM...
@@ -0,0 +1,31 @@ +from datetime import datetime +from typing import Optional +from uuid import UUID, uuid4 + +import sqlalchemy as sa +import sqlalchemy.dialects.postgresql as pg +from sqlmodel import Field, SQLModel + +from .payload_column_type import PayloadContainer, payload_column_type + + +class MessageRevision(SQ...
backend/oasst_backend/models/message_revision.py
26
Python
0.429
question
54
27
26
false
Moderator Message Editing
3,280
LAION-AI/Open-Assistant
29,137
Python
AbdBarho
someone13574
Review this pull request change. Language: Python File: backend/oasst_backend/models/message_revision.py PR Title: Moderator Message Editing BEFORE CODE: import sqlalchemy.dialects.postgresql as pg from sqlmodel import Field, SQLModel from .payload_column_type import PayloadContainer, payload_column_type class M...
could this be null if there are no previous revisions?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
cell: ({ getValue, row }) => { const limit = 95; const text = getValue(); const isActive = row.original.isActive; const renderText = isActive ? text : text.length > limit ? `${text.slice(0, limit)}...` : text; return ( <Box wordBreak="break-all" whi...
can you use `marginStart` or `ms` instead of `ml`? for RTL
cell: ({ getValue, row }) => { const limit = 95; const text = getValue(); const isActive = row.original.isActive; const renderText = isActive ? text : text.length > limit ? `${text.slice(0, limit)}...` : text; return ( <Box wordBreak="break-all" whi...
@@ -150,7 +150,16 @@ export const AdminMessageTable = ({ userId, includeUser }: { userId?: string; in Deleted </Badge> )} - {row.original.review_result === false && <Badge colorScheme="yellow">Spam</Badge>} + {row.original.review_result === fa...
website/src/components/Messages/AdminMessageTable.tsx
26
TypeScript
0.429
suggestion
58
51
51
false
Moderator Message Editing
3,280
LAION-AI/Open-Assistant
29,137
Python
AbdBarho
someone13574
Review this pull request change. Language: TypeScript File: website/src/components/Messages/AdminMessageTable.tsx PR Title: Moderator Message Editing BEFORE CODE: cell: ({ getValue, row }) => { const limit = 95; const text = getValue(); const isActive = row.original.isActive; ...
can you use `marginStart` or `ms` instead of `ml`? for RTL
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
const router = useRouter(); const [messageText, setMessageText] = useState(""); const [submitting, setSubmitting] = useBoolean(false); const { data, isLoading, error } = useSWRImmutable<{ tree: MessageWithChildren | null; message?: Message }>( `/api/admin/messages/${id}/tree`, get, { keepPreviousDa...
please `useCallback` on all of these functions
const { t } = useTranslation(["common", "tasks"]); const router = useRouter(); const [messageText, setMessageText] = useState(""); const { trigger: submitEdit, isMutating: submitting } = useSWRMutation(API_ROUTES.ADMIN_EDIT_MESSAGE(id), post, { onSuccess: () => { router.push(ROUTES.ADMIN_MESSAGE_DETA...
@@ -0,0 +1,176 @@ +import { + Box, + Button, + Card, + CardBody, + Flex, + Stack, + Tab, + TabList, + TabPanel, + TabPanels, + Tabs, + Text, + useColorModeValue, +} from "@chakra-ui/react"; +import { GetServerSideProps, InferGetServerSidePropsType } from "next"; +import Head from "next/head"; +import { use...
website/src/pages/admin/edit/[id].tsx
26
TypeScript
0.286
suggestion
46
51
51
false
Moderator Message Editing
3,280
LAION-AI/Open-Assistant
29,137
Python
AbdBarho
someone13574
Review this pull request change. Language: TypeScript File: website/src/pages/admin/edit/[id].tsx PR Title: Moderator Message Editing BEFORE CODE: const router = useRouter(); const [messageText, setMessageText] = useState(""); const [submitting, setSubmitting] = useBoolean(false); const { data, isLoading, ...
please `useCallback` on all of these functions
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
() => ( <Suspense fallback={messageText}> <RenderedMarkdown markdown={messageText}></RenderedMarkdown> </Suspense> ), [messageText] ); const getThreadFromTree = (tree: MessageWithChildren | null, targetMessageId: string) => { if (!tree) { return null; } if (tree.i...
would it be an option to use swr mutations? https://swr.vercel.app/docs/mutation#useswrmutation This would also eliminate the need for `isSubmitting`
setMessageText(data.message.text); } }, [data]); const previewContent = useMemo( () => ( <Suspense fallback={messageText}> <RenderedMarkdown markdown={messageText}></RenderedMarkdown> </Suspense> ), [messageText] ); const getThreadFromTree = useCallback((tree: Message...
@@ -0,0 +1,176 @@ +import { + Box, + Button, + Card, + CardBody, + Flex, + Stack, + Tab, + TabList, + TabPanel, + TabPanels, + Tabs, + Text, + useColorModeValue, +} from "@chakra-ui/react"; +import { GetServerSideProps, InferGetServerSidePropsType } from "next"; +import Head from "next/head"; +import { use...
website/src/pages/admin/edit/[id].tsx
26
TypeScript
0.571
question
155
51
51
false
Moderator Message Editing
3,280
LAION-AI/Open-Assistant
29,137
Python
AbdBarho
someone13574
Review this pull request change. Language: TypeScript File: website/src/pages/admin/edit/[id].tsx PR Title: Moderator Message Editing BEFORE CODE: () => ( <Suspense fallback={messageText}> <RenderedMarkdown markdown={messageText}></RenderedMarkdown> </Suspense> ), [messageText] ); ...
would it be an option to use swr mutations? https://swr.vercel.app/docs/mutation#useswrmutation This would also eliminate the need for `isSubmitting`
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
onClick={handleSubmit} isLoading={submitting} loadingText={"Submitting"} > {t("common:submit")} </Button> </Flex> </Stack> </> </TwoColumnsWithCards> ...
no need to define the individual namespaces here, `await serverSideTranslations(locale)` is good enough.
isLoading={submitting} loadingText={"Submitting"} > {t("common:submit")} </Button> </Flex> </Stack> </> </TwoColumnsWithCards> </AdminArea> )} </> ); };...
@@ -0,0 +1,176 @@ +import { + Box, + Button, + Card, + CardBody, + Flex, + Stack, + Tab, + TabList, + TabPanel, + TabPanels, + Tabs, + Text, + useColorModeValue, +} from "@chakra-ui/react"; +import { GetServerSideProps, InferGetServerSidePropsType } from "next"; +import Head from "next/head"; +import { use...
website/src/pages/admin/edit/[id].tsx
26
TypeScript
0.5
suggestion
104
31
30
false
Moderator Message Editing
3,280
LAION-AI/Open-Assistant
29,137
Python
AbdBarho
someone13574
Review this pull request change. Language: TypeScript File: website/src/pages/admin/edit/[id].tsx PR Title: Moderator Message Editing BEFORE CODE: onClick={handleSubmit} isLoading={submitting} loadingText={"Submitting"} > ...
no need to define the individual namespaces here, `await serverSideTranslations(locale)` is good enough.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
@router.delete("/{message_id}", status_code=HTTP_204_NO_CONTENT) def mark_message_deleted( *, message_id: UUID, frontend_user: deps.FrontendUserId = Depends(deps.get_frontend_user_id), api_client: ApiClient = Depends(deps.get_trusted_api_client), db: Session = Depends(deps.get_db), ): pr = Prom...
I don't think `HTTP_200_OK` needs specifying
@router.delete("/{message_id}", status_code=HTTP_204_NO_CONTENT) def mark_message_deleted( *, message_id: UUID, frontend_user: deps.FrontendUserId = Depends(deps.get_frontend_user_id), api_client: ApiClient = Depends(deps.get_trusted_api_client), db: Session = Depends(deps.get_db), ): pr = Prom...
@@ -339,6 +339,18 @@ def undelete_message( pr.undelete_deleted_message(message_id) +@router.post("/{message_id}/edit", status_code=HTTP_200_OK)
backend/oasst_backend/api/v1/messages.py
26
Python
0.214
suggestion
44
51
51
false
Moderator Message Editing
3,280
LAION-AI/Open-Assistant
29,137
Python
olliestanley
someone13574
Review this pull request change. Language: Python File: backend/oasst_backend/api/v1/messages.py PR Title: Moderator Message Editing BEFORE CODE: @router.delete("/{message_id}", status_code=HTTP_204_NO_CONTENT) def mark_message_deleted( *, message_id: UUID, frontend_user: deps.FrontendUserId = Depends(...
I don't think `HTTP_200_OK` needs specifying
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
from datetime import datetime from typing import Optional from uuid import UUID import sqlalchemy as sa import sqlalchemy.dialects.postgresql as pg from sqlmodel import Field, SQLModel from uuid_extensions import uuid7 from .payload_column_type import PayloadContainer, payload_column_type class MessageRevision(SQLM...
Why is this `Optional` even though it is not `nullable`?
from datetime import datetime from typing import Optional from uuid import UUID import sqlalchemy as sa import sqlalchemy.dialects.postgresql as pg from sqlmodel import Field, SQLModel from uuid_extensions import uuid7 from .payload_column_type import PayloadContainer, payload_column_type class MessageRevision(SQLM...
@@ -0,0 +1,25 @@ +from datetime import datetime +from typing import Optional +from uuid import UUID + +import sqlalchemy as sa +import sqlalchemy.dialects.postgresql as pg +from sqlmodel import Field, SQLModel +from uuid_extensions import uuid7 + +from .payload_column_type import PayloadContainer, payload_column_type +...
backend/oasst_backend/models/message_revision.py
23
Python
0.5
question
56
26
26
false
Moderator Message Editing
3,280
LAION-AI/Open-Assistant
29,137
Python
olliestanley
someone13574
Review this pull request change. Language: Python File: backend/oasst_backend/models/message_revision.py PR Title: Moderator Message Editing BEFORE CODE: from datetime import datetime from typing import Optional from uuid import UUID import sqlalchemy as sa import sqlalchemy.dialects.postgresql as pg from sqlmodel...
Why is this `Optional` even though it is not `nullable`?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
"payload": payload, } if "tags" in details: tag_name = details["tags"][0] endpoint_data["tag"] = tag_name endpoint = inference.PluginOpenAPIEndpoint(**endpoint_data) return endpoint def get_plugin_endpoints(api_url: str, openapi_dict: dict) -> list[inference.PluginOpenAPIEndp...
Could we restore this? Feels a bit cleaner than an extra layer of nesting in the below code
"payload": payload, } if "tags" in details: tag_name = details["tags"][0] endpoint_data["tag"] = tag_name endpoint = inference.PluginOpenAPIEndpoint(**endpoint_data) return endpoint def get_plugin_endpoints(api_url: str, openapi_dict: dict) -> list[inference.PluginOpenAPIEndp...
@@ -135,19 +140,20 @@ def get_plugin_endpoints(api_url: str, openapi_dict: dict) -> list[inference.Plu def prepare_plugin_for_llm(plugin_url: str) -> inference.PluginConfig | None: plugin_config = get_plugin_config(plugin_url) - if not plugin_config:
inference/worker/openapi_parser.py
26
Python
0.286
suggestion
91
48
49
false
fix for plugins openapi parser
3,316
LAION-AI/Open-Assistant
29,137
Python
olliestanley
draganjovanovich
Review this pull request change. Language: Python File: inference/worker/openapi_parser.py PR Title: fix for plugins openapi parser BEFORE CODE: "payload": payload, } if "tags" in details: tag_name = details["tags"][0] endpoint_data["tag"] = tag_name endpoint = inference.Plugin...
Could we restore this? Feels a bit cleaner than an extra layer of nesting in the below code
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
message = self.db.query(Message).filter(Message.id == message_id).one_or_none() if fail_if_missing and not message: raise OasstError("Message not found", OasstErrorCode.MESSAGE_NOT_FOUND, HTTPStatus.NOT_FOUND) return message def fetch_non_task_text_labels(self, message_id: UUID...
Could you maybe add a comment here that we sort by the date part of the uuid7? Might not be directly obvious to everyone...
message = self.db.query(Message).filter(Message.id == message_id).one_or_none() if fail_if_missing and not message: raise OasstError("Message not found", OasstErrorCode.MESSAGE_NOT_FOUND, HTTPStatus.NOT_FOUND) return message def fetch_non_task_text_labels(self, message_id: UUID...
@@ -800,6 +800,15 @@ def fetch_message_text_labels(self, message_id: UUID, user_id: Optional[UUID] = query = query.filter(TextLabels.user_id == user_id) return query.all() + def fetch_message_revision_history(self, message_id: UUID) -> list[MessageRevision]: + revisions: list[MessageRe...
backend/oasst_backend/prompt_repository.py
26
Python
0.429
question
123
51
51
false
Edit history viewer
3,322
LAION-AI/Open-Assistant
29,137
Python
andreaskoepf
someone13574
Review this pull request change. Language: Python File: backend/oasst_backend/prompt_repository.py PR Title: Edit history viewer BEFORE CODE: message = self.db.query(Message).filter(Message.id == message_id).one_or_none() if fail_if_missing and not message: raise OasstError("Message not...
Could you maybe add a comment here that we sort by the date part of the uuid7? Might not be directly obvious to everyone...
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
export interface MessageHistoryTableProps { message: Message; revisions: MessageRevision[]; } export function MessageHistoryTable({ message, revisions }: MessageHistoryTableProps) { const { t } = useTranslation(["message"]); const router = useRouter(); return ( <Stack spacing={4}> {(revisions.leng...
You can use `Omit<MessageRevision, ...>` here to avoid lengthy code
export interface MessageHistoryTableProps { message: Message; revisions: MessageRevision[]; } export function MessageHistoryTable({ message, revisions }: MessageHistoryTableProps) { const { t } = useTranslation(["message"]); const router = useRouter(); return ( <Stack spacing={4}> {(revisions.leng...
@@ -0,0 +1,85 @@ +import { Badge, Flex, Stack, Tooltip } from "@chakra-ui/react"; +import { boolean } from "boolean"; +import { User } from "lucide-react"; +import { useRouter } from "next/router"; +import { useTranslation } from "next-i18next"; +import { ROUTES } from "src/lib/routes"; +import { Message, MessageRevisi...
website/src/components/Messages/MessageHistoryTable.tsx
26
TypeScript
0.429
suggestion
67
51
51
false
Edit history viewer
3,322
LAION-AI/Open-Assistant
29,137
Python
notmd
someone13574
Review this pull request change. Language: TypeScript File: website/src/components/Messages/MessageHistoryTable.tsx PR Title: Edit history viewer BEFORE CODE: export interface MessageHistoryTableProps { message: Message; revisions: MessageRevision[]; } export function MessageHistoryTable({ message, revisions }...
You can use `Omit<MessageRevision, ...>` here to avoid lengthy code
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
}), })) || []), ], false ); }, [mutateChatResponses] ); const handleCreateChat = useCallback(() => { mutateChatResponses(); }, [mutateChatResponses]); return ( <Box gap="1" height="full" minH="0" display="flex" flexDirec...
why do we need zIndex on this? Isn't it is the last layer by default?
}), })) || []), ], false ); }, [mutateChatResponses] ); const handleCreateChat = useCallback(() => { mutateChatResponses(); }, [mutateChatResponses]); const content = ( <> {chats.map((chat) => ( <ChatListItem key={chat.id} ...
@@ -79,6 +79,7 @@ export const ChatListBase = memo(function ChatListBase({ bg: "blackAlpha.400", }} {...props} + zIndex="var(--chakra-zIndices-base)"
website/src/components/Chat/ChatListBase.tsx
26
TypeScript
0.214
question
69
51
51
false
Bug Fix: Delete feature (Fixes three issues)
3,383
LAION-AI/Open-Assistant
29,137
Python
notmd
CertifiedJoon
Review this pull request change. Language: TypeScript File: website/src/components/Chat/ChatListBase.tsx PR Title: Bug Fix: Delete feature (Fixes three issues) BEFORE CODE: }), })) || []), ], false ); }, [mutateChatResponses] ); const handleCreateChat = useCa...
why do we need zIndex on this? Isn't it is the last layer by default?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
const { trigger: updateChatTitle, isMutating: isUpdatingTitle } = useSWRMutation(API_ROUTES.UPDATE_CHAT(), put); const handleConfirmEdit = useCallback(async () => { const title = inputRef.current?.value.trim(); if (!title) return; await updateChatTitle({ chat_id: chat.id, title }); setIsEditing.off(...
Please revert this. Using a tag is much more better than JS
const handleConfirmEdit = useCallback(async () => { const title = inputRef.current?.value.trim(); if (!title) return; await updateChatTitle({ chat_id: chat.id, title }); setIsEditing.off(); onUpdateTitle({ chatId: chat.id, title }); }, [chat.id, onUpdateTitle, setIsEditing, updateChatTitle]); ...
@@ -78,7 +78,7 @@ export const ChatListItem = ({ <Button // @ts-expect-error error due to dynamically changing as prop ref={rootRef} - {...(!isEditing ? { as: Link, href: ROUTES.CHAT(chat.id) } : { as: "div" })} + // {...(!isEditing ? { as: Link, href: ROUTES.CHAT(chat.id) } : { as: "div" }...
website/src/components/Chat/ChatListItem.tsx
26
TypeScript
0.286
suggestion
59
51
51
false
Bug Fix: Delete feature (Fixes three issues)
3,383
LAION-AI/Open-Assistant
29,137
Python
notmd
CertifiedJoon
Review this pull request change. Language: TypeScript File: website/src/components/Chat/ChatListItem.tsx PR Title: Bug Fix: Delete feature (Fixes three issues) BEFORE CODE: const { trigger: updateChatTitle, isMutating: isUpdatingTitle } = useSWRMutation(API_ROUTES.UPDATE_CHAT(), put); const handleConfirmEdit = ...
Please revert this. Using a tag is much more better than JS
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import { Button, ButtonProps, Modal, ModalBody, ModalCloseButton, ModalContent, ModalFooter, ModalHeader, ModalOverlay, useDisclosure, } from "@chakra-ui/react"; import { useTranslation } from "next-i18next"; interface SkipButtonProps extends ButtonProps { onSkip: () => void; confirmSkip: boole...
Also can you only show the modal when the input is not empty?
import { Button, ButtonProps, Modal, ModalBody, ModalCloseButton, ModalContent, ModalFooter, ModalHeader, ModalOverlay, useDisclosure, } from "@chakra-ui/react"; import { useTranslation } from "next-i18next"; interface SkipButtonProps extends ButtonProps { onSkip: () => void; confirmSkip: boole...
@@ -0,0 +1,62 @@ +import { + Button, + ButtonProps, + Modal, + ModalBody, + ModalCloseButton, + ModalContent, + ModalFooter, + ModalHeader, + ModalOverlay, + useDisclosure, +} from "@chakra-ui/react"; +import { useTranslation } from "next-i18next"; + +interface SkipButtonProps extends ButtonProps { + onSkip:...
website/src/components/Buttons/Skip.tsx
26
TypeScript
0.214
question
61
51
51
false
Added confirmation dialog when skipping after entering text
3,479
LAION-AI/Open-Assistant
29,137
Python
notmd
MehrJonas
Review this pull request change. Language: TypeScript File: website/src/components/Buttons/Skip.tsx PR Title: Added confirmation dialog when skipping after entering text BEFORE CODE: import { Button, ButtonProps, Modal, ModalBody, ModalCloseButton, ModalContent, ModalFooter, ModalHeader, ModalOver...
Also can you only show the modal when the input is not empty?
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
s.add(id); result.set(authType, s); return result; }, new Map()); const authOptions: AuthOptions = { // Ensure we can store user data in a database. adapter: PrismaAdapter(prisma), providers, session: { strategy: "jwt", }, pages: { signIn: "/auth/signin", verifyRequest: "/auth/verify", ...
You can receive image from user property in the callback here
result.set(authType, s); return result; }, new Map()); const authOptions: AuthOptions = { // Ensure we can store user data in a database. adapter: PrismaAdapter(prisma), providers, session: { strategy: "jwt", }, pages: { signIn: "/auth/signin", verifyRequest: "/auth/verify", // error: "...
@@ -127,60 +126,44 @@ const authOptions: AuthOptions = { session.user.role = token.role; session.user.isNew = token.isNew; session.user.name = token.name; + session.user.image = token.picture;
website/src/pages/api/auth/[...nextauth].ts
26
TypeScript
0.286
suggestion
61
51
51
false
Update profile image on login
3,491
LAION-AI/Open-Assistant
29,137
Python
notmd
AbdBarho
Review this pull request change. Language: TypeScript File: website/src/pages/api/auth/[...nextauth].ts PR Title: Update profile image on login BEFORE CODE: s.add(id); result.set(authType, s); return result; }, new Map()); const authOptions: AuthOptions = { // Ensure we can store user data in a database. ...
You can receive image from user property in the callback here
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
if (showEncourageMessage) { onEncourageMessageClose(); } }, [chatId, messageId, onEncourageMessageClose, onVote, score, showEncourageMessage] ); const handleThumbsUp = useCallback(() => { handleVote("+1"); }, [handleVote]); const handleThumbsDown = useCallback(() => { handl...
This probably has no effect, you can remove this.
const newScore = getNewScore(emoji, score); onVote({ newScore, chatId, messageId, oldScore: score }); if (showEncourageMessage) { onEncourageMessageClose(); } }, [chatId, messageId, onEncourageMessageClose, onVote, score, showEncourageMessage] ); const handleThumbsUp = useCa...
@@ -92,7 +92,9 @@ export const ChatMessageEntry = memo(function ChatMessageEntry({ const isAssistant = message.role === "assistant"; const [isEditing, setIsEditing] = useBoolean(false); + const [isPlainText, setIsPlainText] = useState<boolean>(false); const inputRef = useRef<HTMLTextAreaElement>(null); + c...
website/src/components/Chat/ChatMessageEntry.tsx
26
TypeScript
0.143
refactor
49
51
51
false
Add: option to view plaintext chat message. Issue/2508
3,496
LAION-AI/Open-Assistant
29,137
Python
notmd
CertifiedJoon
Review this pull request change. Language: TypeScript File: website/src/components/Chat/ChatMessageEntry.tsx PR Title: Add: option to view plaintext chat message. Issue/2508 BEFORE CODE: if (showEncourageMessage) { onEncourageMessageClose(); } }, [chatId, messageId, onEncourageMessageClo...
This probably has no effect, you can remove this.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
bg: "gray.800", }} autoFocus ></Textarea> </Box> )} {!isEditing && ( <Flex justifyContent={pagingSlot ? "space-between" : "end"} mt="1"> {pagingSlot} {isAssistant && ( <MessageInlineEmojiRow...
Can you adjust icon base on the `isPlainText` state? I think using these two icons will make more sense https://tabler-icons.io/i/markdown-off https://tabler-icons.io/i/markdown Just copy the SVG, we don't need to install the lib
borderRadius="xl" _dark={{ bg: "gray.800", }} autoFocus ></Textarea> </Box> )} {!isEditing && ( <Flex justifyContent={pagingSlot ? "space-between" : "end"} mt="1"> {pagingSlot} ...
@@ -175,6 +177,12 @@ export const ChatMessageEntry = memo(function ChatMessageEntry({ )} {state === "complete" && ( <> + <BaseMessageEmojiButton
website/src/components/Chat/ChatMessageEntry.tsx
26
TypeScript
0.571
suggestion
235
51
51
false
Add: option to view plaintext chat message. Issue/2508
3,496
LAION-AI/Open-Assistant
29,137
Python
notmd
CertifiedJoon
Review this pull request change. Language: TypeScript File: website/src/components/Chat/ChatMessageEntry.tsx PR Title: Add: option to view plaintext chat message. Issue/2508 BEFORE CODE: bg: "gray.800", }} autoFocus ></Textarea> </Box> )} ...
Can you adjust icon base on the `isPlainText` state? I think using these two icons will make more sense https://tabler-icons.io/i/markdown-off https://tabler-icons.io/i/markdown Just copy the SVG, we don't need to install the lib
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
tokenizer=pythia_tokenizer, padding=True, system_add_length=False, ) features = [ create_dataset_entry_qa( mode="sft", questions=["Dummy Question?"], answers=["Dummy Answer."], ) ] batch = d(features) expected_decoded_input_...
From a swollen rump, to "too" :joy:
tokenizer=pythia_tokenizer, padding=True, system_add_length=False, ) features = [ create_dataset_entry_qa( mode="sft", questions=["Dummy Question?"], answers=["Dummy Answer."], ) ] batch = d(features) expected_decoded_input_...
@@ -53,7 +53,7 @@ def test_dataset_entry_no_context(pythia_tokenizer): # check if targets are as expected assert pythia_tokenizer.decode(batch.targets[0]) == expected_decoded_targets[0] - # check if masking is correct. Note that we mask the system aswell + # check if masking is correct. Note that we m...
model/model_training/tests/test_dialogue_data_collator.py
26
Python
0.071
suggestion
35
51
51
false
fix typos
3,543
LAION-AI/Open-Assistant
29,137
Python
bitplane
RainRat
Review this pull request change. Language: Python File: model/model_training/tests/test_dialogue_data_collator.py PR Title: fix typos BEFORE CODE: tokenizer=pythia_tokenizer, padding=True, system_add_length=False, ) features = [ create_dataset_entry_qa( mode="sft"...
From a swollen rump, to "too" :joy:
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import torch # rotary pos emb helpers (torch.jit.script does not seem to support staticmethod...) def rotate_half(x): x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :] return torch.cat((-x2, x1), dim=x1.ndim - 1) # dim=-1 triggers a bug in torch < 1.8.0 class RWNTKScaledRope(torch.nn.Module):...
Could you add some comments about the origin of these rope scaling variants? Were they copied from the [scaled-rope](https://github.com/jquesnelle/scaled-rope) repository? If they were imported from a different place we should add a proper attribution.
import torch # rotary pos emb helpers (torch.jit.script does not seem to support staticmethod...) def rotate_half(x): x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :] return torch.cat((-x2, x1), dim=x1.ndim - 1) # dim=-1 triggers a bug in torch < 1.8.0 class RWNTKScaledRope(torch.nn.Module):...
@@ -0,0 +1,175 @@ +import torch + + +# rotary pos emb helpers (torch.jit.script does not seem to support staticmethod...) +def rotate_half(x): + x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :] + return torch.cat((-x2, x1), dim=x1.ndim - 1) # dim=-1 triggers a bug in torch < 1.8.0 + + +class RWNTK...
model/model_training/models/rope.py
10
Python
0.5
question
252
35
35
false
Add RoPE Interpolation
3,564
LAION-AI/Open-Assistant
29,137
Python
andreaskoepf
shahules786
Review this pull request change. Language: Python File: model/model_training/models/rope.py PR Title: Add RoPE Interpolation BEFORE CODE: import torch # rotary pos emb helpers (torch.jit.script does not seem to support staticmethod...) def rotate_half(x): x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1...
Could you add some comments about the origin of these rope scaling variants? Were they copied from the [scaled-rope](https://github.com/jquesnelle/scaled-rope) repository? If they were imported from a different place we should add a proper attribution.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
if training_conf.use_custom_sampler: samples_length = None if training_conf.sort_by_length: samples_length = list( map( lambda x: train_collate_fn.process_one(x, return_length=True), tqdm(train, desc="Calculating lengths per sample...
Is there a benefit of late import, otherwise I would recommend to move this to the other imports at the beginning of the file (to make it easier to see all main dependencies).
if training_conf.use_custom_sampler: samples_length = None if training_conf.sort_by_length: samples_length = list( map( lambda x: train_collate_fn.process_one(x, return_length=True), tqdm(train, desc="Calculating lengths per sample...
@@ -416,9 +416,14 @@ def main(): sampler = None metrics, preprocess_fns = get_metrics(training_conf, tokenizer) - model = get_model(training_conf, tokenizer) + from model_training.models.patching import RopePatch
model/model_training/trainer_sft.py
26
Python
0.429
refactor
175
51
51
false
Add RoPE Interpolation
3,564
LAION-AI/Open-Assistant
29,137
Python
andreaskoepf
shahules786
Review this pull request change. Language: Python File: model/model_training/trainer_sft.py PR Title: Add RoPE Interpolation BEFORE CODE: if training_conf.use_custom_sampler: samples_length = None if training_conf.sort_by_length: samples_length = list( map( ...
Is there a benefit of late import, otherwise I would recommend to move this to the other imports at the beginning of the file (to make it easier to see all main dependencies).
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
@property def num_requests_in_progress(self) -> int: return len(self.work_request_map) @classmethod async def build(cls, websocket: fastapi.WebSocket, api_key: str, protocol_version: str): try: worker_utils.get_protocol_version(protocol_version) api_key = worker...
Moved to `HandleWorkerContext.build()` without changes
@property def num_requests_in_progress(self) -> int: return len(self.work_request_map) @classmethod async def build(cls, websocket: fastapi.WebSocket, api_key: str, protocol_version: str): try: worker_utils.get_protocol_version(protocol_version) api_key = worker_...
@@ -85,191 +72,319 @@ def get_work_request_container(work_request_map: WorkRequestContainerMap, reques return container -@router.websocket("/work") -async def handle_worker( - websocket: fastapi.WebSocket, - api_key: str = worker_utils.api_key_header, - protocol_version: str = worker_utils.protocol_ve...
inference/server/oasst_inference_server/routes/workers.py
26
Python
0.571
suggestion
54
51
51
false
Cleanup `handle_worker()` in preparation for #2815 (Stop generation early)
3,573
LAION-AI/Open-Assistant
29,137
Python
0xfacade
0xfacade
Review this pull request change. Language: Python File: inference/server/oasst_inference_server/routes/workers.py PR Title: Cleanup `handle_worker()` in preparation for #2815 (Stop generation early) BEFORE CODE: @property def num_requests_in_progress(self) -> int: return len(self.work_request_map) ...
Moved to `HandleWorkerContext.build()` without changes
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
@classmethod async def build(cls, websocket: fastapi.WebSocket, api_key: str, protocol_version: str): try: worker_utils.get_protocol_version(protocol_version) api_key = worker_utils.get_api_key(api_key) worker_id = await worker_utils.get_worker_id(api_key=api_key, pro...
Moved to `SessionManager.init()`
async def build(cls, websocket: fastapi.WebSocket, api_key: str, protocol_version: str): try: worker_utils.get_protocol_version(protocol_version) api_key = worker_utils.get_api_key(api_key) worker_id = await worker_utils.get_worker_id(api_key=api_key, protocol_version=pro...
@@ -85,191 +72,319 @@ def get_work_request_container(work_request_map: WorkRequestContainerMap, reques return container -@router.websocket("/work") -async def handle_worker( - websocket: fastapi.WebSocket, - api_key: str = worker_utils.api_key_header, - protocol_version: str = worker_utils.protocol_ve...
inference/server/oasst_inference_server/routes/workers.py
26
Python
0.286
suggestion
32
51
51
false
Cleanup `handle_worker()` in preparation for #2815 (Stop generation early)
3,573
LAION-AI/Open-Assistant
29,137
Python
0xfacade
0xfacade
Review this pull request change. Language: Python File: inference/server/oasst_inference_server/routes/workers.py PR Title: Cleanup `handle_worker()` in preparation for #2815 (Stop generation early) BEFORE CODE: @classmethod async def build(cls, websocket: fastapi.WebSocket, api_key: str, protocol_version: ...
Moved to `SessionManager.init()`
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
except fastapi.HTTPException as e: logger.warning(f"handle_worker: {e.status_code=} {e.detail=}") if e.status_code == fastapi.status.HTTP_426_UPGRADE_REQUIRED: await worker_utils.send_worker_request(websocket=websocket, request=inference.UpgradeProtocolRequest()) ...
Moved to `SessionManager.update()`
logger.warning(f"handle_worker: {e.status_code=} {e.detail=}") if e.status_code == fastapi.status.HTTP_426_UPGRADE_REQUIRED: await worker_utils.send_worker_request(websocket=websocket, request=inference.UpgradeProtocolRequest()) elif e.status_code == fastapi.status.HT...
@@ -85,191 +72,319 @@ def get_work_request_container(work_request_map: WorkRequestContainerMap, reques return container -@router.websocket("/work") -async def handle_worker( - websocket: fastapi.WebSocket, - api_key: str = worker_utils.api_key_header, - protocol_version: str = worker_utils.protocol_ve...
inference/server/oasst_inference_server/routes/workers.py
26
Python
0.286
suggestion
34
51
51
false
Cleanup `handle_worker()` in preparation for #2815 (Stop generation early)
3,573
LAION-AI/Open-Assistant
29,137
Python
0xfacade
0xfacade
Review this pull request change. Language: Python File: inference/server/oasst_inference_server/routes/workers.py PR Title: Cleanup `handle_worker()` in preparation for #2815 (Stop generation early) BEFORE CODE: except fastapi.HTTPException as e: logger.warning(f"handle_worker: {e.status_code=} ...
Moved to `SessionManager.update()`
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
await worker_utils.send_worker_request(websocket=websocket, request=inference.WrongApiKeyRequest()) try: await websocket.close(code=e.status_code, reason=e.detail) except Exception: pass raise fastapi.WebSocketException(e.status_code, e...
Moved to `FuturesManager.ensure_listening_for_work_requests()`. The future is now wrapped such that it returns a `tuple[FutureType, X]` where `X` is the return type of whatever the future returned before.
try: await websocket.close(code=e.status_code, reason=e.detail) except Exception: pass raise fastapi.WebSocketException(e.status_code, e.detail) logger.info(f"handle_worker: {worker_id=}") worker_info = await worker_utils.receive_worke...
@@ -85,191 +72,319 @@ def get_work_request_container(work_request_map: WorkRequestContainerMap, reques return container -@router.websocket("/work") -async def handle_worker( - websocket: fastapi.WebSocket, - api_key: str = worker_utils.api_key_header, - protocol_version: str = worker_utils.protocol_ve...
inference/server/oasst_inference_server/routes/workers.py
26
Python
0.786
suggestion
204
51
51
false
Cleanup `handle_worker()` in preparation for #2815 (Stop generation early)
3,573
LAION-AI/Open-Assistant
29,137
Python
0xfacade
0xfacade
Review this pull request change. Language: Python File: inference/server/oasst_inference_server/routes/workers.py PR Title: Cleanup `handle_worker()` in preparation for #2815 (Stop generation early) BEFORE CODE: await worker_utils.send_worker_request(websocket=websocket, request=inference.WrongApiKe...
Moved to `FuturesManager.ensure_listening_for_work_requests()`. The future is now wrapped such that it returns a `tuple[FutureType, X]` where `X` is the return type of whatever the future returned before.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
except Exception: pass raise fastapi.WebSocketException(e.status_code, e.detail) logger.info(f"handle_worker: {worker_id=}") worker_info = await worker_utils.receive_worker_info(websocket) logger.info(f"handle_worker: {worker_info=}") work_queue...
Moved to `FuturesManager.ensure_listening_for_worker_response()` with similar changes to return the `FutureType` in addition to the response.
pass raise fastapi.WebSocketException(e.status_code, e.detail) logger.info(f"handle_worker: {worker_id=}") worker_info = await worker_utils.receive_worker_info(websocket) logger.info(f"handle_worker: {worker_info=}") work_queue = queueing.work_queue(deps.red...
@@ -85,191 +72,319 @@ def get_work_request_container(work_request_map: WorkRequestContainerMap, reques return container -@router.websocket("/work") -async def handle_worker( - websocket: fastapi.WebSocket, - api_key: str = worker_utils.api_key_header, - protocol_version: str = worker_utils.protocol_ve...
inference/server/oasst_inference_server/routes/workers.py
26
Python
0.714
suggestion
141
51
51
false
Cleanup `handle_worker()` in preparation for #2815 (Stop generation early)
3,573
LAION-AI/Open-Assistant
29,137
Python
0xfacade
0xfacade
Review this pull request change. Language: Python File: inference/server/oasst_inference_server/routes/workers.py PR Title: Cleanup `handle_worker()` in preparation for #2815 (Stop generation early) BEFORE CODE: except Exception: pass raise fastapi.WebSocketException(e.status...
Moved to `FuturesManager.ensure_listening_for_worker_response()` with similar changes to return the `FutureType` in addition to the response.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
return cls( websocket=websocket, worker_id=worker_id, worker_info=worker_info, work_queue=work_queue, blocking_work_queue=blocking_work_queue ) async def close(self): try: await self.blocking_work_queue.redis_client.cl...
Moved to `FuturesManager.wait_for_event_or_timeout()`
websocket=websocket, worker_id=worker_id, worker_info=worker_info, work_queue=work_queue, blocking_work_queue=blocking_work_queue, ) async def close(self): try: await self.blocking_work_queue.redis_client.close() except...
@@ -85,191 +72,319 @@ def get_work_request_container(work_request_map: WorkRequestContainerMap, reques return container -@router.websocket("/work") -async def handle_worker( - websocket: fastapi.WebSocket, - api_key: str = worker_utils.api_key_header, - protocol_version: str = worker_utils.protocol_ve...
inference/server/oasst_inference_server/routes/workers.py
26
Python
0.429
suggestion
53
51
51
false
Cleanup `handle_worker()` in preparation for #2815 (Stop generation early)
3,573
LAION-AI/Open-Assistant
29,137
Python
0xfacade
0xfacade
Review this pull request change. Language: Python File: inference/server/oasst_inference_server/routes/workers.py PR Title: Cleanup `handle_worker()` in preparation for #2815 (Stop generation early) BEFORE CODE: return cls( websocket=websocket, worker_id=worker_id, worke...
Moved to `FuturesManager.wait_for_event_or_timeout()`
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
worker_info=worker_info, work_queue=work_queue, blocking_work_queue=blocking_work_queue ) async def close(self): try: await self.blocking_work_queue.redis_client.close() except Exception: logger.warning("Error while closing redis c...
This is the test that has so far been used to identify a dequeued work request, which has now been replaced by a check for `type_ == FutureType.WORK_REQUEST`
blocking_work_queue=blocking_work_queue, ) async def close(self): try: await self.blocking_work_queue.redis_client.close() except Exception: logger.warning("Error while closing redis client") try: await self.websocket.close() ...
@@ -85,191 +72,319 @@ def get_work_request_container(work_request_map: WorkRequestContainerMap, reques return container -@router.websocket("/work") -async def handle_worker( - websocket: fastapi.WebSocket, - api_key: str = worker_utils.api_key_header, - protocol_version: str = worker_utils.protocol_ve...
inference/server/oasst_inference_server/routes/workers.py
26
Python
0.714
suggestion
157
51
51
false
Cleanup `handle_worker()` in preparation for #2815 (Stop generation early)
3,573
LAION-AI/Open-Assistant
29,137
Python
0xfacade
0xfacade
Review this pull request change. Language: Python File: inference/server/oasst_inference_server/routes/workers.py PR Title: Cleanup `handle_worker()` in preparation for #2815 (Stop generation early) BEFORE CODE: worker_info=worker_info, work_queue=work_queue, blocking_work_queue=...
This is the test that has so far been used to identify a dequeued work request, which has now been replaced by a check for `type_ == FutureType.WORK_REQUEST`
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
WORK_REQUEST = 'WORK_REQUEST' WORKER_RESPONSE = 'WORKER_RESPONSE' AwaitResult = TypeVar('AwaitResult') class FuturesManager: _context: HandleWorkerContext _futures: set[asyncio.Future] def __init__(self, context: HandleWorkerContext): self._context = context self._futures = set()...
Moved to `_handle_work_request`
AwaitResult = TypeVar("AwaitResult") class FuturesManager: _context: HandleWorkerContext _futures: set[asyncio.Future] def __init__(self, context: HandleWorkerContext): self._context = context self._futures = set() def ensure_listening_for_work_requests(self): requests_in_pr...
@@ -85,191 +72,319 @@ def get_work_request_container(work_request_map: WorkRequestContainerMap, reques return container -@router.websocket("/work") -async def handle_worker( - websocket: fastapi.WebSocket, - api_key: str = worker_utils.api_key_header, - protocol_version: str = worker_utils.protocol_ve...
inference/server/oasst_inference_server/routes/workers.py
26
Python
0.429
suggestion
31
51
51
false
Cleanup `handle_worker()` in preparation for #2815 (Stop generation early)
3,573
LAION-AI/Open-Assistant
29,137
Python
0xfacade
0xfacade
Review this pull request change. Language: Python File: inference/server/oasst_inference_server/routes/workers.py PR Title: Cleanup `handle_worker()` in preparation for #2815 (Stop generation early) BEFORE CODE: WORK_REQUEST = 'WORK_REQUEST' WORKER_RESPONSE = 'WORKER_RESPONSE' AwaitResult = TypeVar('AwaitR...
Moved to `_handle_work_request`
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
for ftr in self._futures: try: ftr.cancel() except Exception: logger.warning("Error while cancelling pending future") def _as_typed_future(self, future_type: FutureType, awaitable: Awaitable[AwaitResult]) -> asyncio.Future: async def wrapp...
Moved to `_handle_worker_response()`
logger.info(f"Cancelling {len(self._futures)} pending futures") for ftr in self._futures: try: ftr.cancel() except Exception: logger.warning("Error while cancelling pending future") def _as_typed_future(self, future_type: FutureType, awaitable...
@@ -85,191 +72,319 @@ def get_work_request_container(work_request_map: WorkRequestContainerMap, reques return container -@router.websocket("/work") -async def handle_worker( - websocket: fastapi.WebSocket, - api_key: str = worker_utils.api_key_header, - protocol_version: str = worker_utils.protocol_ve...
inference/server/oasst_inference_server/routes/workers.py
26
Python
0.429
suggestion
36
51
51
false
Cleanup `handle_worker()` in preparation for #2815 (Stop generation early)
3,573
LAION-AI/Open-Assistant
29,137
Python
0xfacade
0xfacade
Review this pull request change. Language: Python File: inference/server/oasst_inference_server/routes/workers.py PR Title: Cleanup `handle_worker()` in preparation for #2815 (Stop generation early) BEFORE CODE: for ftr in self._futures: try: ftr.cancel() except Excep...
Moved to `_handle_worker_response()`
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
async def initiate_work_for_message( *, websocket: fastapi.WebSocket, work_queue: queueing.RedisQueue, message_id: str, worker_id: str, worker_config: inference.WorkerConfig, ) -> inference.WorkRequest: async with deps.manual_create_session() as session: cr = chat_repository.ChatRep...
In order to avoid logical changes as much as possible, I kept this piece of code here as it was, but that now means that it accesses the internal structure of the `FuturesManager`. I'm considering whether it might be nicer to not throw all the futures into a single set, but instead keep one future in a specific vari...
await session.update(worker_response.metrics) case "general_error": worker_response = cast(inference.GeneralErrorResponse, worker_response) await handle_general_error_response( response=worker_response, ) awa...
@@ -85,191 +72,321 @@ def get_work_request_container(work_request_map: WorkRequestContainerMap, reques return container -@router.websocket("/work") -async def handle_worker( - websocket: fastapi.WebSocket, - api_key: str = worker_utils.api_key_header, - protocol_version: str = worker_utils.protocol_ve...
inference/server/oasst_inference_server/routes/workers.py
26
Python
0.786
suggestion
655
51
51
false
Cleanup `handle_worker()` in preparation for #2815 (Stop generation early)
3,573
LAION-AI/Open-Assistant
29,137
Python
0xfacade
0xfacade
Review this pull request change. Language: Python File: inference/server/oasst_inference_server/routes/workers.py PR Title: Cleanup `handle_worker()` in preparation for #2815 (Stop generation early) BEFORE CODE: async def initiate_work_for_message( *, websocket: fastapi.WebSocket, work_queue: queueing....
In order to avoid logical changes as much as possible, I kept this piece of code here as it was, but that now means that it accesses the internal structure of the `FuturesManager`. I'm considering whether it might be nicer to not throw all the futures into a single set, but instead keep one future in a specific vari...
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import transformers # from .gptj import get_model as get_gptj_model SUPPORTED_MODELS = ["galactica", "gpt-j"] def freeze_top_n_layers(model, target_layers): # its possible we can simply detect which module is a ModuleList # and simply freeze the module without doing string parsing for name, param in mod...
so falcon 40B still needs trust_remote_code = True.
def get_specific_model( model_name, seq2seqmodel=False, without_head=False, cache_dir=".cache", quantization=False, **kwargs, ): if without_head: model = transformers.AutoModel.from_pretrained(model_name, cache_dir=cache_dir, **kwargs) elif seq2seqmodel: # encoder-decod...
@@ -25,17 +21,27 @@ def freeze_top_n_layers(model, target_layers): def get_specific_model( - model_name, seq2seqmodel=False, without_head=False, cache_dir=".cache", quantization=False, **kwargs + model_name, + seq2seqmodel=False, + without_head=False, + cache_dir=".cache", + quantization=False, +...
model/model_training/models/__init__.py
26
Python
0.214
suggestion
51
42
28
false
Add flash-attention patch for falcon-7b
3,580
LAION-AI/Open-Assistant
29,137
Python
jordiclive
andreaskoepf
Review this pull request change. Language: Python File: model/model_training/models/__init__.py PR Title: Add flash-attention patch for falcon-7b BEFORE CODE: import transformers # from .gptj import get_model as get_gptj_model SUPPORTED_MODELS = ["galactica", "gpt-j"] def freeze_top_n_layers(model, target_layer...
so falcon 40B still needs trust_remote_code = True.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import torch import torch.nn.functional as F def compute_flash_attention(flash_attn, q, k, v, attention_mask=None, head_mask=None): # q, k, v: [bs, seq_len, num_attention_heads, attn_head_size] # attention_mask (float): [bs, seq_len] batch_size, max_len = q.size(0), q.size(1) qkv = torch.stack([q, k,...
Falcon is torch.bfloat16? Will the casting to float16 pose a problem.
import torch import torch.nn.functional as F def compute_flash_attention(flash_attn, q, k, v, attention_mask=None, head_mask=None): # q, k, v: [bs, seq_len, num_attention_heads, attn_head_size] # attention_mask (float): [bs, seq_len] batch_size, max_len = q.size(0), q.size(1) qkv = torch.stack([q, k,...
@@ -7,11 +7,14 @@ def compute_flash_attention(flash_attn, q, k, v, attention_mask=None, head_mask= # attention_mask (float): [bs, seq_len] batch_size, max_len = q.size(0), q.size(1) - qkv = torch.stack([q, k, v], dim=2).to(torch.float16) # need to truncate in case input is fp32 + qkv = torch.stack([q...
model/model_training/models/patching_utils.py
13
Python
0.357
suggestion
69
38
38
false
Add flash-attention patch for falcon-7b
3,580
LAION-AI/Open-Assistant
29,137
Python
jordiclive
andreaskoepf
Review this pull request change. Language: Python File: model/model_training/models/patching_utils.py PR Title: Add flash-attention patch for falcon-7b BEFORE CODE: import torch import torch.nn.functional as F def compute_flash_attention(flash_attn, q, k, v, attention_mask=None, head_mask=None): # q, k, v: [b...
Falcon is torch.bfloat16? Will the casting to float16 pose a problem.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
def make_prompt_and_parameters( tokenizer: transformers.PreTrainedTokenizer, work_request: inference.WorkRequest, ) -> tuple[str, interface.GenerateStreamParameters]: """Prepare a formatted prompt and stream generation parameters based on a work request.""" if settings.oa_protocol_version != "v2": ...
Can we change this so that the whole custom instruction prefix is not prepended at all if no instructions are given? Otherwise we are just using up tokens for no reason, as the worker retains the system prompt in context always at the cost of other tokens
def make_prompt_and_parameters( tokenizer: transformers.PreTrainedTokenizer, work_request: inference.WorkRequest, ) -> tuple[str, interface.GenerateStreamParameters]: """Prepare a formatted prompt and stream generation parameters based on a work request.""" if settings.oa_protocol_version != "v2": ...
@@ -40,9 +41,17 @@ def _prepare_message(message: inference.MessageRead) -> str: # Construct prompt messages = [_prepare_message(message) for message in work_request.thread.messages] - # Prepend system prompt if it was specified in work parameters - if work_request.parameters.system_prompt: - pr...
inference/worker/work.py
26
Python
0.5
question
255
51
51
false
Custom instructions feature
3,597
LAION-AI/Open-Assistant
29,137
Python
olliestanley
draganjovanovich
Review this pull request change. Language: Python File: inference/worker/work.py PR Title: Custom instructions feature BEFORE CODE: def make_prompt_and_parameters( tokenizer: transformers.PreTrainedTokenizer, work_request: inference.WorkRequest, ) -> tuple[str, interface.GenerateStreamParameters]: """P...
Can we change this so that the whole custom instruction prefix is not prepended at all if no instructions are given? Otherwise we are just using up tokens for no reason, as the worker retains the system prompt in context always at the cost of other tokens
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
try: original_prompt = work_request.thread.messages[-1].content if not original_prompt: raise ValueError("Prompt is empty") language = "English" plugin = next((p for p in parameters.plugins if p.enabled), None) tools_instructions_template, tools = compose_tools_...
Also here - surely if `user_profile` and `user_response_instructions` are empty, we want this value `custom_instructions` to also be an entirely empty string, without the contents of `CUSTOM_INSTRUCTIONS_PREFIX`
try: original_prompt = work_request.thread.messages[-1].content if not original_prompt: raise ValueError("Prompt is empty") language = "English" plugin = next((p for p in parameters.plugins if p.enabled), None) tools_instructions_template, tools = compose_tools_...
@@ -355,11 +379,17 @@ def handle_conversation( "language", "current_time", "action_input_format", + "custom_instructions", ] + (["tools_names"] if plugin_enabled else []) # TODO: Consider passing language from the UI here prompt_template = P...
inference/worker/chat_chain.py
26
Python
0.643
suggestion
211
51
51
false
Custom instructions feature
3,597
LAION-AI/Open-Assistant
29,137
Python
olliestanley
draganjovanovich
Review this pull request change. Language: Python File: inference/worker/chat_chain.py PR Title: Custom instructions feature BEFORE CODE: try: original_prompt = work_request.thread.messages[-1].content if not original_prompt: raise ValueError("Prompt is empty") language = "E...
Also here - surely if `user_profile` and `user_response_instructions` are empty, we want this value `custom_instructions` to also be an entirely empty string, without the contents of `CUSTOM_INSTRUCTIONS_PREFIX`
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
def make_prompt_and_parameters( tokenizer: transformers.PreTrainedTokenizer, work_request: inference.WorkRequest, ) -> tuple[str, interface.GenerateStreamParameters]: """Prepare a formatted prompt and stream generation parameters based on a work request.""" if settings.oa_protocol_version != "v2": ...
This can be simplified a bit (currently the same `if` condition is repeated) ```suggestion work_params = work_request.parameters if work_params.system_prompt or work_params.user_profile or work_params.user_response_instructions: pre_prompt = V2_SYSTEM_PREFIX + (work_params.system_prompt or "") ```
def make_prompt_and_parameters( tokenizer: transformers.PreTrainedTokenizer, work_request: inference.WorkRequest, ) -> tuple[str, interface.GenerateStreamParameters]: """Prepare a formatted prompt and stream generation parameters based on a work request.""" if settings.oa_protocol_version != "v2": ...
@@ -40,9 +41,20 @@ def _prepare_message(message: inference.MessageRead) -> str: # Construct prompt messages = [_prepare_message(message) for message in work_request.thread.messages] - # Prepend system prompt if it was specified in work parameters - if work_request.parameters.system_prompt: - pr...
inference/worker/work.py
26
Python
0.857
suggestion
319
51
51
false
Custom instructions feature
3,597
LAION-AI/Open-Assistant
29,137
Python
olliestanley
draganjovanovich
Review this pull request change. Language: Python File: inference/worker/work.py PR Title: Custom instructions feature BEFORE CODE: def make_prompt_and_parameters( tokenizer: transformers.PreTrainedTokenizer, work_request: inference.WorkRequest, ) -> tuple[str, interface.GenerateStreamParameters]: """Pr...
This can be simplified a bit (currently the same `if` condition is repeated) ```suggestion work_params = work_request.parameters if work_params.system_prompt or work_params.user_profile or work_params.user_response_instructions: pre_prompt = V2_SYSTEM_PREFIX + (work_params.system_prompt or "") ```
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
const resetParameters = (setValue: UseFormSetValue<ChatConfigFormData>, params: SamplingParameters) => { for (const [key, value] of Object.entries(params) as Array<[keyof SamplingParameters, number]>) { setValue(key, value); // call setValue instead of setValues to avoid reset unwanted fields } }; export cons...
This state can be handled by react-hook-form. You just need to wrap the `CustomInstructions` with the `Controller` component.
}; const findPresetName = (presets: ModelParameterConfig[], config: SamplingParameters) => { return ( presets.find((preset) => areParametersEqual(preset.sampling_parameters, config))?.name ?? unKnownCustomPresetName ); }; const resetParameters = (setValue: UseFormSetValue<ChatConfigFormData>, params: Sampling...
@@ -104,6 +111,10 @@ export const ChatConfigForm = memo(function ChatConfigForm() { const selectedModel = getValues("model_config_name"); // have to use getValues to here to access latest value const selectedPlugins = getValues("plugins"); const presets = modelInfos.find((model) => model.name === selectedModel...
website/src/components/Chat/ChatConfigForm.tsx
26
TypeScript
0.643
suggestion
125
51
51
false
Custom instructions feature
3,597
LAION-AI/Open-Assistant
29,137
Python
notmd
draganjovanovich
Review this pull request change. Language: TypeScript File: website/src/components/Chat/ChatConfigForm.tsx PR Title: Custom instructions feature BEFORE CODE: const resetParameters = (setValue: UseFormSetValue<ChatConfigFormData>, params: SamplingParameters) => { for (const [key, value] of Object.entries(params) ...
This state can be handled by react-hook-form. You just need to wrap the `CustomInstructions` with the `Controller` component.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import gzip import json import re from pathlib import Path from typing import List, Optional, Union import requests from datasets import load_dataset from model_training.custom_datasets.formatting import DatasetEntrySft, Role, Utterance from model_training.custom_datasets.oasst_dataset import ListDataset from model_tr...
I should have used shuffle(seed) too in my code ;-) .. will update later.
def __getitem__(self, idx): conversation, instruction = [self.dataset[idx][key] for key in ("conversation", "instruction")] conversation = [(item["input"], item["output"]) for item in conversation] conversation = list(sum(conversation, ())) conv_utt: list[Utterance] = [ ...
@@ -193,3 +194,61 @@ def __getitem__(self, idx): ] return DatasetEntrySft(conversation=conv_utt, system_message=instruction) + + +class DolphinMix(Dataset): + name = "dophin-mix" + + def __init__(self, cache_dir, num_samples=100000, max_char_len=8000, seed=42): + self.dataset = load_dat...
model/model_training/custom_datasets/prompt_dialogue.py
26
Python
0.286
suggestion
73
196
51
false
Dolphin gpt 3.5 data mix
3,606
LAION-AI/Open-Assistant
29,137
Python
andreaskoepf
shahules786
Review this pull request change. Language: Python File: model/model_training/custom_datasets/prompt_dialogue.py PR Title: Dolphin gpt 3.5 data mix BEFORE CODE: import gzip import json import re from pathlib import Path from typing import List, Optional, Union import requests from datasets import load_dataset from ...
I should have used shuffle(seed) too in my code ;-) .. will update later.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import gzip import json import re from pathlib import Path from typing import List, Optional, Union import requests from datasets import load_dataset from model_training.custom_datasets.formatting import DatasetEntrySft, Role, Utterance from model_training.custom_datasets.oasst_dataset import ListDataset from model_tr...
Generating the indices to pick set every time seems a bit costly .. but since it is only done during startup it might be ok.
name = "dophin-mix" def __init__(self, cache_dir, num_samples=100000, max_char_len=8000, seed=42): self.dataset = load_dataset( "ehartford/dolphin", data_files="flan5m-alpaca-uncensored.jsonl", cache_dir=cache_dir ) self.dataset = self.dataset["train"].shuffle(seed).select(r...
@@ -193,3 +194,61 @@ def __getitem__(self, idx): ] return DatasetEntrySft(conversation=conv_utt, system_message=instruction) + + +class DolphinMix(Dataset): + name = "dophin-mix" + + def __init__(self, cache_dir, num_samples=100000, max_char_len=8000, seed=42): + self.dataset = load_dat...
model/model_training/custom_datasets/prompt_dialogue.py
26
Python
0.357
suggestion
125
196
51
false
Dolphin gpt 3.5 data mix
3,606
LAION-AI/Open-Assistant
29,137
Python
andreaskoepf
shahules786
Review this pull request change. Language: Python File: model/model_training/custom_datasets/prompt_dialogue.py PR Title: Dolphin gpt 3.5 data mix BEFORE CODE: import gzip import json import re from pathlib import Path from typing import List, Optional, Union import requests from datasets import load_dataset from ...
Generating the indices to pick set every time seems a bit costly .. but since it is only done during startup it might be ok.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
self.dataset = load_dataset("shahules786/orca-chat", split="train", data_files=data_files, cache_dir=cache_dir) def __len__(self): return len(self.dataset) def __getitem__(self, idx): conversation, instruction = [self.dataset[idx][key] for key in ("conversation", "instruction")] ...
Isn't it better to add `data_files` as an argument with the default value "flan-5m..."? In this way, we can change to gpt-4 version using config if required. `
self.dataset = load_dataset("shahules786/orca-chat", split="train", data_files=data_files, cache_dir=cache_dir) def __len__(self): return len(self.dataset) def __getitem__(self, idx): conversation, instruction = [self.dataset[idx][key] for key in ("conversation", "instruction")] ...
@@ -199,45 +198,37 @@ def __getitem__(self, idx): class DolphinMix(Dataset): name = "dophin-mix" - def __init__(self, cache_dir, num_samples=100000, max_char_len=8000, seed=42): + def __init__(self, cache_dir, num_samples: Optional[int] = None, max_char_len: int = 8000, seed: int = 42):
model/model_training/custom_datasets/prompt_dialogue.py
26
Python
0.571
question
162
51
51
false
Changes for orcacode experiment
3,612
LAION-AI/Open-Assistant
29,137
Python
shahules786
andreaskoepf
Review this pull request change. Language: Python File: model/model_training/custom_datasets/prompt_dialogue.py PR Title: Changes for orcacode experiment BEFORE CODE: self.dataset = load_dataset("shahules786/orca-chat", split="train", data_files=data_files, cache_dir=cache_dir) def __len__(self): ...
Isn't it better to add `data_files` as an argument with the default value "flan-5m..."? In this way, we can change to gpt-4 version using config if required. `
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
</Box> </MenuItem> </MenuList> </Menu> <Modal isOpen={isOpen} onClose={onClose} size="xl" initialFocusRef={textareaRef}> <ModalOverlay /> <ModalContent> <ModalHeader>{t(isCreatePlugin ? "add_plugin" : "edit_plugin")}</ModalHeader> <ModalClose...
if you have a url for installing plugins you could use getitAI's callback mechanism: https://www.getit.ai/gpt-plugins/chat-integration
}} /> </Box> </MenuItem> </MenuList> </Menu> <Modal isOpen={isOpen} onClose={onClose} size="xl" initialFocusRef={textareaRef}> <ModalOverlay /> <ModalContent> <ModalHeader>{t(isCreatePlugin ? "add_plugin" : "edit_plugin")}...
@@ -234,6 +236,16 @@ export const PluginsChooser = ({ plugins, setPlugins }: PluginsChooserProps) => placeholder={t("plugin_url_placeholder")} /> {selectedForEditPluginIndex !== null && <JsonCard>{plugins[selectedForEditPluginIndex]}</JsonCard>} + <Box> + ...
website/src/components/Chat/PluginsChooser.tsx
26
TypeScript
0.429
suggestion
134
51
51
false
Added plugin repositories to add-plugin menu
3,638
LAION-AI/Open-Assistant
29,137
Python
digi604
yk
Review this pull request change. Language: TypeScript File: website/src/components/Chat/PluginsChooser.tsx PR Title: Added plugin repositories to add-plugin menu BEFORE CODE: </Box> </MenuItem> </MenuList> </Menu> <Modal isOpen={isOpen} onClose={onClose} size="xl" initialFo...
if you have a url for installing plugins you could use getitAI's callback mechanism: https://www.getit.ai/gpt-plugins/chat-integration
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
case "REVIEW": return { mode: "EDIT", replyValidity: "VALID" }; case "DEFAULT_WARN": return { mode: "EDIT", replyValidity: "DEFAULT" }; case "SUBMITTED": // allow return to edit from subbmitted mode (error happen during submitting task) ...
No issues found.
case "REVIEW": return { mode: "EDIT", replyValidity: "VALID" }; case "DEFAULT_WARN": return { mode: "EDIT", replyValidity: "DEFAULT" }; case "SUBMITTED": // allow return to edit from subbmitted mode (error happen during submitting task) ...
@@ -1,7 +1,6 @@ import { useToast } from "@chakra-ui/react"; import { useTranslation } from "next-i18next"; -import { useCallback, useEffect, useReducer } from "react"; -import { useMemo, useRef } from "react"; +import { useCallback, useEffect, useMemo, useReducer, useRef } from "react"; import { TaskControls } from...
website/src/components/Tasks/Task/Task.tsx
0
TypeScript
1
none
16
51
51
true
Implemented ability to press ctrl+enter (or cmd+enter) to Review/Subm…
1,237
LAION-AI/Open-Assistant
29,137
Python
cooperaustinj
Review this pull request change. Language: TypeScript File: website/src/components/Tasks/Task/Task.tsx PR Title: Implemented ability to press ctrl+enter (or cmd+enter) to Review/Subm… BEFORE CODE: case "REVIEW": return { mode: "EDIT", replyValidity: "VALID" }; case "DEFAULT_WAR...
No issues found.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import { Button, Flex, Modal, ModalBody, ModalCloseButton, ModalContent, ModalFooter, ModalHeader, ModalOverlay, } from "@chakra-ui/react"; import { useTranslation } from "next-i18next"; interface UnchangedWarningProps { show: boolean; title: string; message: string; continueButtonText: strin...
No issues found.
import { Button, Flex, Modal, ModalBody, ModalCloseButton, ModalContent, ModalFooter, ModalHeader, ModalOverlay, } from "@chakra-ui/react"; import { useTranslation } from "next-i18next"; interface UnchangedWarningProps { show: boolean; title: string; message: string; continueButtonText: strin...
@@ -9,6 +9,7 @@ import { ModalHeader, ModalOverlay, } from "@chakra-ui/react"; +import { useTranslation } from "next-i18next"; interface UnchangedWarningProps { show: boolean; @@ -20,6 +21,8 @@ interface UnchangedWarningProps { } export const UnchangedWarning = (props: UnchangedWarningProps) => { + co...
website/src/components/Tasks/UnchangedWarning.tsx
0
TypeScript
1
none
16
47
47
true
Localize some labels that were missing in the tasks view
1,607
LAION-AI/Open-Assistant
29,137
Python
GuilleHoardings
Review this pull request change. Language: TypeScript File: website/src/components/Tasks/UnchangedWarning.tsx PR Title: Localize some labels that were missing in the tasks view BEFORE CODE: import { Button, Flex, Modal, ModalBody, ModalCloseButton, ModalContent, ModalFooter, ModalHeader, ModalOver...
No issues found.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
except OasstError: raise except Exception: logger.exception("Failed to generate task..") raise OasstError("Failed to generate task.", OasstErrorCode.TASK_GENERATION_FAILED) return task @router.post("/availability", response_model=dict[protocol_schema.TaskRequestType, int]) def tas...
No issues found.
except OasstError: raise except Exception: logger.exception("Failed to generate task..") raise OasstError("Failed to generate task.", OasstErrorCode.TASK_GENERATION_FAILED) return task @router.post("/availability", response_model=dict[protocol_schema.TaskRequestType, int]) def tas...
@@ -34,6 +34,24 @@ minutes=settings.RATE_LIMIT_TASK_API_MINUTES, ) ), + Depends( + deps.UserTaskTypeRateLimiter( + [ + protocol_schema.TaskRequestType.assistant_reply, + ], + times=settings.RATE_LIMI...
backend/oasst_backend/api/v1/tasks.py
0
Python
1
none
16
51
51
true
Implement separate rate limit for message submission tasks
1,747
LAION-AI/Open-Assistant
29,137
Python
olliestanley
Review this pull request change. Language: Python File: backend/oasst_backend/api/v1/tasks.py PR Title: Implement separate rate limit for message submission tasks BEFORE CODE: except OasstError: raise except Exception: logger.exception("Failed to generate task..") raise OasstError("...
No issues found.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
hugging_face_api.headers: Dict[str, str] = {"Authorization": f"Bearer {hugging_face_api.api_key}"} result = await hugging_face_api.post(text) return result @app.task(name="toxicity") def toxicity(text, message_id, api_client): try: logger.info(f"checking toxicity : {api_client}") with...
No issues found.
hugging_face_api.headers: Dict[str, str] = {"Authorization": f"Bearer {hugging_face_api.api_key}"} result = await hugging_face_api.post(text) return result @app.task(name="toxicity") def toxicity(text, message_id, api_client): try: logger.info(f"checking toxicity : {api_client}") with...
@@ -0,0 +1,135 @@ +from __future__ import absolute_import, unicode_literals + +import os +from datetime import datetime +from typing import Any, Dict, List + +from asgiref.sync import async_to_sync +from celery import Celery, shared_task +from dotenv import load_dotenv +from loguru import logger +from oasst_backend.mod...
backend/oasst_backend/celery_worker/scheduled_tasks.py
0
Python
1
none
16
51
51
true
feature: Using Celery for APIs and periodic tasks
1,754
LAION-AI/Open-Assistant
29,137
Python
melvinebenezer
Review this pull request change. Language: Python File: backend/oasst_backend/celery_worker/scheduled_tasks.py PR Title: feature: Using Celery for APIs and periodic tasks BEFORE CODE: hugging_face_api.headers: Dict[str, str] = {"Authorization": f"Bearer {hugging_face_api.api_key}"} result = await hugging_fa...
No issues found.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import Image from "next/image"; export function UserAvatar(options: { displayName: string; avatarUrl: string | null }) { const { displayName, avatarUrl } = options; return ( <> <Image src={ avatarUrl ? avatarUrl : `https://api.dicebear.com/5.x/initials/png?seed=${...
No issues found.
import Image from "next/image"; export function UserAvatar(options: { displayName: string; avatarUrl: string | null }) { const { displayName, avatarUrl } = options; return ( <> <Image src={ avatarUrl ? avatarUrl : `https://api.dicebear.com/5.x/initials/png?seed=${...
@@ -0,0 +1,18 @@ +import Image from "next/image"; +export function UserAvatar(options: { displayName: string; avatarUrl: string | null }) { + const { displayName, avatarUrl } = options; + return ( + <> + <Image + src={ + avatarUrl + ? avatarUrl + : `https://api.dicebear.c...
website/src/components/UserAvatar.tsx
0
TypeScript
1
none
16
19
19
true
Display user avatar in leaderboard
1,767
LAION-AI/Open-Assistant
29,137
Python
mrloldev
Review this pull request change. Language: TypeScript File: website/src/components/UserAvatar.tsx PR Title: Display user avatar in leaderboard BEFORE CODE: import Image from "next/image"; export function UserAvatar(options: { displayName: string; avatarUrl: string | null }) { const { displayName, avatarUrl } = o...
No issues found.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import { Box, Button, Center, Link, Text, theme, useColorModeValue } from "@chakra-ui/react"; import { useTranslation } from "next-i18next"; import { AlertTriangle } from "lucide-react"; import Head from "next/head"; import { EmptyState } from "src/components/EmptyState"; import { getTransparentHeaderLayout } from "src...
No issues found.
import { Box, Button, Center, Link, Text, theme, useColorModeValue } from "@chakra-ui/react"; import { useTranslation } from "next-i18next"; import { AlertTriangle } from "lucide-react"; import Head from "next/head"; import { EmptyState } from "src/components/EmptyState"; import { getTransparentHeaderLayout } from "src...
@@ -1,11 +1,13 @@ import { Box, Button, Center, Link, Text, theme, useColorModeValue } from "@chakra-ui/react"; +import { useTranslation } from "next-i18next"; import { AlertTriangle } from "lucide-react"; import Head from "next/head"; import { EmptyState } from "src/components/EmptyState"; import { getTransparent...
website/src/pages/404.tsx
0
TypeScript
1
none
16
48
48
true
404 [en, ru], edit [en, ru], keeping upd, fixes
1,842
LAION-AI/Open-Assistant
29,137
Python
echo0x22
Review this pull request change. Language: TypeScript File: website/src/pages/404.tsx PR Title: 404 [en, ru], edit [en, ru], keeping upd, fixes BEFORE CODE: import { Box, Button, Center, Link, Text, theme, useColorModeValue } from "@chakra-ui/react"; import { useTranslation } from "next-i18next"; import { AlertTria...
No issues found.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
const toast = useToast(); const handleCopyClick = async (event: MouseEvent) => { event.stopPropagation(); toast.closeAll(); try { await navigator.clipboard.writeText(String(children)); toast({ title: "Copied to clipboard", status: "info", duration: 2000, is...
No issues found.
const toast = useToast(); const handleCopyClick = async (event: MouseEvent) => { event.stopPropagation(); toast.closeAll(); try { await navigator.clipboard.writeText(String(children)); toast({ title: "Copied to clipboard", status: "info", duration: 2000, is...
@@ -0,0 +1,71 @@ +import { Button, Flex, useToast } from "@chakra-ui/react"; +import { Copy, Check } from "lucide-react"; +import { useState, MouseEvent } from "react"; +import { Prism as SyntaxHighlighter } from "react-syntax-highlighter"; +import { oneDark } from "react-syntax-highlighter/dist/cjs/styles/prism"; + +e...
website/src/components/Messages/RenderedCodeblock.tsx
0
TypeScript
1
none
16
51
51
true
Add button to copy code in markdown
1,845
LAION-AI/Open-Assistant
29,137
Python
Slowlife01
Review this pull request change. Language: TypeScript File: website/src/components/Messages/RenderedCodeblock.tsx PR Title: Add button to copy code in markdown BEFORE CODE: const toast = useToast(); const handleCopyClick = async (event: MouseEvent) => { event.stopPropagation(); toast.closeAll(); t...
No issues found.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import { del } from "src/lib/api"; import { API_ROUTES } from "src/lib/routes"; import { mutate } from "swr"; import useSWRMutation from "swr/mutation"; export const useDeleteMessage = (messageId: string) => { return useSWRMutation(API_ROUTES.ADMIN_DELETE_MESSAGE(messageId), del, { onSuccess: async () => { ...
No issues found.
import { del } from "src/lib/api"; import { API_ROUTES } from "src/lib/routes"; import { mutate } from "swr"; import useSWRMutation from "swr/mutation"; export const useDeleteMessage = (messageId: string) => { return useSWRMutation(API_ROUTES.ADMIN_DELETE_MESSAGE(messageId), del, { onSuccess: async () => { ...
@@ -0,0 +1,17 @@ +import { del } from "src/lib/api"; +import { API_ROUTES } from "src/lib/routes"; +import { mutate } from "swr"; +import useSWRMutation from "swr/mutation"; + +export const useDeleteMessage = (messageId: string) => { + return useSWRMutation(API_ROUTES.ADMIN_DELETE_MESSAGE(messageId), del, { + onSuc...
website/src/hooks/message/useDeleteMessage.ts
0
TypeScript
1
none
16
18
18
true
Add ability to Delete Messages From the List View in User Detail View…
1,860
LAION-AI/Open-Assistant
29,137
Python
johnflux
Review this pull request change. Language: TypeScript File: website/src/hooks/message/useDeleteMessage.ts PR Title: Add ability to Delete Messages From the List View in User Detail View… BEFORE CODE: import { del } from "src/lib/api"; import { API_ROUTES } from "src/lib/routes"; import { mutate } from "swr"; import...
No issues found.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import { Button, CircularProgress, Flex, Spacer } from "@chakra-ui/react"; import { useTranslation } from "react-i18next"; import { get } from "src/lib/api"; import { FetchUserMessagesCursorResponse } from "src/types/Conversation"; import useSWRImmutable from "swr/immutable"; import { useCursorPagination } from "./Dat...
No issues found.
import { Button, CircularProgress, Flex, Spacer } from "@chakra-ui/react"; import { useTranslation } from "react-i18next"; import { get } from "src/lib/api"; import { FetchUserMessagesCursorResponse } from "src/types/Conversation"; import useSWRImmutable from "swr/immutable"; import { useCursorPagination } from "./Dat...
@@ -0,0 +1,47 @@ +import { Button, CircularProgress, Flex, Spacer } from "@chakra-ui/react"; +import { useTranslation } from "react-i18next"; +import { get } from "src/lib/api"; +import { FetchUserMessagesCursorResponse } from "src/types/Conversation"; +import useSWRImmutable from "swr/immutable"; + +import { useCursor...
website/src/components/UserMessageConversation.tsx
0
TypeScript
1
none
16
48
48
true
Show all my messages
1,864
LAION-AI/Open-Assistant
29,137
Python
johnflux
Review this pull request change. Language: TypeScript File: website/src/components/UserMessageConversation.tsx PR Title: Show all my messages BEFORE CODE: import { Button, CircularProgress, Flex, Spacer } from "@chakra-ui/react"; import { useTranslation } from "react-i18next"; import { get } from "src/lib/api"; imp...
No issues found.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
@app.get("/auth/callback/discord", response_model=protocol.Token) async def callback_discord( code: str, db: sqlmodel.Session = Depends(deps.create_session), ): redirect_uri = f"{settings.api_root}/auth/callback/discord" async with aiohttp.ClientSession(raise_for_status=True) as session: # Ex...
No issues found.
@app.get("/auth/callback/discord", response_model=protocol.Token) async def callback_discord( code: str, db: sqlmodel.Session = Depends(deps.create_session), ): redirect_uri = f"{settings.api_root}/auth/callback/discord" async with aiohttp.ClientSession(raise_for_status=True) as session: # Ex...
@@ -20,6 +20,16 @@ app = fastapi.FastAPI() +@app.middleware("http") +async def log_exceptions(request: fastapi.Request, call_next): + try: + response = await call_next(request) + except Exception: + logger.exception("Exception in request") + raise + return response + + # add promethe...
inference/server/main.py
0
Python
1
none
16
51
51
true
Various fixes in inference
1,865
LAION-AI/Open-Assistant
29,137
Python
yk
Review this pull request change. Language: Python File: inference/server/main.py PR Title: Various fixes in inference BEFORE CODE: @app.get("/auth/callback/discord", response_model=protocol.Token) async def callback_discord( code: str, db: sqlmodel.Session = Depends(deps.create_session), ): redirect_u...
No issues found.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
special_tokens: SpecialTokens = {} TOKENIZER_CONFIGS = { "galactica": TokenizerConfig(special_tokens=SpecialTokens("<pad>", "</s>")), "GPT-JT": TokenizerConfig(special_tokens=SpecialTokens(sep_token="<|extratoken_100|>")), "codegen": TokenizerConfig(special_tokens=SpecialTokens("<|endoftext|>", sep_to...
No issues found.
special_tokens: SpecialTokens = {} TOKENIZER_CONFIGS = { "galactica": TokenizerConfig(special_tokens=SpecialTokens("<pad>", "</s>")), "GPT-JT": TokenizerConfig(special_tokens=SpecialTokens(sep_token="<|extratoken_100|>")), "codegen": TokenizerConfig(special_tokens=SpecialTokens("<|endoftext|>", sep_to...
@@ -1,3 +1,4 @@ +import copy import random from distutils.util import strtobool from pathlib import Path @@ -12,14 +13,14 @@ from models import freeze_top_n_layers, get_specific_model from sklearn.model_selection import train_test_split from torch.utils.data import ConcatDataset, Subset -from torch.utils.data.sam...
model/model_training/utils.py
0
Python
1
none
16
51
51
true
Distributed Sampler
1,869
LAION-AI/Open-Assistant
29,137
Python
sanagno
Review this pull request change. Language: Python File: model/model_training/utils.py PR Title: Distributed Sampler BEFORE CODE: special_tokens: SpecialTokens = {} TOKENIZER_CONFIGS = { "galactica": TokenizerConfig(special_tokens=SpecialTokens("<pad>", "</s>")), "GPT-JT": TokenizerConfig(special_token...
No issues found.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import { RefObject, useEffect, useState } from "react"; /** * This is a custom hook that returns a ref that can be used to focus an element. * * Use like: * * ``` * const ref = useRef(); * useScrollToElementOnMount(ref); * return <div ref={ref} /> * ``` */ export const useScrollToElementOnMount ...
No issues found.
import { RefObject, useEffect, useState } from "react"; /** * This is a custom hook that returns a ref that can be used to focus an element. * * Use like: * * ``` * const ref = useRef(); * useScrollToElementOnMount(ref); * return <div ref={ref} /> * ``` */ export const useScrollToElementOnMount ...
@@ -0,0 +1,24 @@ +import { RefObject, useEffect, useState } from "react"; + +/** + * This is a custom hook that returns a ref that can be used to focus an element. + * + * Use like: + * + * ``` + * const ref = useRef(); + * useScrollToElementOnMount(ref); + * return <div ref={ref} /> + * ``` + */ +export c...
website/src/hooks/ui/useScrollToElementOnMount.ts
0
TypeScript
1
none
16
25
25
true
Scroll to message when loaded
1,886
LAION-AI/Open-Assistant
29,137
Python
johnflux
Review this pull request change. Language: TypeScript File: website/src/hooks/ui/useScrollToElementOnMount.ts PR Title: Scroll to message when loaded BEFORE CODE: import { RefObject, useEffect, useState } from "react"; /** * This is a custom hook that returns a ref that can be used to focus an element. * * U...
No issues found.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import { Button, Progress } from "@chakra-ui/react"; import Head from "next/head"; import { useTranslation } from "next-i18next"; import { useCallback, useMemo } from "react"; import { getDashboardLayout } from "src/components/Layout"; import { post } from "src/lib/api"; export { getDefaultStaticProps as getStaticProps...
No issues found.
import { Button, Progress } from "@chakra-ui/react"; import Head from "next/head"; import { useTranslation } from "next-i18next"; import { useCallback, useMemo } from "react"; import { getDashboardLayout } from "src/components/Layout"; import { post } from "src/lib/api"; export { getDefaultStaticProps as getStaticProps...
@@ -1,134 +1,46 @@ -import { Box, Button, Flex, Textarea, useColorModeValue } from "@chakra-ui/react"; +import { Button, Progress } from "@chakra-ui/react"; import Head from "next/head"; import { useTranslation } from "next-i18next"; -import { useCallback, useRef, useState } from "react"; +import { useCallback, useMe...
website/src/pages/chat.tsx
0
TypeScript
1
none
16
47
47
true
Add debug auth between Website & Inference
1,893
LAION-AI/Open-Assistant
29,137
Python
AbdBarho
Review this pull request change. Language: TypeScript File: website/src/pages/chat.tsx PR Title: Add debug auth between Website & Inference BEFORE CODE: import { Button, Progress } from "@chakra-ui/react"; import Head from "next/head"; import { useTranslation } from "next-i18next"; import { useCallback, useMemo } f...
No issues found.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import enum from uuid import uuid4 import sqlalchemy as sa import sqlalchemy.dialects.postgresql as pg from oasst_shared.schemas import inference from sqlmodel import Field, Relationship, SQLModel class WorkerEventType(str, enum.Enum): connect = "connect" class DbWorkerComplianceCheck(SQLModel, table=True): ...
No issues found.
import enum from uuid import uuid4 import sqlalchemy as sa import sqlalchemy.dialects.postgresql as pg from oasst_shared.schemas import inference from sqlmodel import Field, Relationship, SQLModel class WorkerEventType(str, enum.Enum): connect = "connect" class DbWorkerComplianceCheck(SQLModel, table=True): ...
@@ -0,0 +1,51 @@ +import datetime +import enum +from uuid import uuid4 + +import sqlalchemy as sa +import sqlalchemy.dialects.postgresql as pg +from oasst_shared.schemas import inference +from sqlmodel import Field, Relationship, SQLModel + + +class WorkerEventType(str, enum.Enum): + connect = "connect" + + +class D...
inference/server/oasst_inference_server/models/worker.py
0
Python
1
none
16
51
51
true
Store worker compliance check results, add initial scoring algorithm
1,894
LAION-AI/Open-Assistant
29,137
Python
olliestanley
Review this pull request change. Language: Python File: inference/server/oasst_inference_server/models/worker.py PR Title: Store worker compliance check results, add initial scoring algorithm BEFORE CODE: import enum from uuid import uuid4 import sqlalchemy as sa import sqlalchemy.dialects.postgresql as pg from oa...
No issues found.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
"""Add score to message Revision ID: 0f89c99ffdc8 Revises: a2865908a537 Create Date: 2023-03-01 14:42:18.577510 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = "0f89c99ffdc8" down_revision = "a2865908a537" branch_labels = None depends_on = None def upgrade() -...
No issues found.
"""Add score to message Revision ID: 0f89c99ffdc8 Revises: a2865908a537 Create Date: 2023-03-01 14:42:18.577510 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = "0f89c99ffdc8" down_revision = "a2865908a537" branch_labels = None depends_on = None def upgrade() -...
@@ -0,0 +1,38 @@ +"""Add score to message + +Revision ID: 0f89c99ffdc8 +Revises: a2865908a537 +Create Date: 2023-03-01 14:42:18.577510 + +""" +import sqlalchemy as sa +from alembic import op + +# revision identifiers, used by Alembic. +revision = "0f89c99ffdc8" +down_revision = "a2865908a537" +branch_labels = None +dep...
inference/server/alembic/versions/2023_03_01_1442-0f89c99ffdc8_add_score_to_message.py
0
Python
1
none
16
39
39
true
refactor inference message score
1,907
LAION-AI/Open-Assistant
29,137
Python
notmd
Review this pull request change. Language: Python File: inference/server/alembic/versions/2023_03_01_1442-0f89c99ffdc8_add_score_to_message.py PR Title: refactor inference message score BEFORE CODE: """Add score to message Revision ID: 0f89c99ffdc8 Revises: a2865908a537 Create Date: 2023-03-01 14:42:18.577510 """...
No issues found.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
userEmoji={emojiState.user_emojis} onLabel={showLabelPopup} onReport={showReportPopup} message={message} /> <LabelMessagePopup message={message} show={labelPopupOpen} onClose={closeLabelPopup} /> <ReportPopup messageId={message.id} show={repo...
No issues found.
userEmoji={emojiState.user_emojis} onLabel={showLabelPopup} onReport={showReportPopup} message={message} /> <LabelMessagePopup message={message} show={labelPopupOpen} onClose={closeLabelPopup} /> <ReportPopup messageId={message.id} show={repo...
@@ -1,9 +1,6 @@ import { - Avatar, Badge, - Box, Flex, - HStack, Menu, MenuButton, MenuDivider, @@ -13,7 +10,6 @@ import { Portal, SimpleGrid, Tooltip, - useBreakpointValue, useColorModeValue, useDisclosure, useToast, @@ -34,119 +30,84 @@ import { import NextLink from "next/link";...
website/src/components/Messages/MessageTableEntry.tsx
0
TypeScript
1
none
16
51
51
true
Chat vote UI
1,913
LAION-AI/Open-Assistant
29,137
Python
notmd
Review this pull request change. Language: TypeScript File: website/src/components/Messages/MessageTableEntry.tsx PR Title: Chat vote UI BEFORE CODE: userEmoji={emojiState.user_emojis} onLabel={showLabelPopup} onReport={showReportPopup} message={message} /> ...
No issues found.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
if event.user_id is not None: event.user_id = anonymizer.anonymize("user", event.user_id) case "ranking": event: ExportMessageEventRanking = event if event.user_id is not None: ...
No issues found.
if event.user_id is not None: event.user_id = anonymizer.anonymize("user", event.user_id) case "ranking": event: ExportMessageEventRanking = event if event.user_id is not None: ...
@@ -2,22 +2,96 @@ import contextlib import gzip +import hashlib import json import sys +import uuid from collections import defaultdict from typing import Iterable, Optional, TextIO -from uuid import UUID from fastapi.encoders import jsonable_encoder from oasst_backend.models import Message from oasst_back...
backend/oasst_backend/utils/tree_export.py
0
Python
1
none
16
51
51
true
Extended export script
1,954
LAION-AI/Open-Assistant
29,137
Python
yk
Review this pull request change. Language: Python File: backend/oasst_backend/utils/tree_export.py PR Title: Extended export script BEFORE CODE: if event.user_id is not None: event.user_id = anonymizer.anonymize("user", event.user_id) ...
No issues found.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import { Box, Divider, Text, useColorMode } from "@chakra-ui/react"; import { useSession } from "next-auth/react"; import { useTranslation } from "next-i18next"; export function WelcomeCard() { const { colorMode } = useColorMode(); const backgroundColor = colorMode === "light" ? "white" : "gray.700"; const title...
No issues found.
import { Box, Divider, Text, useColorMode } from "@chakra-ui/react"; import { useSession } from "next-auth/react"; import { useTranslation } from "next-i18next"; export function WelcomeCard() { const { colorMode } = useColorMode(); const backgroundColor = colorMode === "light" ? "white" : "gray.700"; const title...
@@ -10,32 +10,25 @@ export function WelcomeCard() { const { data: session } = useSession(); const { t } = useTranslation("dashboard"); - if (!session) { - return <></>; + const isNew = session?.user?.isNew; + if (!isNew) { + return null; } - if (session && session.user && session.user.isNew) - r...
website/src/components/Dashboard/WelcomeCard.tsx
0
TypeScript
1
none
16
35
35
true
Fix some null checks
1,963
LAION-AI/Open-Assistant
29,137
Python
AbdBarho
Review this pull request change. Language: TypeScript File: website/src/components/Dashboard/WelcomeCard.tsx PR Title: Fix some null checks BEFORE CODE: import { Box, Divider, Text, useColorMode } from "@chakra-ui/react"; import { useSession } from "next-auth/react"; import { useTranslation } from "next-i18next"; ...
No issues found.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import { HStack } from "@chakra-ui/react"; import { Icon } from "@chakra-ui/react"; import { Star } from "lucide-react"; import { useTranslation } from "react-i18next"; import { useUserScore } from "src/hooks/ui/useUserScore"; export const UserScore = () => { const score = useUserScore(); const { t } = useTranslat...
No issues found.
import { HStack } from "@chakra-ui/react"; import { Icon } from "@chakra-ui/react"; import { Star } from "lucide-react"; import { useTranslation } from "react-i18next"; import { useUserScore } from "src/hooks/ui/useUserScore"; export const UserScore = () => { const score = useUserScore(); const { t } = useTranslat...
@@ -0,0 +1,21 @@ +import { HStack } from "@chakra-ui/react"; +import { Icon } from "@chakra-ui/react"; +import { Star } from "lucide-react"; +import { useTranslation } from "react-i18next"; +import { useUserScore } from "src/hooks/ui/useUserScore"; + +export const UserScore = () => { + const score = useUserScore(); + ...
website/src/components/Header/UserScore.tsx
0
TypeScript
1
none
16
22
22
true
Show user score in header
1,969
LAION-AI/Open-Assistant
29,137
Python
AbdBarho
Review this pull request change. Language: TypeScript File: website/src/components/Header/UserScore.tsx PR Title: Show user score in header BEFORE CODE: import { HStack } from "@chakra-ui/react"; import { Icon } from "@chakra-ui/react"; import { Star } from "lucide-react"; import { useTranslation } from "react-i18n...
No issues found.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import { Stack, Text } from "@chakra-ui/react"; import { useTranslation } from "next-i18next"; import { MessageTableEntry } from "src/components/Messages/MessageTableEntry"; import { Message } from "src/types/Conversation"; export interface MessageConversationProps { messages: Message[]; enableLink?: boolean; hi...
No issues found.
import { Stack, Text } from "@chakra-ui/react"; import { useTranslation } from "next-i18next"; import { MessageTableEntry } from "src/components/Messages/MessageTableEntry"; import { Message } from "src/types/Conversation"; export interface MessageConversationProps { messages: Message[]; enableLink?: boolean; hi...
@@ -7,9 +7,15 @@ export interface MessageConversationProps { messages: Message[]; enableLink?: boolean; highlightLastMessage?: boolean; + showCreatedDate?: boolean; } -export function MessageConversation({ messages, enableLink, highlightLastMessage }: MessageConversationProps) { +export function MessageCon...
website/src/components/Messages/MessageConversation.tsx
0
TypeScript
1
none
16
38
38
true
show message create date
1,978
LAION-AI/Open-Assistant
29,137
Python
notmd
Review this pull request change. Language: TypeScript File: website/src/components/Messages/MessageConversation.tsx PR Title: show message create date BEFORE CODE: import { Stack, Text } from "@chakra-ui/react"; import { useTranslation } from "next-i18next"; import { MessageTableEntry } from "src/components/Message...
No issues found.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
num_processes=self.args.world_size, process_index=self.args.process_index, ) return DataLoader( train_dataset, batch_size=self.args.per_device_train_batch_size, collate_fn=data_collator, n...
No issues found.
num_processes=self.args.world_size, process_index=self.args.process_index, ) return DataLoader( train_dataset, batch_size=self.args.per_device_train_batch_size, collate_fn=data_collator, n...
@@ -214,10 +214,18 @@ def argument_parsing(notebook=False, notebook_args=None): train_collate_fn = DialogueDataCollator( tokenizer, max_length=training_conf.max_length, + random_offset_probability=training_conf.random_offset_probability, + label_masking=training_conf.label_masking, ...
model/model_training/trainer_sft.py
0
Python
1
none
16
51
51
true
Add SFT params random_offset_probability, label_masking
2,005
LAION-AI/Open-Assistant
29,137
Python
andreaskoepf
Review this pull request change. Language: Python File: model/model_training/trainer_sft.py PR Title: Add SFT params random_offset_probability, label_masking BEFORE CODE: num_processes=self.args.world_size, process_index=self.args.process_index, ) ...
No issues found.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
def get_message( *, message_id: UUID, frontend_user: deps.FrontendUserId = Depends(deps.get_frontend_user_id), api_client: ApiClient = Depends(deps.get_api_client), db: Session = Depends(deps.get_db), ): """ Get a message by its internal ID. """ pr = PromptRepository(db, api_client, ...
No issues found.
def get_message( *, message_id: UUID, frontend_user: deps.FrontendUserId = Depends(deps.get_frontend_user_id), api_client: ApiClient = Depends(deps.get_api_client), db: Session = Depends(deps.get_db), ): """ Get a message by its internal ID. """ pr = PromptRepository(db, api_client, ...
@@ -70,6 +70,7 @@ def get_messages_cursor( max_count: Optional[int] = Query(10, gt=0, le=1000), desc: Optional[bool] = False, lang: Optional[str] = None, + include_user: Optional[bool] = None, frontend_user: deps.FrontendUserId = Depends(deps.get_frontend_user_id), api_client: ApiClient = De...
backend/oasst_backend/api/v1/messages.py
0
Python
1
none
16
51
51
true
add `include_user` params in /messages/cursor` endpoint
2,021
LAION-AI/Open-Assistant
29,137
Python
notmd
Review this pull request change. Language: Python File: backend/oasst_backend/api/v1/messages.py PR Title: add `include_user` params in /messages/cursor` endpoint BEFORE CODE: def get_message( *, message_id: UUID, frontend_user: deps.FrontendUserId = Depends(deps.get_frontend_user_id), api_client: A...
No issues found.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
""" These are in the form of 'INSTRUCTION', 'RESPONSE' """ from custom_datasets.formatting import format_pair from datasets import load_dataset from torch.utils.data import Dataset INSTRUCTION_DATASETS = { # Note humaneval_mbpp_codegen_qa returns a code string that we would want to at least wrap in ``` marks` ...
No issues found.
""" These are in the form of 'INSTRUCTION', 'RESPONSE' """ from custom_datasets.formatting import format_pair from datasets import load_dataset from torch.utils.data import Dataset INSTRUCTION_DATASETS = { # Note humaneval_mbpp_codegen_qa returns a code string that we would want to at least wrap in ``` marks` ...
@@ -0,0 +1,36 @@ +""" + These are in the form of 'INSTRUCTION', 'RESPONSE' +""" +from custom_datasets.formatting import format_pair +from datasets import load_dataset +from torch.utils.data import Dataset + +INSTRUCTION_DATASETS = { + # Note humaneval_mbpp_codegen_qa returns a code string that we would want to at...
model/model_training/custom_datasets/instruction.py
0
Python
1
none
16
37
37
true
Add option to tokenize numbers per digit
2,024
LAION-AI/Open-Assistant
29,137
Python
johnflux
Review this pull request change. Language: Python File: model/model_training/custom_datasets/instruction.py PR Title: Add option to tokenize numbers per digit BEFORE CODE: """ These are in the form of 'INSTRUCTION', 'RESPONSE' """ from custom_datasets.formatting import format_pair from datasets import load_data...
No issues found.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
import Image from "next/image"; import { useEffect, useState } from "react"; export function UserAvatar({ displayName, avatarUrl }: { displayName: string; avatarUrl?: string }) { const diceBearURL = `https://api.dicebear.com/5.x/initials/png?seed=${displayName}&radius=50&backgroundType=gradientLinear`; const [src,...
No issues found.
import Image from "next/image"; import { useEffect, useState } from "react"; export function UserAvatar({ displayName, avatarUrl }: { displayName: string; avatarUrl?: string }) { const diceBearURL = `https://api.dicebear.com/5.x/initials/png?seed=${displayName}&radius=50&backgroundType=gradientLinear`; const [src,...
@@ -1,26 +1,21 @@ import Image from "next/image"; -import { useState } from "react"; -export function UserAvatar(options: { displayName: string; avatarUrl?: string }) { - const { displayName, avatarUrl } = options; - const [src, setSrc] = useState( - avatarUrl - ? avatarUrl - : `https://api.dicebear.com...
website/src/components/UserAvatar.tsx
0
TypeScript
1
none
16
22
22
true
Show correct user avatars on leaderboard
2,039
LAION-AI/Open-Assistant
29,137
Python
AbdBarho
Review this pull request change. Language: TypeScript File: website/src/components/UserAvatar.tsx PR Title: Show correct user avatars on leaderboard BEFORE CODE: import Image from "next/image"; import { useEffect, useState } from "react"; export function UserAvatar({ displayName, avatarUrl }: { displayName: string;...
No issues found.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
self.data = [json.loads(lines[index].strip()) for index in indices[start_index:end_index]] def __len__(self): return len(self.data) def __getitem__(self, index): # Sample randomly from replies prompt = self.data[index]["prompt"] pairs = [] while True: ...
No issues found.
self.data = [json.loads(lines[index].strip()) for index in indices[start_index:end_index]] def __len__(self): return len(self.data) def __getitem__(self, index): # Sample randomly from replies prompt = self.data[index]["prompt"] pairs = [] while True: ...
@@ -6,7 +6,6 @@ from functools import reduce import numpy as np -from custom_datasets.formatting import QA_SPECIAL_TOKENS, format_pair from torch.utils.data import Dataset @@ -68,56 +67,56 @@ def __getitem__(self, index): if self.mode == "sft": # return all dialogue history - ...
model/model_training/custom_datasets/prompt_dialogue.py
0
Python
1
none
16
51
51
true
Choice to add global system-prefix to the assistant during changes
2,053
LAION-AI/Open-Assistant
29,137
Python
sanagno
Review this pull request change. Language: Python File: model/model_training/custom_datasets/prompt_dialogue.py PR Title: Choice to add global system-prefix to the assistant during changes BEFORE CODE: self.data = [json.loads(lines[index].strip()) for index in indices[start_index:end_index]] def __len...
No issues found.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
const { register, handleSubmit } = useForm<UserForm>({ defaultValues: user, }); return ( <> <Head> <title>Manage Users - Open Assistant</title> <meta name="description" content="Conversational AI for everyone. An open source project to create a chat enabled GPT ...
No issues found.
const { register, handleSubmit } = useForm<UserForm>({ defaultValues: user, }); return ( <> <Head> <title>Manage Users - Open Assistant</title> <meta name="description" content="Conversational AI for everyone. An open source project to create a chat enabled GPT ...
@@ -10,7 +10,6 @@ import { CardBody, CardHeader, Checkbox, - CircularProgress, FormControl, FormLabel, Input, @@ -22,19 +21,16 @@ import Head from "next/head"; import { serverSideTranslations } from "next-i18next/serverSideTranslations"; import { useForm } from "react-hook-form"; import { AdminAre...
website/src/pages/admin/manage_user/[id].tsx
0
TypeScript
1
none
16
51
51
true
Admin message list
2,057
LAION-AI/Open-Assistant
29,137
Python
notmd
Review this pull request change. Language: TypeScript File: website/src/pages/admin/manage_user/[id].tsx PR Title: Admin message list BEFORE CODE: const { register, handleSubmit } = useForm<UserForm>({ defaultValues: user, }); return ( <> <Head> <title>Manage Users - Open Assistant</ti...
No issues found.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
return ( <Box display="-webkit-box" wordBreak="break-all" whiteSpace="pre-wrap" w="md"> <Avatar size="xs" mr="2" src={`${row.original.is_assistant ? "/images/logos/logo.png" : "/images/temp-avatars/av1.jpg"}`} ></Avatar> ...
No issues found.
return ( <Box display="-webkit-box" wordBreak="break-all" whiteSpace="pre-wrap" w="md"> <Avatar size="xs" mr="2" src={`${row.original.is_assistant ? "/images/logos/logo.png" : "/images/temp-avatars/av1.jpg"}`} ></Avatar> ...
@@ -14,7 +14,7 @@ import { } from "@chakra-ui/react"; import { createColumnHelper } from "@tanstack/table-core"; import { formatDistanceToNow, formatISO9075 } from "date-fns"; -import { Eye, Trash } from "lucide-react"; +import { Eye, RotateCw, Trash } from "lucide-react"; import NextLink from "next/link"; import ...
website/src/components/Messages/AdminMessageTable.tsx
0
TypeScript
1
none
16
51
51
true
[#2077] Possbility to revert message deletion
2,079
LAION-AI/Open-Assistant
29,137
Python
Shadowner
Review this pull request change. Language: TypeScript File: website/src/components/Messages/AdminMessageTable.tsx PR Title: [#2077] Possbility to revert message deletion BEFORE CODE: return ( <Box display="-webkit-box" wordBreak="break-all" whiteSpace="pre-wrap" w="md"> <Avatar ...
No issues found.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
collate_fn=data_collator, drop_last=self.args.dataloader_drop_last, num_workers=self.args.dataloader_num_workers, pin_memory=self.args.dataloader_pin_memory, worker_init_fn=seed_worker, ) return dataloader def argument_parsing(notebook=False,...
No issues found.
collate_fn=data_collator, drop_last=self.args.dataloader_drop_last, num_workers=self.args.dataloader_num_workers, pin_memory=self.args.dataloader_pin_memory, worker_init_fn=seed_worker, ) return dataloader def argument_parsing(notebook=False,...
@@ -187,8 +187,6 @@ def argument_parsing(notebook=False, notebook_args=None): else: args, remaining = parser.parse_known_args() - print(args) - # Config from YAML conf = {} configs = read_yamls("./configs") @@ -222,8 +220,12 @@ def argument_parsing(notebook=False, notebook_args=None): ...
model/model_training/trainer_sft.py
0
Python
1
none
16
51
51
true
Add minimath support
2,094
LAION-AI/Open-Assistant
29,137
Python
johnflux
Review this pull request change. Language: Python File: model/model_training/trainer_sft.py PR Title: Add minimath support BEFORE CODE: collate_fn=data_collator, drop_last=self.args.dataloader_drop_last, num_workers=self.args.dataloader_num_workers, pin_memory=self.ar...
No issues found.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
justifyContent="space-between" alignItems="center" gap="6" p="8" pb={["14", "8"]} w="full" mx="auto" maxWidth="7xl" > <Flex alignItems="center"> <Box pr="2"> <Link href="/" aria-label="Home"> ...
No issues found.
justifyContent="space-between" alignItems="center" gap="6" p="8" pb={["14", "8"]} w="full" mx="auto" maxWidth="7xl" > <Flex alignItems="center"> <Box pr="2"> <Link href="/" aria-label="Home"> ...
@@ -63,6 +63,7 @@ export function Footer() { <Text fontWeight="bold" color={textColor}> {t("about")} </Text> + <FooterLink href="/team" label={t("who_are_we")} /> <FooterLink href="https://projects.laion.ai/Open-Assistant" label={t("do...
website/src/components/Footer.tsx
0
TypeScript
1
none
16
51
51
true
Add Team page
2,103
LAION-AI/Open-Assistant
29,137
Python
AbdBarho
Review this pull request change. Language: TypeScript File: website/src/components/Footer.tsx PR Title: Add Team page BEFORE CODE: justifyContent="space-between" alignItems="center" gap="6" p="8" pb={["14", "8"]} w="full" mx="auto" maxW...
No issues found.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
temperature: 1, top_k: 50 / 32000, top_p: 0.95, typical_p: 0.5, }; const parameterLabel: Record<keyof typeof customPresetDefaultValue, string> = { max_new_tokens: "Max new tokens", top_k: "Top K", top_p: "Top P", temperature: "Temperature", repetition_penalty: "Repetition Penalty", typical_p: "Typi...
No issues found.
temperature: 1, top_k: 50 / 32000, top_p: 0.95, typical_p: 0.5, }; const parameterLabel: Record<keyof typeof customPresetDefaultValue, string> = { max_new_tokens: "Max new tokens", top_k: "Top K", top_p: "Top P", temperature: "Temperature", repetition_penalty: "Repetition Penalty", typical_p: "Typi...
@@ -0,0 +1,269 @@ +import { + Drawer, + DrawerBody, + DrawerCloseButton, + DrawerContent, + DrawerHeader, + DrawerOverlay, + Flex, + FormControl, + FormLabel, + IconButton, + NumberDecrementStepper, + NumberIncrementStepper, + NumberInput, + NumberInputField, + NumberInputStepper, + Portal, + Select, +...
website/src/components/Chat/ChatConfigDrawer.tsx
0
TypeScript
1
none
16
51
51
true
Chat config UI
2,115
LAION-AI/Open-Assistant
29,137
Python
notmd
Review this pull request change. Language: TypeScript File: website/src/components/Chat/ChatConfigDrawer.tsx PR Title: Chat config UI BEFORE CODE: temperature: 1, top_k: 50 / 32000, top_p: 0.95, typical_p: 0.5, }; const parameterLabel: Record<keyof typeof customPresetDefaultValue, string> = { max_new_tok...
No issues found.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
<stop offset="1" stopColor={baseRingColor} stopOpacity="0" /> </linearGradient> </defs> <path opacity=".2" d="M1 279C1 125.465 125.465 1 279 1s278 124.465 278 278-124.465 278-278 278S1 432.535 1 279Z" stroke={baseRingColor} /> <path d="M1 279C1 125.465 1...
No issues found.
<stop offset="1" stopColor={baseRingColor} stopOpacity="0" /> </linearGradient> </defs> <path opacity=".2" d="M1 279C1 125.465 125.465 1 279 1s278 124.465 278 278-124.465 278-278 278S1 432.535 1 279Z" stroke={baseRingColor} /> <path d="M1 279C1 125.465 1...
@@ -1,5 +1,5 @@ import { Box, Link, Text, useColorMode } from "@chakra-ui/react"; -import { Github } from "lucide-react"; +import { Github, Users } from "lucide-react"; import { useTranslation } from "next-i18next"; import { useId } from "react"; @@ -62,14 +62,16 @@ export function CallToAction() { <Tex...
website/src/components/CallToAction.tsx
0
TypeScript
1
none
16
51
51
true
Updated team page to fit visually more the the rest of the pages, added a button to the call-to-action section which links to the team page.
2,126
LAION-AI/Open-Assistant
29,137
Python
theopfr
Review this pull request change. Language: TypeScript File: website/src/components/CallToAction.tsx PR Title: Updated team page to fit visually more the the rest of the pages, added a button to the call-to-action section which links to the team page. BEFORE CODE: <stop offset="1" stopColor={baseRingColor}...
No issues found.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
origin: string; }; }>(`/api/admin/messages/${messageId}/tree`, get); return ( <> <Head> <title>Open Assistant</title> </Head> <AdminArea> {isLoading && <CircularProgress isIndeterminate></CircularProgress>} {error && "Unable to load message tree"} {da...
No issues found.
origin: string; }; }>(`/api/admin/messages/${messageId}/tree`, get); return ( <> <Head> <title>Open Assistant</title> </Head> <AdminArea> {isLoading && <CircularProgress isIndeterminate></CircularProgress>} {error && "Unable to load message tree"} {da...
@@ -1,4 +1,19 @@ -import { Card, CardBody, CardHeader, CircularProgress, Grid } from "@chakra-ui/react"; +import { + Card, + CardBody, + CardHeader, + CircularProgress, + Grid, + Text, + TableContainer, + Table, + TableCaption, + Thead, + Tr, + Th, + Tbody, + Td, +} from "@chakra-ui/react"; import { GetS...
website/src/pages/admin/messages/[id].tsx
0
TypeScript
1
none
16
51
51
true
Display message tree state admin
2,133
LAION-AI/Open-Assistant
29,137
Python
Rulios
Review this pull request change. Language: TypeScript File: website/src/pages/admin/messages/[id].tsx PR Title: Display message tree state admin BEFORE CODE: origin: string; }; }>(`/api/admin/messages/${messageId}/tree`, get); return ( <> <Head> <title>Open Assistant</title> <...
No issues found.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
}; } return { props: { ...(await serverSideTranslations(locale)), }, }; }; const Chat = () => { const { t } = useTranslation(["common", "chat"]); const router = useRouter(); const { data } = useSWR<GetChatsResponse>("/api/chat", get, { revalidateOnFocus: true }); const { trigger: newC...
No issues found.
}; } return { props: { ...(await serverSideTranslations(locale)), }, }; }; const Chat = () => { const { t } = useTranslation(["common", "chat"]); const router = useRouter(); const { data } = useSWR<GetChatsResponse>("/api/chat", get, { revalidateOnFocus: true }); const { trigger: newC...
@@ -9,24 +9,25 @@ import { useCallback, useMemo } from "react"; import { getDashboardLayout } from "src/components/Layout"; import { SurveyCard } from "src/components/Survey/SurveyCard"; import { get, post } from "src/lib/api"; +import { isChatEnabled } from "src/lib/chat_enabled"; import { GetChatsResponse } from ...
website/src/pages/chat/index.tsx
0
TypeScript
1
none
16
51
51
true
Added ENABLE_CHAT to chat id page and docker-compose
2,137
LAION-AI/Open-Assistant
29,137
Python
yk
Review this pull request change. Language: TypeScript File: website/src/pages/chat/index.tsx PR Title: Added ENABLE_CHAT to chat id page and docker-compose BEFORE CODE: }; } return { props: { ...(await serverSideTranslations(locale)), }, }; }; const Chat = () => { const { t } = useTransla...
No issues found.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
return inference.compat_hash(model_name=self.work_parameters.model_name) class CreateMessageResponse(pydantic.BaseModel): prompter_message: inference.MessageRead assistant_message: inference.MessageRead class PendingResponseEvent(pydantic.BaseModel): event_type: Literal["pending"] = "pending" ...
No issues found.
return inference.compat_hash(model_name=self.work_parameters.model_name) class CreateMessageResponse(pydantic.BaseModel): prompter_message: inference.MessageRead assistant_message: inference.MessageRead class PendingResponseEvent(pydantic.BaseModel): event_type: Literal["pending"] = "pending" ...
@@ -70,3 +70,9 @@ class ChatRead(ChatListRead): class ListChatsResponse(pydantic.BaseModel): chats: list[ChatListRead] + + +class MessageCancelledException(Exception): + def __init__(self, message_id: str): + super().__init__(f"Message {message_id} was cancelled") + self.message_id = message_id
inference/server/oasst_inference_server/schemas/chat.py
0
Python
1
none
16
51
51
true
Cancelling pending chat messages of user on submission of a new message
2,141
LAION-AI/Open-Assistant
29,137
Python
yk
Review this pull request change. Language: Python File: inference/server/oasst_inference_server/schemas/chat.py PR Title: Cancelling pending chat messages of user on submission of a new message BEFORE CODE: return inference.compat_hash(model_name=self.work_parameters.model_name) class CreateMessageRespons...
No issues found.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
if eos_token: parameters.stop.append(eos_token) return prompt, parameters def handle_work_request( ws: websocket.WebSocket, tokenizer: transformers.PreTrainedTokenizer, work_request: inference.WorkRequest, ): prompt, parameters = make_prompt_and_parameters(tokenizer, work_request) ...
No issues found.
if eos_token: parameters.stop.append(eos_token) return prompt, parameters def handle_work_request( ws: websocket.WebSocket, tokenizer: transformers.PreTrainedTokenizer, work_request: inference.WorkRequest, ): prompt, parameters = make_prompt_and_parameters(tokenizer, work_request) ...
@@ -85,12 +85,15 @@ def handle_work_request( ) if settings.model_id == "_lorem": stream_events = utils.lorem_events(parameters.seed) - elif "llama" in settings.model_id: - prompt = truncate_prompt(tokenizer, parameters, prompt) - stream_events = get_hf_stream_events(stream_request) +...
inference/worker/work.py
0
Python
1
none
16
51
51
true
Llama inference
2,144
LAION-AI/Open-Assistant
29,137
Python
yk
Review this pull request change. Language: Python File: inference/worker/work.py PR Title: Llama inference BEFORE CODE: if eos_token: parameters.stop.append(eos_token) return prompt, parameters def handle_work_request( ws: websocket.WebSocket, tokenizer: transformers.PreTrainedTokenizer, ...
No issues found.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
class ModelInfo(pydantic.BaseModel): name: str description: str = "" parameter_configs: list[ParameterConfig] = [] DEFAULT_PARAMETER_CONFIGS = [ ParameterConfig( name="k50", description="Top-k sampling with k=50", work_parameters=inference.WorkParametersInput( mode...
No issues found.
class ModelInfo(pydantic.BaseModel): name: str description: str = "" parameter_configs: list[ParameterConfig] = [] DEFAULT_PARAMETER_CONFIGS = [ ParameterConfig( name="k50", description="Top-k sampling with k=50", work_parameters=inference.WorkParametersInput( mode...
@@ -20,29 +20,60 @@ class ModelInfo(pydantic.BaseModel): parameter_configs: list[ParameterConfig] = [] +DEFAULT_PARAMETER_CONFIGS = [ + ParameterConfig( + name="k50", + description="Top-k sampling with k=50", + work_parameters=inference.WorkParametersInput( + model_name="_mod...
inference/server/oasst_inference_server/routes/configs.py
0
Python
1
none
16
51
51
true
Added param configs from eval to pass to the frontend
2,163
LAION-AI/Open-Assistant
29,137
Python
yk
Review this pull request change. Language: Python File: inference/server/oasst_inference_server/routes/configs.py PR Title: Added param configs from eval to pass to the frontend BEFORE CODE: class ModelInfo(pydantic.BaseModel): name: str description: str = "" parameter_configs: list[ParameterConfig] = ...
No issues found.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
items: SideMenuItem[]; } export const SIDE_MENU_WIDTH = { MD: `100px`, LG: `280px`, }; export function SideMenu({ items }: SideMenuProps) { const router = useRouter(); const { t } = useTranslation(); return ( <Card position={{ base: "relative", md: "fixed" }} p="4" width={{ base: "1...
No issues found.
items: SideMenuItem[]; } export const SIDE_MENU_WIDTH = { MD: `100px`, LG: `280px`, }; export function SideMenu({ items }: SideMenuProps) { const router = useRouter(); const { t } = useTranslation(); return ( <Card position={{ base: "relative", md: "fixed" }} p="4" width={{ base: "1...
@@ -1,75 +1,84 @@ -import { Button, Card, Text, Tooltip } from "@chakra-ui/react"; +import { Box, Button, Card, Text, Tooltip } from "@chakra-ui/react"; import { LucideIcon } from "lucide-react"; import Link from "next/link"; import { useRouter } from "next/router"; import { useTranslation } from "next-i18next"; i...
website/src/components/SideMenu.tsx
0
TypeScript
1
none
16
51
51
true
rework layout
2,172
LAION-AI/Open-Assistant
29,137
Python
notmd
Review this pull request change. Language: TypeScript File: website/src/components/SideMenu.tsx PR Title: rework layout BEFORE CODE: items: SideMenuItem[]; } export const SIDE_MENU_WIDTH = { MD: `100px`, LG: `280px`, }; export function SideMenu({ items }: SideMenuProps) { const router = useRouter(); con...
No issues found.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.
// error: "/auth/error", -Will be used later }, callbacks: { /** * Ensure we propagate the user's role when creating the session from the * token. */ async session({ session, token }) { session.user.role = token.role; session.user.isNew = token.isNew; session.user.name =...
No issues found.
// error: "/auth/error", -Will be used later }, callbacks: { /** * Ensure we propagate the user's role when creating the session from the * token. */ async session({ session, token }) { session.user.role = token.role; session.user.isNew = token.isNew; session.user.name =...
@@ -1,5 +1,6 @@ import { PrismaAdapter } from "@next-auth/prisma-adapter"; import { boolean } from "boolean"; +import Cookies from "cookies"; import { generateUsername } from "friendly-username-generator"; import { NextApiRequest, NextApiResponse } from "next"; import type { AuthOptions } from "next-auth"; @@ -11,...
website/src/pages/api/auth/[...nextauth].ts
0
TypeScript
1
none
16
51
51
true
Login to inference through website
2,176
LAION-AI/Open-Assistant
29,137
Python
AbdBarho
Review this pull request change. Language: TypeScript File: website/src/pages/api/auth/[...nextauth].ts PR Title: Login to inference through website BEFORE CODE: // error: "/auth/error", -Will be used later }, callbacks: { /** * Ensure we propagate the user's role when creating the session from the...
No issues found.
You are an expert software engineer and code reviewer. Review pull requests carefully for correctness, bugs, security issues, performance problems, maintainability, and unnecessary complexity. Only raise actionable issues supported by the code. Explain why an issue matters and suggest a concrete fix when appropriate.