Skip to content

Commit

Permalink
Assorted backend fixes/cleanup (#1432)
Browse files Browse the repository at this point in the history
* Suppress: Possible hardcoded password (bandit B105)
* Fix: Redefinition of unused `on_action` (Ruff F811)
* Use `importlib.util.find_spec` to check if a package is installed
* Raise from Exception
* Fixed undefined variable
* Fixed error message

---------

Authored-by: EWouters <6179932+EWouters@users.noreply.github.com>
  • Loading branch information
dokterbob authored Oct 17, 2024
1 parent 33a377c commit beb44ca
Show file tree
Hide file tree
Showing 11 changed files with 27 additions and 28 deletions.
6 changes: 4 additions & 2 deletions backend/chainlit/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,10 @@ async def authenticate_user(token: str = Depends(reuseable_oauth)):
)
del dict["exp"]
user = User(**dict)
except Exception:
raise HTTPException(status_code=401, detail="Invalid authentication token")
except Exception as e:
raise HTTPException(
status_code=401, detail="Invalid authentication token"
) from e
if data_layer := get_data_layer():
try:
persisted_user = await data_layer.get_user(user.identifier)
Expand Down
7 changes: 2 additions & 5 deletions backend/chainlit/cache.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import importlib.util
import os
import threading

Expand All @@ -8,11 +9,7 @@
def init_lc_cache():
use_cache = config.project.cache is True and config.run.no_cache is False

if use_cache:
try:
import langchain
except ImportError:
return
if use_cache and importlib.util.find_spec("langchain") is not None:
from langchain.cache import SQLiteCache
from langchain.globals import set_llm_cache

Expand Down
2 changes: 1 addition & 1 deletion backend/chainlit/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ def chainlit_run(
# This is required to have OpenAI LLM providers available for the CI run
os.environ["OPENAI_API_KEY"] = "sk-FAKE-OPENAI-API-KEY"
# This is required for authentication tests
os.environ["CHAINLIT_AUTH_SECRET"] = "SUPER_SECRET"
os.environ["CHAINLIT_AUTH_SECRET"] = "SUPER_SECRET" # nosec B105
else:
trace_event("chainlit run")

Expand Down
4 changes: 2 additions & 2 deletions backend/chainlit/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,8 @@ def init_http_context(
def get_context() -> ChainlitContext:
try:
return context_var.get()
except LookupError:
raise ChainlitContextException()
except LookupError as e:
raise ChainlitContextException() from e


context: ChainlitContext = LazyProxy(get_context, enable_cache=False)
8 changes: 4 additions & 4 deletions backend/chainlit/discord/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
try:
import discord
except ModuleNotFoundError:
import importlib.util

if importlib.util.find_spec("discord") is None:
raise ValueError(
"The discord package is required to integrate Chainlit with a Slack app. Run `pip install discord --upgrade`"
"The discord package is required to integrate Chainlit with a Discord app. Run `pip install discord --upgrade`"
)
2 changes: 1 addition & 1 deletion backend/chainlit/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -730,7 +730,7 @@ async def update_feedback(
try:
feedback_id = await data_layer.upsert_feedback(feedback=update.feedback)
except Exception as e:
raise HTTPException(detail=str(e), status_code=500)
raise HTTPException(detail=str(e), status_code=500) from e

return JSONResponse(content={"success": True, "feedbackId": feedback_id})

Expand Down
6 changes: 3 additions & 3 deletions backend/chainlit/slack/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
try:
import slack_bolt
except ModuleNotFoundError:
import importlib.util

if importlib.util.find_spec("slack_bolt") is None:
raise ValueError(
"The slack_bolt package is required to integrate Chainlit with a Slack app. Run `pip install slack_bolt --upgrade`"
)
2 changes: 1 addition & 1 deletion backend/chainlit/step.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ def sync_wrapper(*args, **kwargs):
try:
if result and not step.output:
step.output = result
except:
except Exception as e:
step.is_error = True
step.output = str(e)
return result
Expand Down
6 changes: 3 additions & 3 deletions backend/chainlit/teams/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
try:
import botbuilder
except ModuleNotFoundError:
import importlib.util

if importlib.util.find_spec("botbuilder") is None:
raise ValueError(
"The botbuilder-core package is required to integrate Chainlit with a Slack app. Run `pip install botbuilder-core --upgrade`"
)
4 changes: 2 additions & 2 deletions backend/tests/test_callbacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def test_config(monkeypatch: pytest.MonkeyPatch):
async def test_password_auth_callback(test_config):
@password_auth_callback
async def auth_func(username: str, password: str) -> User | None:
if username == "testuser" and password == "testpass":
if username == "testuser" and password == "testpass": # nosec B105
return User(identifier="testuser")
return None

Expand Down Expand Up @@ -86,7 +86,7 @@ async def auth_func(
default_app_user: User,
id_token: str | None = None,
) -> User | None:
if provider_id == "google" and token == "valid_token":
if provider_id == "google" and token == "valid_token": # nosec B105
return User(identifier="oauth_user")
return None

Expand Down
8 changes: 4 additions & 4 deletions cypress/e2e/action/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,24 @@


@cl.action_callback("test action")
async def on_action():
async def on_test_action():
await cl.Message(content="Executed test action!").send()


@cl.action_callback("removable action")
async def on_action(action: cl.Action):
async def on_removable_action(action: cl.Action):
await cl.Message(content="Executed removable action!").send()
await action.remove()


@cl.action_callback("multiple actions")
async def on_action(action: cl.Action):
async def on_multiple_actions(action: cl.Action):
await cl.Message(content=f"Action(id={action.id}) has been removed!").send()
await action.remove()


@cl.action_callback("all actions removed")
async def on_action(_: cl.Action):
async def on_all_actions_removed(_: cl.Action):
await cl.Message(content="All actions have been removed!").send()
to_remove = cl.user_session.get("to_remove") # type: cl.Message
await to_remove.remove_actions()
Expand Down

0 comments on commit beb44ca

Please sign in to comment.