Skip to content

Commit

Permalink
feat: mypy for all type check (langgenius#10921)
Browse files Browse the repository at this point in the history
  • Loading branch information
yihong0618 authored Dec 24, 2024
1 parent c91e8b1 commit 56e15d0
Show file tree
Hide file tree
Showing 584 changed files with 3,980 additions and 2,831 deletions.
6 changes: 6 additions & 0 deletions .github/workflows/api-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,12 @@ jobs:
- name: Run Tool
run: poetry run -C api bash dev/pytest/pytest_tools.sh

- name: Run mypy
run: |
pushd api
poetry run python -m mypy --install-types --non-interactive .
popd
- name: Set up dotenvs
run: |
cp docker/.env.example docker/.env
Expand Down
13 changes: 8 additions & 5 deletions api/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,8 +159,7 @@ def migrate_annotation_vector_database():
try:
# get apps info
apps = (
db.session.query(App)
.filter(App.status == "normal")
App.query.filter(App.status == "normal")
.order_by(App.created_at.desc())
.paginate(page=page, per_page=50)
)
Expand Down Expand Up @@ -285,8 +284,7 @@ def migrate_knowledge_vector_database():
while True:
try:
datasets = (
db.session.query(Dataset)
.filter(Dataset.indexing_technique == "high_quality")
Dataset.query.filter(Dataset.indexing_technique == "high_quality")
.order_by(Dataset.created_at.desc())
.paginate(page=page, per_page=50)
)
Expand Down Expand Up @@ -450,7 +448,8 @@ def convert_to_agent_apps():
if app_id not in proceeded_app_ids:
proceeded_app_ids.append(app_id)
app = db.session.query(App).filter(App.id == app_id).first()
apps.append(app)
if app is not None:
apps.append(app)

if len(apps) == 0:
break
Expand Down Expand Up @@ -621,6 +620,10 @@ def fix_app_site_missing():

try:
app = db.session.query(App).filter(App.id == app_id).first()
if not app:
print(f"App {app_id} not found")
continue

tenant = app.tenant
if tenant:
accounts = tenant.get_accounts()
Expand Down
14 changes: 6 additions & 8 deletions api/configs/feature/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,6 @@ class HttpConfig(BaseSettings):
)

@computed_field
@property
def CONSOLE_CORS_ALLOW_ORIGINS(self) -> list[str]:
return self.inner_CONSOLE_CORS_ALLOW_ORIGINS.split(",")

Expand All @@ -250,7 +249,6 @@ def CONSOLE_CORS_ALLOW_ORIGINS(self) -> list[str]:
)

@computed_field
@property
def WEB_API_CORS_ALLOW_ORIGINS(self) -> list[str]:
return self.inner_WEB_API_CORS_ALLOW_ORIGINS.split(",")

Expand Down Expand Up @@ -715,27 +713,27 @@ class PositionConfig(BaseSettings):
default="",
)

@computed_field
@property
def POSITION_PROVIDER_PINS_LIST(self) -> list[str]:
return [item.strip() for item in self.POSITION_PROVIDER_PINS.split(",") if item.strip() != ""]

@computed_field
@property
def POSITION_PROVIDER_INCLUDES_SET(self) -> set[str]:
return {item.strip() for item in self.POSITION_PROVIDER_INCLUDES.split(",") if item.strip() != ""}

@computed_field
@property
def POSITION_PROVIDER_EXCLUDES_SET(self) -> set[str]:
return {item.strip() for item in self.POSITION_PROVIDER_EXCLUDES.split(",") if item.strip() != ""}

@computed_field
@property
def POSITION_TOOL_PINS_LIST(self) -> list[str]:
return [item.strip() for item in self.POSITION_TOOL_PINS.split(",") if item.strip() != ""]

@computed_field
@property
def POSITION_TOOL_INCLUDES_SET(self) -> set[str]:
return {item.strip() for item in self.POSITION_TOOL_INCLUDES.split(",") if item.strip() != ""}

