refac
This commit is contained in:
@@ -559,9 +559,7 @@ OAUTH_SESSION_TOKEN_ENCRYPTION_KEY = os.environ.get(
|
|||||||
|
|
||||||
# Maximum number of concurrent OAuth sessions per user per provider
|
# Maximum number of concurrent OAuth sessions per user per provider
|
||||||
# This prevents unbounded session growth while allowing multi-device usage
|
# This prevents unbounded session growth while allowing multi-device usage
|
||||||
OAUTH_MAX_SESSIONS_PER_USER = int(
|
OAUTH_MAX_SESSIONS_PER_USER = int(os.environ.get("OAUTH_MAX_SESSIONS_PER_USER", "10"))
|
||||||
os.environ.get("OAUTH_MAX_SESSIONS_PER_USER", "10")
|
|
||||||
)
|
|
||||||
|
|
||||||
# Token Exchange Configuration
|
# Token Exchange Configuration
|
||||||
# Allows external apps to exchange OAuth tokens for OpenWebUI tokens
|
# Allows external apps to exchange OAuth tokens for OpenWebUI tokens
|
||||||
@@ -985,7 +983,8 @@ OTEL_LOGS_OTLP_SPAN_EXPORTER = os.environ.get(
|
|||||||
####################################
|
####################################
|
||||||
|
|
||||||
ENABLE_PIP_INSTALL_FRONTMATTER_REQUIREMENTS = (
|
ENABLE_PIP_INSTALL_FRONTMATTER_REQUIREMENTS = (
|
||||||
os.environ.get("ENABLE_PIP_INSTALL_FRONTMATTER_REQUIREMENTS", "True").lower() == "true"
|
os.environ.get("ENABLE_PIP_INSTALL_FRONTMATTER_REQUIREMENTS", "True").lower()
|
||||||
|
== "true"
|
||||||
)
|
)
|
||||||
|
|
||||||
PIP_OPTIONS = os.getenv("PIP_OPTIONS", "").split()
|
PIP_OPTIONS = os.getenv("PIP_OPTIONS", "").split()
|
||||||
|
|||||||
@@ -1764,7 +1764,10 @@ async def chat_completion(
|
|||||||
|
|
||||||
# Verify chat ownership — lightweight EXISTS check avoids
|
# Verify chat ownership — lightweight EXISTS check avoids
|
||||||
# deserializing the full chat JSON blob just to confirm the row exists
|
# deserializing the full chat JSON blob just to confirm the row exists
|
||||||
if not Chats.is_chat_owner(metadata["chat_id"], user.id) and user.role != "admin": # admins can access any chat
|
if (
|
||||||
|
not Chats.is_chat_owner(metadata["chat_id"], user.id)
|
||||||
|
and user.role != "admin"
|
||||||
|
): # admins can access any chat
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=status.HTTP_404_NOT_FOUND,
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
detail=ERROR_MESSAGES.DEFAULT(),
|
detail=ERROR_MESSAGES.DEFAULT(),
|
||||||
@@ -1972,7 +1975,6 @@ async def generate_messages(
|
|||||||
return response
|
return response
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@app.post("/api/chat/completed")
|
@app.post("/api/chat/completed")
|
||||||
async def chat_completed(
|
async def chat_completed(
|
||||||
request: Request, form_data: dict, user=Depends(get_verified_user)
|
request: Request, form_data: dict, user=Depends(get_verified_user)
|
||||||
|
|||||||
@@ -439,9 +439,7 @@ class ChannelTable:
|
|||||||
"channel", channel_ids, db=db
|
"channel", channel_ids, db=db
|
||||||
)
|
)
|
||||||
return [
|
return [
|
||||||
self._to_channel_model(
|
self._to_channel_model(c, access_grants=grants_map.get(c.id, []), db=db)
|
||||||
c, access_grants=grants_map.get(c.id, []), db=db
|
|
||||||
)
|
|
||||||
for c in all_channels
|
for c in all_channels
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
@@ -984,9 +984,7 @@ class ChatTable:
|
|||||||
try:
|
try:
|
||||||
with get_db_context(db) as db:
|
with get_db_context(db) as db:
|
||||||
return db.query(
|
return db.query(
|
||||||
exists().where(
|
exists().where(and_(Chat.id == id, Chat.user_id == user_id))
|
||||||
and_(Chat.id == id, Chat.user_id == user_id)
|
|
||||||
)
|
|
||||||
).scalar()
|
).scalar()
|
||||||
except Exception:
|
except Exception:
|
||||||
return False
|
return False
|
||||||
@@ -1001,9 +999,7 @@ class ChatTable:
|
|||||||
try:
|
try:
|
||||||
with get_db_context(db) as db:
|
with get_db_context(db) as db:
|
||||||
result = (
|
result = (
|
||||||
db.query(Chat.folder_id)
|
db.query(Chat.folder_id).filter_by(id=id, user_id=user_id).first()
|
||||||
.filter_by(id=id, user_id=user_id)
|
|
||||||
.first()
|
|
||||||
)
|
)
|
||||||
return result[0] if result else None
|
return result[0] if result else None
|
||||||
except Exception:
|
except Exception:
|
||||||
@@ -1074,9 +1070,7 @@ class ChatTable:
|
|||||||
db.query(Chat)
|
db.query(Chat)
|
||||||
.filter_by(user_id=user_id, pinned=True, archived=False)
|
.filter_by(user_id=user_id, pinned=True, archived=False)
|
||||||
.order_by(Chat.updated_at.desc())
|
.order_by(Chat.updated_at.desc())
|
||||||
.with_entities(
|
.with_entities(Chat.id, Chat.title, Chat.updated_at, Chat.created_at)
|
||||||
Chat.id, Chat.title, Chat.updated_at, Chat.created_at
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
return [
|
return [
|
||||||
ChatTitleIdResponse.model_validate(
|
ChatTitleIdResponse.model_validate(
|
||||||
@@ -1214,29 +1208,23 @@ class ChatTable:
|
|||||||
|
|
||||||
# Check if there are any tags to filter, it should have all the tags
|
# Check if there are any tags to filter, it should have all the tags
|
||||||
if "none" in tag_ids:
|
if "none" in tag_ids:
|
||||||
query = query.filter(
|
query = query.filter(text("""
|
||||||
text(
|
|
||||||
"""
|
|
||||||
NOT EXISTS (
|
NOT EXISTS (
|
||||||
SELECT 1
|
SELECT 1
|
||||||
FROM json_each(Chat.meta, '$.tags') AS tag
|
FROM json_each(Chat.meta, '$.tags') AS tag
|
||||||
)
|
)
|
||||||
"""
|
"""))
|
||||||
)
|
|
||||||
)
|
|
||||||
elif tag_ids:
|
elif tag_ids:
|
||||||
query = query.filter(
|
query = query.filter(
|
||||||
and_(
|
and_(
|
||||||
*[
|
*[
|
||||||
text(
|
text(f"""
|
||||||
f"""
|
|
||||||
EXISTS (
|
EXISTS (
|
||||||
SELECT 1
|
SELECT 1
|
||||||
FROM json_each(Chat.meta, '$.tags') AS tag
|
FROM json_each(Chat.meta, '$.tags') AS tag
|
||||||
WHERE tag.value = :tag_id_{tag_idx}
|
WHERE tag.value = :tag_id_{tag_idx}
|
||||||
)
|
)
|
||||||
"""
|
""").params(**{f"tag_id_{tag_idx}": tag_id})
|
||||||
).params(**{f"tag_id_{tag_idx}": tag_id})
|
|
||||||
for tag_idx, tag_id in enumerate(tag_ids)
|
for tag_idx, tag_id in enumerate(tag_ids)
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
@@ -1272,29 +1260,23 @@ class ChatTable:
|
|||||||
|
|
||||||
# Check if there are any tags to filter, it should have all the tags
|
# Check if there are any tags to filter, it should have all the tags
|
||||||
if "none" in tag_ids:
|
if "none" in tag_ids:
|
||||||
query = query.filter(
|
query = query.filter(text("""
|
||||||
text(
|
|
||||||
"""
|
|
||||||
NOT EXISTS (
|
NOT EXISTS (
|
||||||
SELECT 1
|
SELECT 1
|
||||||
FROM json_array_elements_text(Chat.meta->'tags') AS tag
|
FROM json_array_elements_text(Chat.meta->'tags') AS tag
|
||||||
)
|
)
|
||||||
"""
|
"""))
|
||||||
)
|
|
||||||
)
|
|
||||||
elif tag_ids:
|
elif tag_ids:
|
||||||
query = query.filter(
|
query = query.filter(
|
||||||
and_(
|
and_(
|
||||||
*[
|
*[
|
||||||
text(
|
text(f"""
|
||||||
f"""
|
|
||||||
EXISTS (
|
EXISTS (
|
||||||
SELECT 1
|
SELECT 1
|
||||||
FROM json_array_elements_text(Chat.meta->'tags') AS tag
|
FROM json_array_elements_text(Chat.meta->'tags') AS tag
|
||||||
WHERE tag = :tag_id_{tag_idx}
|
WHERE tag = :tag_id_{tag_idx}
|
||||||
)
|
)
|
||||||
"""
|
""").params(**{f"tag_id_{tag_idx}": tag_id})
|
||||||
).params(**{f"tag_id_{tag_idx}": tag_id})
|
|
||||||
for tag_idx, tag_id in enumerate(tag_ids)
|
for tag_idx, tag_id in enumerate(tag_ids)
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -286,9 +286,7 @@ class KnowledgeTable:
|
|||||||
{
|
{
|
||||||
**self._to_knowledge_model(
|
**self._to_knowledge_model(
|
||||||
knowledge_base,
|
knowledge_base,
|
||||||
access_grants=grants_map.get(
|
access_grants=grants_map.get(knowledge_base.id, []),
|
||||||
knowledge_base.id, []
|
|
||||||
),
|
|
||||||
db=db,
|
db=db,
|
||||||
).model_dump(),
|
).model_dump(),
|
||||||
"user": (
|
"user": (
|
||||||
|
|||||||
@@ -230,9 +230,7 @@ class ModelsTable:
|
|||||||
|
|
||||||
def get_base_models(self, db: Optional[Session] = None) -> list[ModelModel]:
|
def get_base_models(self, db: Optional[Session] = None) -> list[ModelModel]:
|
||||||
with get_db_context(db) as db:
|
with get_db_context(db) as db:
|
||||||
all_models = (
|
all_models = db.query(Model).filter(Model.base_model_id == None).all()
|
||||||
db.query(Model).filter(Model.base_model_id == None).all()
|
|
||||||
)
|
|
||||||
model_ids = [model.id for model in all_models]
|
model_ids = [model.id for model in all_models]
|
||||||
grants_map = AccessGrants.get_grants_by_resources("model", model_ids, db=db)
|
grants_map = AccessGrants.get_grants_by_resources("model", model_ids, db=db)
|
||||||
return [
|
return [
|
||||||
|
|||||||
@@ -217,7 +217,9 @@ class PromptsTable:
|
|||||||
|
|
||||||
users = Users.get_users_by_user_ids(user_ids, db=db) if user_ids else []
|
users = Users.get_users_by_user_ids(user_ids, db=db) if user_ids else []
|
||||||
users_dict = {user.id: user for user in users}
|
users_dict = {user.id: user for user in users}
|
||||||
grants_map = AccessGrants.get_grants_by_resources("prompt", prompt_ids, db=db)
|
grants_map = AccessGrants.get_grants_by_resources(
|
||||||
|
"prompt", prompt_ids, db=db
|
||||||
|
)
|
||||||
|
|
||||||
prompts = []
|
prompts = []
|
||||||
for prompt in all_prompts:
|
for prompt in all_prompts:
|
||||||
@@ -343,7 +345,9 @@ class PromptsTable:
|
|||||||
items = query.all()
|
items = query.all()
|
||||||
|
|
||||||
prompt_ids = [prompt.id for prompt, _ in items]
|
prompt_ids = [prompt.id for prompt, _ in items]
|
||||||
grants_map = AccessGrants.get_grants_by_resources("prompt", prompt_ids, db=db)
|
grants_map = AccessGrants.get_grants_by_resources(
|
||||||
|
"prompt", prompt_ids, db=db
|
||||||
|
)
|
||||||
|
|
||||||
prompts = []
|
prompts = []
|
||||||
for prompt, user in items:
|
for prompt, user in items:
|
||||||
|
|||||||
@@ -283,7 +283,9 @@ class SkillsTable:
|
|||||||
items = query.all()
|
items = query.all()
|
||||||
|
|
||||||
skill_ids = [skill.id for skill, _ in items]
|
skill_ids = [skill.id for skill, _ in items]
|
||||||
grants_map = AccessGrants.get_grants_by_resources("skill", skill_ids, db=db)
|
grants_map = AccessGrants.get_grants_by_resources(
|
||||||
|
"skill", skill_ids, db=db
|
||||||
|
)
|
||||||
|
|
||||||
skills = []
|
skills = []
|
||||||
for skill, user in items:
|
for skill, user in items:
|
||||||
|
|||||||
@@ -856,12 +856,14 @@ def get_embedding_function(
|
|||||||
batch, prefix=prefix, user=user
|
batch, prefix=prefix, user=user
|
||||||
)
|
)
|
||||||
|
|
||||||
tasks = [generate_batch_with_semaphore(batch) for batch in batches]
|
tasks = [
|
||||||
|
generate_batch_with_semaphore(batch) for batch in batches
|
||||||
|
]
|
||||||
else:
|
else:
|
||||||
tasks = [
|
tasks = [
|
||||||
embedding_function(batch, prefix=prefix, user=user)
|
embedding_function(batch, prefix=prefix, user=user)
|
||||||
for batch in batches
|
for batch in batches
|
||||||
]
|
]
|
||||||
batch_results = await asyncio.gather(*tasks)
|
batch_results = await asyncio.gather(*tasks)
|
||||||
else:
|
else:
|
||||||
log.debug(
|
log.debug(
|
||||||
|
|||||||
@@ -400,7 +400,9 @@ async def search_files(
|
|||||||
Uses SQL-based filtering with pagination for better performance.
|
Uses SQL-based filtering with pagination for better performance.
|
||||||
"""
|
"""
|
||||||
# Determine user_id: null for admin with bypass (search all), user.id otherwise
|
# Determine user_id: null for admin with bypass (search all), user.id otherwise
|
||||||
user_id = None if (user.role == "admin" and BYPASS_ADMIN_ACCESS_CONTROL) else user.id
|
user_id = (
|
||||||
|
None if (user.role == "admin" and BYPASS_ADMIN_ACCESS_CONTROL) else user.id
|
||||||
|
)
|
||||||
|
|
||||||
# Use optimized database query with pagination
|
# Use optimized database query with pagination
|
||||||
files = Files.search_files(
|
files = Files.search_files(
|
||||||
|
|||||||
@@ -69,8 +69,6 @@ log = logging.getLogger(__name__)
|
|||||||
##########################################
|
##########################################
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
async def send_get_request(url, key=None, user: UserModel = None):
|
async def send_get_request(url, key=None, user: UserModel = None):
|
||||||
timeout = aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT_MODEL_LIST)
|
timeout = aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT_MODEL_LIST)
|
||||||
try:
|
try:
|
||||||
@@ -374,9 +372,7 @@ async def get_all_models_responses(request: Request, user: UserModel) -> list:
|
|||||||
request_tasks = []
|
request_tasks = []
|
||||||
for idx, url in enumerate(api_base_urls):
|
for idx, url in enumerate(api_base_urls):
|
||||||
if (str(idx) not in api_configs) and (url not in api_configs): # Legacy support
|
if (str(idx) not in api_configs) and (url not in api_configs): # Legacy support
|
||||||
request_tasks.append(
|
request_tasks.append(get_models_request(url, api_keys[idx], user=user))
|
||||||
get_models_request(url, api_keys[idx], user=user)
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
api_config = api_configs.get(
|
api_config = api_configs.get(
|
||||||
str(idx),
|
str(idx),
|
||||||
@@ -716,9 +712,7 @@ async def verify_connection(
|
|||||||
status_code=500, detail="Failed to connect to Anthropic API"
|
status_code=500, detail="Failed to connect to Anthropic API"
|
||||||
)
|
)
|
||||||
if "error" in result:
|
if "error" in result:
|
||||||
raise HTTPException(
|
raise HTTPException(status_code=500, detail=result["error"])
|
||||||
status_code=500, detail=result["error"]
|
|
||||||
)
|
|
||||||
return result
|
return result
|
||||||
else:
|
else:
|
||||||
async with session.get(
|
async with session.get(
|
||||||
|
|||||||
@@ -1216,9 +1216,7 @@ async def update_rag_config(
|
|||||||
request.app.state.config.YANDEX_WEB_SEARCH_CONFIG = (
|
request.app.state.config.YANDEX_WEB_SEARCH_CONFIG = (
|
||||||
form_data.web.YANDEX_WEB_SEARCH_CONFIG
|
form_data.web.YANDEX_WEB_SEARCH_CONFIG
|
||||||
)
|
)
|
||||||
request.app.state.config.YOUCOM_API_KEY = (
|
request.app.state.config.YOUCOM_API_KEY = form_data.web.YOUCOM_API_KEY
|
||||||
form_data.web.YOUCOM_API_KEY
|
|
||||||
)
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"status": True,
|
"status": True,
|
||||||
@@ -1950,7 +1948,9 @@ async def process_web(
|
|||||||
request: Request,
|
request: Request,
|
||||||
form_data: ProcessUrlForm,
|
form_data: ProcessUrlForm,
|
||||||
process: bool = Query(True, description="Whether to process and save the content"),
|
process: bool = Query(True, description="Whether to process and save the content"),
|
||||||
overwrite: bool = Query(True, description="Whether to overwrite existing collection"),
|
overwrite: bool = Query(
|
||||||
|
True, description="Whether to overwrite existing collection"
|
||||||
|
),
|
||||||
user=Depends(get_verified_user),
|
user=Depends(get_verified_user),
|
||||||
):
|
):
|
||||||
try:
|
try:
|
||||||
@@ -2362,7 +2362,9 @@ async def process_web_search(
|
|||||||
user,
|
user,
|
||||||
)
|
)
|
||||||
|
|
||||||
search_tasks = [search_query_with_semaphore(query) for query in form_data.queries]
|
search_tasks = [
|
||||||
|
search_query_with_semaphore(query) for query in form_data.queries
|
||||||
|
]
|
||||||
else:
|
else:
|
||||||
# Unlimited parallel execution (previous behavior)
|
# Unlimited parallel execution (previous behavior)
|
||||||
search_tasks = [
|
search_tasks = [
|
||||||
|
|||||||
@@ -62,13 +62,15 @@ async def get_anthropic_models(url: str, key: str, user: UserModel = None) -> di
|
|||||||
data = await response.json()
|
data = await response.json()
|
||||||
|
|
||||||
for model in data.get("data", []):
|
for model in data.get("data", []):
|
||||||
all_models.append({
|
all_models.append(
|
||||||
"id": model.get("id"),
|
{
|
||||||
"object": "model",
|
"id": model.get("id"),
|
||||||
"created": 0,
|
"object": "model",
|
||||||
"owned_by": "anthropic",
|
"created": 0,
|
||||||
"name": model.get("display_name", model.get("id")),
|
"owned_by": "anthropic",
|
||||||
})
|
"name": model.get("display_name", model.get("id")),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
if not data.get("has_more", False):
|
if not data.get("has_more", False):
|
||||||
break
|
break
|
||||||
@@ -136,37 +138,47 @@ def convert_anthropic_to_openai_payload(anthropic_payload: dict) -> dict:
|
|||||||
block_type = block.get("type", "text")
|
block_type = block.get("type", "text")
|
||||||
|
|
||||||
if block_type == "text":
|
if block_type == "text":
|
||||||
openai_content.append({
|
openai_content.append(
|
||||||
"type": "text",
|
{
|
||||||
"text": block.get("text", ""),
|
"type": "text",
|
||||||
})
|
"text": block.get("text", ""),
|
||||||
|
}
|
||||||
|
)
|
||||||
elif block_type == "image":
|
elif block_type == "image":
|
||||||
source = block.get("source", {})
|
source = block.get("source", {})
|
||||||
if source.get("type") == "base64":
|
if source.get("type") == "base64":
|
||||||
media_type = source.get("media_type", "image/png")
|
media_type = source.get("media_type", "image/png")
|
||||||
data = source.get("data", "")
|
data = source.get("data", "")
|
||||||
openai_content.append({
|
openai_content.append(
|
||||||
"type": "image_url",
|
{
|
||||||
"image_url": {
|
"type": "image_url",
|
||||||
"url": f"data:{media_type};base64,{data}",
|
"image_url": {
|
||||||
},
|
"url": f"data:{media_type};base64,{data}",
|
||||||
})
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
elif source.get("type") == "url":
|
elif source.get("type") == "url":
|
||||||
openai_content.append({
|
openai_content.append(
|
||||||
"type": "image_url",
|
{
|
||||||
"image_url": {"url": source.get("url", "")},
|
"type": "image_url",
|
||||||
})
|
"image_url": {"url": source.get("url", "")},
|
||||||
|
}
|
||||||
|
)
|
||||||
elif block_type == "tool_use":
|
elif block_type == "tool_use":
|
||||||
tool_calls.append({
|
tool_calls.append(
|
||||||
"id": block.get("id", ""),
|
{
|
||||||
"type": "function",
|
"id": block.get("id", ""),
|
||||||
"function": {
|
"type": "function",
|
||||||
"name": block.get("name", ""),
|
"function": {
|
||||||
"arguments": json.dumps(block.get("input", {}))
|
"name": block.get("name", ""),
|
||||||
if isinstance(block.get("input"), dict)
|
"arguments": (
|
||||||
else str(block.get("input", "{}")),
|
json.dumps(block.get("input", {}))
|
||||||
},
|
if isinstance(block.get("input"), dict)
|
||||||
})
|
else str(block.get("input", "{}"))
|
||||||
|
),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
elif block_type == "tool_result":
|
elif block_type == "tool_result":
|
||||||
# Tool results become separate tool messages in OpenAI format
|
# Tool results become separate tool messages in OpenAI format
|
||||||
tool_content = block.get("content", "")
|
tool_content = block.get("content", "")
|
||||||
@@ -181,11 +193,13 @@ def convert_anthropic_to_openai_payload(anthropic_payload: dict) -> dict:
|
|||||||
if block.get("is_error"):
|
if block.get("is_error"):
|
||||||
tool_content = f"Error: {tool_content}"
|
tool_content = f"Error: {tool_content}"
|
||||||
|
|
||||||
messages.append({
|
messages.append(
|
||||||
"role": "tool",
|
{
|
||||||
"tool_call_id": block.get("tool_use_id", ""),
|
"role": "tool",
|
||||||
"content": tool_content,
|
"tool_call_id": block.get("tool_use_id", ""),
|
||||||
})
|
"content": tool_content,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
# Build the message
|
# Build the message
|
||||||
if tool_calls:
|
if tool_calls:
|
||||||
@@ -204,7 +218,9 @@ def convert_anthropic_to_openai_payload(anthropic_payload: dict) -> dict:
|
|||||||
elif openai_content:
|
elif openai_content:
|
||||||
# If there's only a single text block, flatten it to a string
|
# If there's only a single text block, flatten it to a string
|
||||||
if len(openai_content) == 1 and openai_content[0]["type"] == "text":
|
if len(openai_content) == 1 and openai_content[0]["type"] == "text":
|
||||||
messages.append({"role": role, "content": openai_content[0]["text"]})
|
messages.append(
|
||||||
|
{"role": role, "content": openai_content[0]["text"]}
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
messages.append({"role": role, "content": openai_content})
|
messages.append({"role": role, "content": openai_content})
|
||||||
else:
|
else:
|
||||||
@@ -228,14 +244,16 @@ def convert_anthropic_to_openai_payload(anthropic_payload: dict) -> dict:
|
|||||||
if "tools" in anthropic_payload:
|
if "tools" in anthropic_payload:
|
||||||
openai_tools = []
|
openai_tools = []
|
||||||
for tool in anthropic_payload["tools"]:
|
for tool in anthropic_payload["tools"]:
|
||||||
openai_tools.append({
|
openai_tools.append(
|
||||||
"type": "function",
|
{
|
||||||
"function": {
|
"type": "function",
|
||||||
"name": tool.get("name", ""),
|
"function": {
|
||||||
"description": tool.get("description", ""),
|
"name": tool.get("name", ""),
|
||||||
"parameters": tool.get("input_schema", {}),
|
"description": tool.get("description", ""),
|
||||||
},
|
"parameters": tool.get("input_schema", {}),
|
||||||
})
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
openai_payload["tools"] = openai_tools
|
openai_payload["tools"] = openai_tools
|
||||||
|
|
||||||
# tool_choice
|
# tool_choice
|
||||||
@@ -294,12 +312,14 @@ def convert_openai_to_anthropic_response(
|
|||||||
tool_input = json.loads(func.get("arguments", "{}"))
|
tool_input = json.loads(func.get("arguments", "{}"))
|
||||||
except (json.JSONDecodeError, TypeError):
|
except (json.JSONDecodeError, TypeError):
|
||||||
tool_input = {}
|
tool_input = {}
|
||||||
content.append({
|
content.append(
|
||||||
"type": "tool_use",
|
{
|
||||||
"id": tc.get("id", f"toolu_{_uuid.uuid4().hex[:24]}"),
|
"type": "tool_use",
|
||||||
"name": func.get("name", ""),
|
"id": tc.get("id", f"toolu_{_uuid.uuid4().hex[:24]}"),
|
||||||
"input": tool_input,
|
"name": func.get("name", ""),
|
||||||
})
|
"input": tool_input,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
# Usage
|
# Usage
|
||||||
openai_usage = openai_response.get("usage", {})
|
openai_usage = openai_response.get("usage", {})
|
||||||
@@ -320,9 +340,7 @@ def convert_openai_to_anthropic_response(
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async def openai_stream_to_anthropic_stream(
|
async def openai_stream_to_anthropic_stream(openai_stream_generator, model: str = ""):
|
||||||
openai_stream_generator, model: str = ""
|
|
||||||
):
|
|
||||||
"""
|
"""
|
||||||
Convert an OpenAI SSE streaming response to Anthropic Messages SSE format.
|
Convert an OpenAI SSE streaming response to Anthropic Messages SSE format.
|
||||||
|
|
||||||
@@ -391,9 +409,7 @@ async def openai_stream_to_anthropic_stream(
|
|||||||
if not choices:
|
if not choices:
|
||||||
# Check for usage in the final chunk
|
# Check for usage in the final chunk
|
||||||
if data.get("usage"):
|
if data.get("usage"):
|
||||||
input_tokens = data["usage"].get(
|
input_tokens = data["usage"].get("prompt_tokens", input_tokens)
|
||||||
"prompt_tokens", input_tokens
|
|
||||||
)
|
|
||||||
output_tokens = data["usage"].get(
|
output_tokens = data["usage"].get(
|
||||||
"completion_tokens", output_tokens
|
"completion_tokens", output_tokens
|
||||||
)
|
)
|
||||||
@@ -404,9 +420,7 @@ async def openai_stream_to_anthropic_stream(
|
|||||||
|
|
||||||
# Update usage if present
|
# Update usage if present
|
||||||
if data.get("usage"):
|
if data.get("usage"):
|
||||||
input_tokens = data["usage"].get(
|
input_tokens = data["usage"].get("prompt_tokens", input_tokens)
|
||||||
"prompt_tokens", input_tokens
|
|
||||||
)
|
|
||||||
output_tokens = data["usage"].get(
|
output_tokens = data["usage"].get(
|
||||||
"completion_tokens", output_tokens
|
"completion_tokens", output_tokens
|
||||||
)
|
)
|
||||||
@@ -454,9 +468,7 @@ async def openai_stream_to_anthropic_stream(
|
|||||||
tool_call_started[tc_index] = True
|
tool_call_started[tc_index] = True
|
||||||
|
|
||||||
# Extract tool call ID and name from the first chunk
|
# Extract tool call ID and name from the first chunk
|
||||||
tc_id = tc.get(
|
tc_id = tc.get("id", f"toolu_{_uuid.uuid4().hex[:24]}")
|
||||||
"id", f"toolu_{_uuid.uuid4().hex[:24]}"
|
|
||||||
)
|
|
||||||
tc_name = tc.get("function", {}).get("name", "")
|
tc_name = tc.get("function", {}).get("name", "")
|
||||||
|
|
||||||
block_start = {
|
block_start = {
|
||||||
@@ -473,9 +485,7 @@ async def openai_stream_to_anthropic_stream(
|
|||||||
current_block_index += 1
|
current_block_index += 1
|
||||||
|
|
||||||
# Emit argument chunks as input_json_delta
|
# Emit argument chunks as input_json_delta
|
||||||
args_chunk = tc.get("function", {}).get(
|
args_chunk = tc.get("function", {}).get("arguments", "")
|
||||||
"arguments", ""
|
|
||||||
)
|
|
||||||
if args_chunk:
|
if args_chunk:
|
||||||
block_delta = {
|
block_delta = {
|
||||||
"type": "content_block_delta",
|
"type": "content_block_delta",
|
||||||
@@ -522,4 +532,3 @@ async def openai_stream_to_anthropic_stream(
|
|||||||
|
|
||||||
# Emit message_stop
|
# Emit message_stop
|
||||||
yield f"event: message_stop\ndata: {json.dumps({'type': 'message_stop'})}\n\n".encode()
|
yield f"event: message_stop\ndata: {json.dumps({'type': 'message_stop'})}\n\n".encode()
|
||||||
|
|
||||||
|
|||||||
@@ -1248,7 +1248,11 @@ class OAuthManager:
|
|||||||
name=group_name,
|
name=group_name,
|
||||||
description=f"Group '{group_name}' created automatically via OAuth.",
|
description=f"Group '{group_name}' created automatically via OAuth.",
|
||||||
permissions=default_permissions, # Use default permissions from function args
|
permissions=default_permissions, # Use default permissions from function args
|
||||||
data={"config": {"share": auth_manager_config.OAUTH_GROUP_DEFAULT_SHARE}},
|
data={
|
||||||
|
"config": {
|
||||||
|
"share": auth_manager_config.OAUTH_GROUP_DEFAULT_SHARE
|
||||||
|
}
|
||||||
|
},
|
||||||
)
|
)
|
||||||
# Use determined creator ID (admin or fallback to current user)
|
# Use determined creator ID (admin or fallback to current user)
|
||||||
created_group = Groups.insert_new_group(
|
created_group = Groups.insert_new_group(
|
||||||
@@ -1686,19 +1690,13 @@ class OAuthManager:
|
|||||||
# unbounded growth while allowing multi-device usage
|
# unbounded growth while allowing multi-device usage
|
||||||
sessions = OAuthSessions.get_sessions_by_user_id(user.id, db=db)
|
sessions = OAuthSessions.get_sessions_by_user_id(user.id, db=db)
|
||||||
provider_sessions = sorted(
|
provider_sessions = sorted(
|
||||||
[
|
[session for session in sessions if session.provider == provider],
|
||||||
session
|
|
||||||
for session in sessions
|
|
||||||
if session.provider == provider
|
|
||||||
],
|
|
||||||
key=lambda session: session.created_at,
|
key=lambda session: session.created_at,
|
||||||
reverse=True,
|
reverse=True,
|
||||||
)
|
)
|
||||||
# Keep the newest sessions up to the limit, prune the rest
|
# Keep the newest sessions up to the limit, prune the rest
|
||||||
if len(provider_sessions) >= OAUTH_MAX_SESSIONS_PER_USER:
|
if len(provider_sessions) >= OAUTH_MAX_SESSIONS_PER_USER:
|
||||||
for old_session in provider_sessions[
|
for old_session in provider_sessions[OAUTH_MAX_SESSIONS_PER_USER - 1 :]:
|
||||||
OAUTH_MAX_SESSIONS_PER_USER - 1 :
|
|
||||||
]:
|
|
||||||
OAuthSessions.delete_session_by_id(old_session.id, db=db)
|
OAuthSessions.delete_session_by_id(old_session.id, db=db)
|
||||||
|
|
||||||
session = OAuthSessions.create_session(
|
session = OAuthSessions.create_session(
|
||||||
|
|||||||
@@ -8,7 +8,12 @@ import tempfile
|
|||||||
import logging
|
import logging
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from open_webui.env import PIP_OPTIONS, PIP_PACKAGE_INDEX_OPTIONS, OFFLINE_MODE, ENABLE_PIP_INSTALL_FRONTMATTER_REQUIREMENTS
|
from open_webui.env import (
|
||||||
|
PIP_OPTIONS,
|
||||||
|
PIP_PACKAGE_INDEX_OPTIONS,
|
||||||
|
OFFLINE_MODE,
|
||||||
|
ENABLE_PIP_INSTALL_FRONTMATTER_REQUIREMENTS,
|
||||||
|
)
|
||||||
from open_webui.models.functions import Functions
|
from open_webui.models.functions import Functions
|
||||||
from open_webui.models.tools import Tools
|
from open_webui.models.tools import Tools
|
||||||
|
|
||||||
@@ -402,7 +407,9 @@ def get_function_module_from_cache(request, function_id, load_from_db=True):
|
|||||||
|
|
||||||
def install_frontmatter_requirements(requirements: str):
|
def install_frontmatter_requirements(requirements: str):
|
||||||
if not ENABLE_PIP_INSTALL_FRONTMATTER_REQUIREMENTS:
|
if not ENABLE_PIP_INSTALL_FRONTMATTER_REQUIREMENTS:
|
||||||
log.info("ENABLE_PIP_INSTALL_FRONTMATTER_REQUIREMENTS is disabled, skipping installation of requirements.")
|
log.info(
|
||||||
|
"ENABLE_PIP_INSTALL_FRONTMATTER_REQUIREMENTS is disabled, skipping installation of requirements."
|
||||||
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
if OFFLINE_MODE:
|
if OFFLINE_MODE:
|
||||||
|
|||||||
@@ -473,7 +473,15 @@ def get_builtin_tools(
|
|||||||
|
|
||||||
# Add memory tools if builtin category enabled AND enabled for this chat
|
# Add memory tools if builtin category enabled AND enabled for this chat
|
||||||
if is_builtin_tool_enabled("memory") and features.get("memory"):
|
if is_builtin_tool_enabled("memory") and features.get("memory"):
|
||||||
builtin_functions.extend([search_memories, add_memory, replace_memory_content, delete_memory, list_memories])
|
builtin_functions.extend(
|
||||||
|
[
|
||||||
|
search_memories,
|
||||||
|
add_memory,
|
||||||
|
replace_memory_content,
|
||||||
|
delete_memory,
|
||||||
|
list_memories,
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
# Add web search tools if builtin category enabled AND enabled globally AND model has web_search capability
|
# Add web search tools if builtin category enabled AND enabled globally AND model has web_search capability
|
||||||
if (
|
if (
|
||||||
|
|||||||
@@ -71,7 +71,6 @@
|
|||||||
return 0;
|
return 0;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
let defaultPermissions = {};
|
let defaultPermissions = {};
|
||||||
|
|
||||||
let showAddGroupModal = false;
|
let showAddGroupModal = false;
|
||||||
|
|||||||
@@ -159,7 +159,11 @@
|
|||||||
})
|
})
|
||||||
).filter((item) => !(item.model?.info?.meta?.hidden ?? false));
|
).filter((item) => !(item.model?.info?.meta?.hidden ?? false));
|
||||||
|
|
||||||
$: if (selectedTag !== undefined || selectedConnectionType !== undefined || searchValue !== undefined) {
|
$: if (
|
||||||
|
selectedTag !== undefined ||
|
||||||
|
selectedConnectionType !== undefined ||
|
||||||
|
searchValue !== undefined
|
||||||
|
) {
|
||||||
resetView();
|
resetView();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -81,7 +81,9 @@
|
|||||||
</button>
|
</button>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
|
|
||||||
<Tooltip content={(connection?.config?.enable ?? true) ? $i18n.t('Enabled') : $i18n.t('Disabled')}>
|
<Tooltip
|
||||||
|
content={(connection?.config?.enable ?? true) ? $i18n.t('Enabled') : $i18n.t('Disabled')}
|
||||||
|
>
|
||||||
<Switch
|
<Switch
|
||||||
state={connection?.config?.enable ?? true}
|
state={connection?.config?.enable ?? true}
|
||||||
on:change={() => {
|
on:change={() => {
|
||||||
|
|||||||
@@ -31,7 +31,13 @@
|
|||||||
|
|
||||||
import { goto } from '$app/navigation';
|
import { goto } from '$app/navigation';
|
||||||
import { WEBUI_NAME, config, user } from '$lib/stores';
|
import { WEBUI_NAME, config, user } from '$lib/stores';
|
||||||
import { createNewNote, deleteNoteById, getNoteById, getNoteList, searchNotes } from '$lib/apis/notes';
|
import {
|
||||||
|
createNewNote,
|
||||||
|
deleteNoteById,
|
||||||
|
getNoteById,
|
||||||
|
getNoteList,
|
||||||
|
searchNotes
|
||||||
|
} from '$lib/apis/notes';
|
||||||
import { capitalizeFirstLetter, copyToClipboard, getTimeRange } from '$lib/utils';
|
import { capitalizeFirstLetter, copyToClipboard, getTimeRange } from '$lib/utils';
|
||||||
import { downloadPdf, createNoteHandler } from './utils';
|
import { downloadPdf, createNoteHandler } from './utils';
|
||||||
|
|
||||||
|
|||||||
@@ -399,7 +399,6 @@
|
|||||||
<div class="text-xs overflow-hidden text-ellipsis line-clamp-1 text-gray-500">
|
<div class="text-xs overflow-hidden text-ellipsis line-clamp-1 text-gray-500">
|
||||||
/{prompt.command}
|
/{prompt.command}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
{#if !prompt.write_access}
|
{#if !prompt.write_access}
|
||||||
<Badge type="muted" content={$i18n.t('Read Only')} />
|
<Badge type="muted" content={$i18n.t('Read Only')} />
|
||||||
@@ -488,7 +487,9 @@
|
|||||||
</PromptMenu>
|
</PromptMenu>
|
||||||
|
|
||||||
<button on:click|stopPropagation|preventDefault>
|
<button on:click|stopPropagation|preventDefault>
|
||||||
<Tooltip content={prompt.is_active !== false ? $i18n.t('Enabled') : $i18n.t('Disabled')}>
|
<Tooltip
|
||||||
|
content={prompt.is_active !== false ? $i18n.t('Enabled') : $i18n.t('Disabled')}
|
||||||
|
>
|
||||||
<Switch
|
<Switch
|
||||||
bind:state={prompt.is_active}
|
bind:state={prompt.is_active}
|
||||||
on:change={async () => {
|
on:change={async () => {
|
||||||
|
|||||||
@@ -218,11 +218,9 @@
|
|||||||
const items = Array.isArray(parsedSkills) ? parsedSkills : [parsedSkills];
|
const items = Array.isArray(parsedSkills) ? parsedSkills : [parsedSkills];
|
||||||
|
|
||||||
for (const skill of items) {
|
for (const skill of items) {
|
||||||
await createNewSkill(localStorage.token, skill).catch(
|
await createNewSkill(localStorage.token, skill).catch((error) => {
|
||||||
(error) => {
|
toast.error(`${error}`);
|
||||||
toast.error(`${error}`);
|
});
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
toast.success($i18n.t('Skill imported successfully'));
|
toast.success($i18n.t('Skill imported successfully'));
|
||||||
|
|||||||
@@ -22,7 +22,6 @@
|
|||||||
user,
|
user,
|
||||||
settings,
|
settings,
|
||||||
models,
|
models,
|
||||||
prompts,
|
|
||||||
knowledge,
|
knowledge,
|
||||||
tools,
|
tools,
|
||||||
functions,
|
functions,
|
||||||
|
|||||||
@@ -68,13 +68,13 @@
|
|||||||
>
|
>
|
||||||
|
|
||||||
{#if $config?.features.enable_admin_analytics ?? true}
|
{#if $config?.features.enable_admin_analytics ?? true}
|
||||||
<a
|
<a
|
||||||
draggable="false"
|
draggable="false"
|
||||||
class="min-w-fit p-1.5 {$page.url.pathname.includes('/admin/analytics')
|
class="min-w-fit p-1.5 {$page.url.pathname.includes('/admin/analytics')
|
||||||
? ''
|
? ''
|
||||||
: 'text-gray-300 dark:text-gray-600 hover:text-gray-700 dark:hover:text-white'} transition select-none"
|
: 'text-gray-300 dark:text-gray-600 hover:text-gray-700 dark:hover:text-white'} transition select-none"
|
||||||
href="/admin/analytics">{$i18n.t('Analytics')}</a
|
href="/admin/analytics">{$i18n.t('Analytics')}</a
|
||||||
>
|
>
|
||||||
{/if}
|
{/if}
|
||||||
|
|
||||||
<a
|
<a
|
||||||
|
|||||||
@@ -7,7 +7,6 @@
|
|||||||
user,
|
user,
|
||||||
mobile,
|
mobile,
|
||||||
models,
|
models,
|
||||||
prompts,
|
|
||||||
knowledge,
|
knowledge,
|
||||||
tools
|
tools
|
||||||
} from '$lib/stores';
|
} from '$lib/stores';
|
||||||
|
|||||||
Reference in New Issue
Block a user