Skip to content

Commit

Permalink
Python fixes (#1353)
Browse files Browse the repository at this point in the history
* Fix: f-string without any placeholders (Ruff F541)
* Fix: Local variable is assigned to but never used (Ruff F841)
* Remove unused imports
* Fix: Comparison to `None` should be `cond is (not) None` (Ruff E711)
* Organize imports
  • Loading branch information
EWouters committed Sep 21, 2024
1 parent 1964409 commit 69ecdaf
Show file tree
Hide file tree
Showing 16 changed files with 28 additions and 48 deletions.
14 changes: 7 additions & 7 deletions backend/chainlit/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,14 +42,14 @@ def get_configuration():
"requireLogin": require_login(),
"passwordAuth": config.code.password_auth_callback is not None,
"headerAuth": config.code.header_auth_callback is not None,
"oauthProviders": get_configured_oauth_providers()
if is_oauth_enabled()
else [],
"oauthProviders": (
get_configured_oauth_providers() if is_oauth_enabled() else []
),
}


def create_jwt(data: User) -> str:
to_encode = data.to_dict() # type: Dict[str, Any]
to_encode: Dict[str, Any] = data.to_dict()
to_encode.update(
{
"exp": datetime.utcnow() + timedelta(minutes=60 * 24 * 15), # 15 days
Expand All @@ -69,14 +69,14 @@ async def authenticate_user(token: str = Depends(reuseable_oauth)):
)
del dict["exp"]
user = User(**dict)
except Exception as e:
except Exception:
raise HTTPException(status_code=401, detail="Invalid authentication token")
if data_layer := get_data_layer():
try:
persisted_user = await data_layer.get_user(user.identifier)
if persisted_user == None:
if persisted_user is None:
persisted_user = await data_layer.create_user(user)
except Exception as e:
except Exception:
return user

return persisted_user
Expand Down
2 changes: 2 additions & 0 deletions backend/chainlit/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@
import nest_asyncio
import uvicorn

# Not sure if it is necessary to call nest_asyncio.apply() before the other imports
nest_asyncio.apply()

# ruff: noqa: E402
from chainlit.cache import init_lc_cache
from chainlit.config import (
BACKEND_ROOT,
Expand Down
4 changes: 1 addition & 3 deletions backend/chainlit/haystack/callbacks.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
import re
from typing import Any, Generic, List, Optional, TypeVar

from chainlit.context import context
from chainlit import Message
from chainlit.step import Step
from chainlit.sync import run_sync
from haystack.agents import Agent, Tool
from haystack.agents.agent_step import AgentStep
from literalai.helper import utc_now

from chainlit import Message

T = TypeVar("T")


Expand Down
1 change: 0 additions & 1 deletion backend/chainlit/langchain/callbacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
from langchain.callbacks.tracers.base import BaseTracer
from langchain.callbacks.tracers.schemas import Run
from langchain.schema import BaseMessage
from langchain.schema.output import ChatGenerationChunk, GenerationChunk
from langchain_core.outputs import ChatGenerationChunk, GenerationChunk
from literalai import ChatGeneration, CompletionGeneration, GenerationMessage
from literalai.helper import utc_now
Expand Down
1 change: 0 additions & 1 deletion backend/chainlit/mistralai/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

from chainlit.context import get_context
from chainlit.step import Step
from chainlit.utils import check_module_version
from literalai import ChatGeneration, CompletionGeneration
from literalai.helper import timestamp_utc

Expand Down
6 changes: 3 additions & 3 deletions backend/chainlit/oauth_providers.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ async def get_user_info(self, token: str):
azure_user["image"] = (
f"data:{photo_response.headers['Content-Type']};base64,{base64_image.decode('utf-8')}"
)
except Exception as e:
except Exception:
# Ignore errors getting the photo
pass

Expand Down Expand Up @@ -291,7 +291,7 @@ async def get_user_info(self, token: str):
azure_user["image"] = (
f"data:{photo_response.headers['Content-Type']};base64,{base64_image.decode('utf-8')}"
)
except Exception as e:
except Exception:
# Ignore errors getting the photo
pass

Expand Down Expand Up @@ -442,7 +442,7 @@ class DescopeOAuthProvider(OAuthProvider):
id = "descope"
env = ["OAUTH_DESCOPE_CLIENT_ID", "OAUTH_DESCOPE_CLIENT_SECRET"]
# Ensure that the domain does not have a trailing slash
domain = f"https://api.descope.com/oauth2/v1"
domain = "https://api.descope.com/oauth2/v1"

authorize_url = f"{domain}/authorize"

Expand Down
21 changes: 5 additions & 16 deletions backend/chainlit/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,14 @@
import mimetypes
import shutil
import uuid
from typing import (
TYPE_CHECKING,
Any,
Callable,
Deque,
Dict,
List,
Literal,
Optional,
Union,
)
from typing import TYPE_CHECKING, Any, Callable, Deque, Dict, Literal, Optional, Union

import aiofiles
from chainlit.logger import logger
from chainlit.types import FileReference

if TYPE_CHECKING:
from chainlit.message import Message
from chainlit.step import Step
from chainlit.types import FileDict, FileReference
from chainlit.types import FileDict
from chainlit.user import PersistedUser, User

ClientType = Literal["webapp", "copilot", "teams", "slack", "discord"]
Expand Down Expand Up @@ -86,7 +75,7 @@ def __init__(
self.chat_profile = chat_profile
self.http_referer = http_referer

self.files = {} # type: Dict[str, "FileDict"]
self.files: Dict[str, FileDict] = {}

self.id = id

Expand All @@ -104,7 +93,7 @@ async def persist_file(
mime: str,
path: Optional[str] = None,
content: Optional[Union[bytes, str]] = None,
) -> "FileReference":
) -> FileReference:
if not path and not content:
raise ValueError(
"Either path or content must be provided to persist a file"
Expand Down
4 changes: 2 additions & 2 deletions backend/chainlit/socket.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ async def connect(sid, environ):
authorization_header = environ.get("HTTP_AUTHORIZATION")
token = authorization_header.split(" ")[1] if authorization_header else None
user = await get_current_user(token=token)
except Exception as e:
except Exception:
logger.info("Authentication failed")
return False

Expand All @@ -145,7 +145,7 @@ def emit_call_fn(event: Literal["ask", "call_fn"], data, timeout):
unquote(url_encoded_chat_profile) if url_encoded_chat_profile else None
)

ws_session = WebsocketSession(
WebsocketSession(
id=session_id,
socket_id=sid,
emit=emit_fn,
Expand Down
4 changes: 2 additions & 2 deletions cypress/e2e/action/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ async def on_action(action: cl.Action):

@cl.action_callback("all actions removed")
async def on_action(_: cl.Action):
await cl.Message(content=f"All actions have been removed!").send()
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 Expand Up @@ -71,5 +71,5 @@ async def main():
],
).send()

if result != None:
if result is not None:
await cl.Message(f"Thanks for pressing: {result['value']}").send()
2 changes: 1 addition & 1 deletion cypress/e2e/chat_settings/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

@cl.on_chat_start
async def start():
settings = await cl.ChatSettings(
await cl.ChatSettings(
[
Select(
id="Model",
Expand Down
4 changes: 1 addition & 3 deletions cypress/e2e/data_layer/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import pickle
from typing import Dict, List, Optional

import chainlit as cl
import chainlit.data as cl_data
from chainlit.data.utils import queue_until_user_message
from chainlit.element import Element, ElementDict
Expand All @@ -15,11 +16,8 @@
ThreadDict,
ThreadFilter,
)
from chainlit.user import PersistedUser, User
from literalai.helper import utc_now

import chainlit as cl

now = utc_now()

thread_history = [
Expand Down
2 changes: 0 additions & 2 deletions cypress/e2e/elements/main.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from chainlit.context import context

import chainlit as cl


Expand Down
3 changes: 1 addition & 2 deletions cypress/e2e/llama_index_cb/main.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import chainlit as cl
from llama_index.core.callbacks.schema import CBEventType, EventPayload
from llama_index.core.llms import ChatMessage, ChatResponse
from llama_index.core.schema import NodeWithScore, TextNode

import chainlit as cl


@cl.on_chat_start
async def start():
Expand Down
3 changes: 1 addition & 2 deletions cypress/e2e/plotly/main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import plotly.graph_objects as go

import chainlit as cl
import plotly.graph_objects as go


@cl.on_chat_start
Expand Down
3 changes: 1 addition & 2 deletions cypress/e2e/pyplot/main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import matplotlib.pyplot as plt

import chainlit as cl
import matplotlib.pyplot as plt


@cl.on_chat_start
Expand Down
2 changes: 1 addition & 1 deletion cypress/e2e/readme/main.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
import chainlit as cl
import chainlit as cl # noqa: F401

0 comments on commit 69ecdaf

Please sign in to comment.