@computed_field
@property
def POSITION_TOOL_EXCLUDES_SET(self) -> set[str]:
return {item.strip() for item in self.POSITION_TOOL_EXCLUDES.split(",") if item.strip() != ""}

Expand Down
4 changes: 0 additions & 4 deletions api/configs/middleware/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,6 @@ class DatabaseConfig(BaseSettings):
)

@computed_field
@property
def SQLALCHEMY_DATABASE_URI(self) -> str:
db_extras = (
f"{self.DB_EXTRAS}&client_encoding={self.DB_CHARSET}" if self.DB_CHARSET else self.DB_EXTRAS
Expand Down Expand Up @@ -168,7 +167,6 @@ def SQLALCHEMY_DATABASE_URI(self) -> str:
)

@computed_field
@property
def SQLALCHEMY_ENGINE_OPTIONS(self) -> dict[str, Any]:
return {
"pool_size": self.SQLALCHEMY_POOL_SIZE,
Expand Down Expand Up @@ -206,15 +204,13 @@ class CeleryConfig(DatabaseConfig):
)

@computed_field
@property
def CELERY_RESULT_BACKEND(self) -> str | None:
return (
"db+{}".format(self.SQLALCHEMY_DATABASE_URI)
if self.CELERY_BACKEND == "database"
else self.CELERY_BROKER_URL
)

@computed_field
@property
def BROKER_USE_SSL(self) -> bool:
return self.CELERY_BROKER_URL.startswith("rediss://") if self.CELERY_BROKER_URL else False
Expand Down
5 changes: 3 additions & 2 deletions api/configs/remote_settings_sources/apollo/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import os
import threading
import time
from collections.abc import Mapping
from pathlib import Path

from .python_3x import http_request, makedirs_wrapper
Expand Down Expand Up @@ -255,8 +256,8 @@ def _listener(self):
logger.info("stopped, long_poll")

# add the need for endorsement to the header
def _sign_headers(self, url):
headers = {}
def _sign_headers(self, url: str) -> Mapping[str, str]:
headers: dict[str, str] = {}
if self.secret == "":
return headers
uri = url[len(self.config_url) : len(url)]
Expand Down
3 changes: 2 additions & 1 deletion api/constants/model_template.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import json
from collections.abc import Mapping

from models.model import AppMode

default_app_templates = {
default_app_templates: Mapping[AppMode, Mapping] = {
# workflow default mode
AppMode.WORKFLOW: {
"app": {
Expand Down
2 changes: 1 addition & 1 deletion api/controllers/common/fields.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from flask_restful import fields
from flask_restful import fields # type: ignore

parameters__system_parameters = {
"image_file_size_limit": fields.Integer,
Expand Down
95 changes: 90 additions & 5 deletions api/controllers/console/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,25 @@
from libs.external_api import ExternalApi

from .app.app_import import AppImportApi, AppImportConfirmApi
from .explore.audio import ChatAudioApi, ChatTextApi
from .explore.completion import ChatApi, ChatStopApi, CompletionApi, CompletionStopApi
from .explore.conversation import (
ConversationApi,
ConversationListApi,
ConversationPinApi,
ConversationRenameApi,
ConversationUnPinApi,
)
from .explore.message import (
MessageFeedbackApi,
MessageListApi,
MessageMoreLikeThisApi,
MessageSuggestedQuestionApi,
)
from .explore.workflow import (
InstalledAppWorkflowRunApi,
InstalledAppWorkflowTaskStopApi,
)
from .files import FileApi, FilePreviewApi, FileSupportTypeApi
from .remote_files import RemoteFileInfoApi, RemoteFileUploadApi

Expand Down Expand Up @@ -66,15 +85,81 @@

# Import explore controllers
from .explore import (
audio,
completion,
conversation,
installed_app,
message,
parameter,
recommended_app,
saved_message,
workflow,
)

# Explore Audio
api.add_resource(ChatAudioApi, "/installed-apps/<uuid:installed_app_id>/audio-to-text", endpoint="installed_app_audio")
api.add_resource(ChatTextApi, "/installed-apps/<uuid:installed_app_id>/text-to-audio", endpoint="installed_app_text")

# Explore Completion
api.add_resource(
CompletionApi, "/installed-apps/<uuid:installed_app_id>/completion-messages", endpoint="installed_app_completion"
)
api.add_resource(
CompletionStopApi,
"/installed-apps/<uuid:installed_app_id>/completion-messages/<string:task_id>/stop",
endpoint="installed_app_stop_completion",
)
api.add_resource(
ChatApi, "/installed-apps/<uuid:installed_app_id>/chat-messages", endpoint="installed_app_chat_completion"
)
api.add_resource(
ChatStopApi,
"/installed-apps/<uuid:installed_app_id>/chat-messages/<string:task_id>/stop",
endpoint="installed_app_stop_chat_completion",
)

# Explore Conversation
api.add_resource(
ConversationRenameApi,
"/installed-apps/<uuid:installed_app_id>/conversations/<uuid:c_id>/name",
endpoint="installed_app_conversation_rename",
)
api.add_resource(
ConversationListApi, "/installed-apps/<uuid:installed_app_id>/conversations", endpoint="installed_app_conversations"
)
api.add_resource(
ConversationApi,
"/installed-apps/<uuid:installed_app_id>/conversations/<uuid:c_id>",
endpoint="installed_app_conversation",
)
api.add_resource(
ConversationPinApi,
"/installed-apps/<uuid:installed_app_id>/conversations/<uuid:c_id>/pin",
endpoint="installed_app_conversation_pin",
)
api.add_resource(
ConversationUnPinApi,
"/installed-apps/<uuid:installed_app_id>/conversations/<uuid:c_id>/unpin",
endpoint="installed_app_conversation_unpin",
)


# Explore Message
api.add_resource(MessageListApi, "/installed-apps/<uuid:installed_app_id>/messages", endpoint="installed_app_messages")
api.add_resource(
MessageFeedbackApi,
"/installed-apps/<uuid:installed_app_id>/messages/<uuid:message_id>/feedbacks",
endpoint="installed_app_message_feedback",
)
api.add_resource(
MessageMoreLikeThisApi,
"/installed-apps/<uuid:installed_app_id>/messages/<uuid:message_id>/more-like-this",
endpoint="installed_app_more_like_this",
)
api.add_resource(
MessageSuggestedQuestionApi,
"/installed-apps/<uuid:installed_app_id>/messages/<uuid:message_id>/suggested-questions",
endpoint="installed_app_suggested_question",
)
# Explore Workflow
api.add_resource(InstalledAppWorkflowRunApi, "/installed-apps/<uuid:installed_app_id>/workflows/run")
api.add_resource(
InstalledAppWorkflowTaskStopApi, "/installed-apps/<uuid:installed_app_id>/workflows/tasks/<string:task_id>/stop"
)

# Import tag controllers
Expand Down
2 changes: 1 addition & 1 deletion api/controllers/console/admin.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from functools import wraps

from flask import request
from flask_restful import Resource, reqparse
from flask_restful import Resource, reqparse # type: ignore
from werkzeug.exceptions import NotFound, Unauthorized

from configs import dify_config
Expand Down
23 changes: 14 additions & 9 deletions api/controllers/console/apikey.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import flask_restful
from flask_login import current_user
from typing import Any

import flask_restful # type: ignore
from flask_login import current_user # type: ignore
from flask_restful import Resource, fields, marshal_with
from werkzeug.exceptions import Forbidden

Expand Down Expand Up @@ -35,14 +37,15 @@ def _get_resource(resource_id, tenant_id, resource_model):
class BaseApiKeyListResource(Resource):
method_decorators = [account_initialization_required, login_required, setup_required]

resource_type = None
resource_model = None
resource_id_field = None
token_prefix = None
resource_type: str | None = None
resource_model: Any = None
resource_id_field: str | None = None
token_prefix: str | None = None
max_keys = 10

@marshal_with(api_key_list)
def get(self, resource_id):
assert self.resource_id_field is not None, "resource_id_field must be set"
resource_id = str(resource_id)
_get_resource(resource_id, current_user.current_tenant_id, self.resource_model)
keys = (
Expand All @@ -54,6 +57,7 @@ def get(self, resource_id):

@marshal_with(api_key_fields)
def post(self, resource_id):
assert self.resource_id_field is not None, "resource_id_field must be set"
resource_id = str(resource_id)
_get_resource(resource_id, current_user.current_tenant_id, self.resource_model)
if not current_user.is_editor:
Expand Down Expand Up @@ -86,11 +90,12 @@ def post(self, resource_id):
class BaseApiKeyResource(Resource):
method_decorators = [account_initialization_required, login_required, setup_required]

resource_type = None
resource_model = None
resource_id_field = None
resource_type: str | None = None
resource_model: Any = None
resource_id_field: str | None = None

def delete(self, resource_id, api_key_id):
assert self.resource_id_field is not None, "resource_id_field must be set"
resource_id = str(resource_id)
api_key_id = str(api_key_id)
_get_resource(resource_id, current_user.current_tenant_id, self.resource_model)
Expand Down
2 changes: 1 addition & 1 deletion api/controllers/console/app/advanced_prompt_template.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from flask_restful import Resource, reqparse
from flask_restful import Resource, reqparse # type: ignore

from controllers.console import api
from controllers.console.wraps import account_initialization_required, setup_required
Expand Down
2 changes: 1 addition & 1 deletion api/controllers/console/app/agent.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from flask_restful import Resource, reqparse
from flask_restful import Resource, reqparse # type: ignore

from controllers.console import api
from controllers.console.app.wraps import get_app_model
Expand Down
6 changes: 3 additions & 3 deletions api/controllers/console/app/annotation.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from flask import request
from flask_login import current_user
from flask_restful import Resource, marshal, marshal_with, reqparse
from flask_login import current_user # type: ignore
from flask_restful import Resource, marshal, marshal_with, reqparse # type: ignore
from werkzeug.exceptions import Forbidden

from controllers.console import api
Expand Down Expand Up @@ -110,7 +110,7 @@ def get(self, app_id):

page = request.args.get("page", default=1, type=int)
limit = request.args.get("limit", default=20, type=int)
keyword = request.args.get("keyword", default=None, type=str)
keyword = request.args.get("keyword", default="", type=str)

app_id = str(app_id)
annotation_list, total = AppAnnotationService.get_annotation_list_by_app_id(app_id, page, limit, keyword)
Expand Down
4 changes: 2 additions & 2 deletions api/controllers/console/app/app.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import uuid
from typing import cast

from flask_login import current_user
from flask_restful import Resource, inputs, marshal, marshal_with, reqparse
from flask_login import current_user # type: ignore
from flask_restful import Resource, inputs, marshal, marshal_with, reqparse # type: ignore
from sqlalchemy import select
from sqlalchemy.orm import Session
from werkzeug.exceptions import BadRequest, Forbidden, abort
Expand Down
4 changes: 2 additions & 2 deletions api/controllers/console/app/app_import.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from typing import cast

from flask_login import current_user
from flask_restful import Resource, marshal_with, reqparse
from flask_login import current_user # type: ignore
from flask_restful import Resource, marshal_with, reqparse # type: ignore
from sqlalchemy.orm import Session
from werkzeug.exceptions import Forbidden

Expand Down
Loading

0 comments on commit 56e15d0

Please sign in to comment.