mirror of
https://github.com/onyx-dot-app/onyx.git
synced 2026-04-09 00:42:47 +00:00
Compare commits
13 Commits
jamison/on
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a823c3ead1 | ||
|
|
bd7d378a9a | ||
|
|
dcec0c8ef3 | ||
|
|
6456b51dcf | ||
|
|
7cfe27e31e | ||
|
|
3c5f77f5a4 | ||
|
|
ab4d1dce01 | ||
|
|
80c928eb58 | ||
|
|
77528876b1 | ||
|
|
3bf53495f3 | ||
|
|
e4cfcda0bf | ||
|
|
475e8f6cdc | ||
|
|
945272c1d2 |
2
.github/workflows/deployment.yml
vendored
2
.github/workflows/deployment.yml
vendored
@@ -13,7 +13,7 @@ permissions:
|
||||
id-token: write # zizmor: ignore[excessive-permissions]
|
||||
|
||||
env:
|
||||
EDGE_TAG: ${{ startsWith(github.ref_name, 'nightly-latest') }}
|
||||
EDGE_TAG: ${{ startsWith(github.ref_name, 'nightly-latest') || github.ref_name == 'edge' }}
|
||||
|
||||
jobs:
|
||||
# Determine which components to build based on the tag
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import time
|
||||
from collections.abc import Generator
|
||||
from collections.abc import Iterator
|
||||
from collections.abc import Sequence
|
||||
@@ -30,6 +31,8 @@ from onyx.connectors.models import HierarchyNode
|
||||
from onyx.connectors.models import SlimDocument
|
||||
from onyx.httpx.httpx_pool import HttpxPool
|
||||
from onyx.indexing.indexing_heartbeat import IndexingHeartbeatInterface
|
||||
from onyx.server.metrics.pruning_metrics import inc_pruning_rate_limit_error
|
||||
from onyx.server.metrics.pruning_metrics import observe_pruning_enumeration_duration
|
||||
from onyx.utils.logger import setup_logger
|
||||
|
||||
|
||||
@@ -130,6 +133,7 @@ def _extract_from_batch(
|
||||
def extract_ids_from_runnable_connector(
|
||||
runnable_connector: BaseConnector,
|
||||
callback: IndexingHeartbeatInterface | None = None,
|
||||
connector_type: str = "unknown",
|
||||
) -> SlimConnectorExtractionResult:
|
||||
"""
|
||||
Extract document IDs and hierarchy nodes from a runnable connector.
|
||||
@@ -179,21 +183,38 @@ def extract_ids_from_runnable_connector(
|
||||
)
|
||||
|
||||
# process raw batches to extract both IDs and hierarchy nodes
|
||||
for doc_list in raw_batch_generator:
|
||||
if callback and callback.should_stop():
|
||||
raise RuntimeError(
|
||||
"extract_ids_from_runnable_connector: Stop signal detected"
|
||||
)
|
||||
enumeration_start = time.monotonic()
|
||||
try:
|
||||
for doc_list in raw_batch_generator:
|
||||
if callback and callback.should_stop():
|
||||
raise RuntimeError(
|
||||
"extract_ids_from_runnable_connector: Stop signal detected"
|
||||
)
|
||||
|
||||
batch_result = _extract_from_batch(doc_list)
|
||||
batch_ids = batch_result.raw_id_to_parent
|
||||
batch_nodes = batch_result.hierarchy_nodes
|
||||
doc_batch_processing_func(batch_ids)
|
||||
all_raw_id_to_parent.update(batch_ids)
|
||||
all_hierarchy_nodes.extend(batch_nodes)
|
||||
batch_result = _extract_from_batch(doc_list)
|
||||
batch_ids = batch_result.raw_id_to_parent
|
||||
batch_nodes = batch_result.hierarchy_nodes
|
||||
doc_batch_processing_func(batch_ids)
|
||||
all_raw_id_to_parent.update(batch_ids)
|
||||
all_hierarchy_nodes.extend(batch_nodes)
|
||||
|
||||
if callback:
|
||||
callback.progress("extract_ids_from_runnable_connector", len(batch_ids))
|
||||
if callback:
|
||||
callback.progress("extract_ids_from_runnable_connector", len(batch_ids))
|
||||
except Exception as e:
|
||||
# Best-effort rate limit detection via string matching.
|
||||
# Connectors surface rate limits inconsistently — some raise HTTP 429,
|
||||
# some use SDK-specific exceptions (e.g. google.api_core.exceptions.ResourceExhausted)
|
||||
# that may or may not include "rate limit" or "429" in the message.
|
||||
# TODO(Bo): replace with a standard ConnectorRateLimitError exception that all
|
||||
# connectors raise when rate limited, making this check precise.
|
||||
error_str = str(e)
|
||||
if "rate limit" in error_str.lower() or "429" in error_str:
|
||||
inc_pruning_rate_limit_error(connector_type)
|
||||
raise
|
||||
finally:
|
||||
observe_pruning_enumeration_duration(
|
||||
time.monotonic() - enumeration_start, connector_type
|
||||
)
|
||||
|
||||
return SlimConnectorExtractionResult(
|
||||
raw_id_to_parent=all_raw_id_to_parent,
|
||||
|
||||
@@ -72,6 +72,7 @@ from onyx.redis.redis_hierarchy import get_source_node_id_from_cache
|
||||
from onyx.redis.redis_hierarchy import HierarchyNodeCacheEntry
|
||||
from onyx.redis.redis_pool import get_redis_client
|
||||
from onyx.redis.redis_pool import get_redis_replica_client
|
||||
from onyx.server.metrics.pruning_metrics import observe_pruning_diff_duration
|
||||
from onyx.server.runtime.onyx_runtime import OnyxRuntime
|
||||
from onyx.server.utils import make_short_id
|
||||
from onyx.utils.logger import format_error_for_logging
|
||||
@@ -570,8 +571,9 @@ def connector_pruning_generator_task(
|
||||
)
|
||||
|
||||
# Extract docs and hierarchy nodes from the source
|
||||
connector_type = cc_pair.connector.source.value
|
||||
extraction_result = extract_ids_from_runnable_connector(
|
||||
runnable_connector, callback
|
||||
runnable_connector, callback, connector_type=connector_type
|
||||
)
|
||||
all_connector_doc_ids = extraction_result.raw_id_to_parent
|
||||
|
||||
@@ -636,40 +638,46 @@ def connector_pruning_generator_task(
|
||||
commit=True,
|
||||
)
|
||||
|
||||
# a list of docs in our local index
|
||||
all_indexed_document_ids = {
|
||||
doc.id
|
||||
for doc in get_documents_for_connector_credential_pair(
|
||||
db_session=db_session,
|
||||
connector_id=connector_id,
|
||||
credential_id=credential_id,
|
||||
diff_start = time.monotonic()
|
||||
try:
|
||||
# a list of docs in our local index
|
||||
all_indexed_document_ids = {
|
||||
doc.id
|
||||
for doc in get_documents_for_connector_credential_pair(
|
||||
db_session=db_session,
|
||||
connector_id=connector_id,
|
||||
credential_id=credential_id,
|
||||
)
|
||||
}
|
||||
|
||||
# generate list of docs to remove (no longer in the source)
|
||||
doc_ids_to_remove = list(
|
||||
all_indexed_document_ids - all_connector_doc_ids.keys()
|
||||
)
|
||||
}
|
||||
|
||||
# generate list of docs to remove (no longer in the source)
|
||||
doc_ids_to_remove = list(
|
||||
all_indexed_document_ids - all_connector_doc_ids.keys()
|
||||
)
|
||||
task_logger.info(
|
||||
"Pruning set collected: "
|
||||
f"cc_pair={cc_pair_id} "
|
||||
f"connector_source={cc_pair.connector.source} "
|
||||
f"docs_to_remove={len(doc_ids_to_remove)}"
|
||||
)
|
||||
|
||||
task_logger.info(
|
||||
"Pruning set collected: "
|
||||
f"cc_pair={cc_pair_id} "
|
||||
f"connector_source={cc_pair.connector.source} "
|
||||
f"docs_to_remove={len(doc_ids_to_remove)}"
|
||||
)
|
||||
task_logger.info(
|
||||
f"RedisConnector.prune.generate_tasks starting. cc_pair={cc_pair_id}"
|
||||
)
|
||||
tasks_generated = redis_connector.prune.generate_tasks(
|
||||
set(doc_ids_to_remove), self.app, db_session, None
|
||||
)
|
||||
if tasks_generated is None:
|
||||
return None
|
||||
|
||||
task_logger.info(
|
||||
f"RedisConnector.prune.generate_tasks starting. cc_pair={cc_pair_id}"
|
||||
)
|
||||
tasks_generated = redis_connector.prune.generate_tasks(
|
||||
set(doc_ids_to_remove), self.app, db_session, None
|
||||
)
|
||||
if tasks_generated is None:
|
||||
return None
|
||||
|
||||
task_logger.info(
|
||||
f"RedisConnector.prune.generate_tasks finished. cc_pair={cc_pair_id} tasks_generated={tasks_generated}"
|
||||
)
|
||||
task_logger.info(
|
||||
f"RedisConnector.prune.generate_tasks finished. cc_pair={cc_pair_id} tasks_generated={tasks_generated}"
|
||||
)
|
||||
finally:
|
||||
observe_pruning_diff_duration(
|
||||
time.monotonic() - diff_start, connector_type
|
||||
)
|
||||
|
||||
redis_connector.prune.generator_complete = tasks_generated
|
||||
|
||||
|
||||
@@ -87,6 +87,44 @@ PROVIDER_DISPLAY_NAMES: dict[str, str] = {
|
||||
"gemini": "Gemini",
|
||||
"stability": "Stability",
|
||||
"writer": "Writer",
|
||||
# Custom provider display names (used in the custom provider picker)
|
||||
"aiml": "AI/ML",
|
||||
"assemblyai": "AssemblyAI",
|
||||
"aws_polly": "AWS Polly",
|
||||
"azure_ai": "Azure AI",
|
||||
"chatgpt": "ChatGPT",
|
||||
"cohere_chat": "Cohere Chat",
|
||||
"datarobot": "DataRobot",
|
||||
"deepgram": "Deepgram",
|
||||
"deepinfra": "DeepInfra",
|
||||
"elevenlabs": "ElevenLabs",
|
||||
"fal_ai": "fal.ai",
|
||||
"featherless_ai": "Featherless AI",
|
||||
"fireworks_ai": "Fireworks AI",
|
||||
"friendliai": "FriendliAI",
|
||||
"gigachat": "GigaChat",
|
||||
"github_copilot": "GitHub Copilot",
|
||||
"gradient_ai": "Gradient AI",
|
||||
"huggingface": "HuggingFace",
|
||||
"jina_ai": "Jina AI",
|
||||
"lambda_ai": "Lambda AI",
|
||||
"llamagate": "LlamaGate",
|
||||
"meta_llama": "Meta Llama",
|
||||
"minimax": "MiniMax",
|
||||
"nlp_cloud": "NLP Cloud",
|
||||
"nvidia_nim": "NVIDIA NIM",
|
||||
"oci": "OCI",
|
||||
"ovhcloud": "OVHcloud",
|
||||
"palm": "PaLM",
|
||||
"publicai": "PublicAI",
|
||||
"runwayml": "RunwayML",
|
||||
"sambanova": "SambaNova",
|
||||
"together_ai": "Together AI",
|
||||
"vercel_ai_gateway": "Vercel AI Gateway",
|
||||
"volcengine": "Volcengine",
|
||||
"wandb": "W&B",
|
||||
"watsonx": "IBM watsonx",
|
||||
"zai": "ZAI",
|
||||
}
|
||||
|
||||
# Map vendors to their brand names (used for provider_display_name generation)
|
||||
|
||||
@@ -90,6 +90,7 @@ from onyx.onyxbot.slack.utils import respond_in_thread_or_channel
|
||||
from onyx.onyxbot.slack.utils import TenantSocketModeClient
|
||||
from onyx.redis.redis_pool import get_redis_client
|
||||
from onyx.server.manage.models import SlackBotTokens
|
||||
from onyx.tracing.setup import setup_tracing
|
||||
from onyx.utils.logger import setup_logger
|
||||
from onyx.utils.variable_functionality import fetch_ee_implementation_or_noop
|
||||
from onyx.utils.variable_functionality import set_is_ee_based_on_env_variable
|
||||
@@ -1206,6 +1207,7 @@ if __name__ == "__main__":
|
||||
tenant_handler = SlackbotHandler()
|
||||
|
||||
set_is_ee_based_on_env_variable()
|
||||
setup_tracing()
|
||||
|
||||
try:
|
||||
# Keep the main thread alive
|
||||
|
||||
@@ -58,7 +58,7 @@ docker buildx build --platform linux/amd64,linux/arm64 \
|
||||
|
||||
1. **Build and push** the new image (see above)
|
||||
|
||||
2. **Update the ConfigMap** in `cloud-deployment-yamls/danswer/configmap/env-configmap.yaml`:
|
||||
2. **Update the ConfigMap** in in the internal repo
|
||||
```yaml
|
||||
SANDBOX_CONTAINER_IMAGE: "onyxdotapp/sandbox:v0.1.x"
|
||||
```
|
||||
|
||||
@@ -40,6 +40,8 @@ from onyx.db.models import User
|
||||
from onyx.db.persona import user_can_access_persona
|
||||
from onyx.error_handling.error_codes import OnyxErrorCode
|
||||
from onyx.error_handling.exceptions import OnyxError
|
||||
from onyx.llm.constants import PROVIDER_DISPLAY_NAMES
|
||||
from onyx.llm.constants import WELL_KNOWN_PROVIDER_NAMES
|
||||
from onyx.llm.factory import get_default_llm
|
||||
from onyx.llm.factory import get_llm
|
||||
from onyx.llm.factory import get_max_input_tokens_from_llm_provider
|
||||
@@ -60,6 +62,7 @@ from onyx.server.manage.llm.models import BedrockFinalModelResponse
|
||||
from onyx.server.manage.llm.models import BedrockModelsRequest
|
||||
from onyx.server.manage.llm.models import BifrostFinalModelResponse
|
||||
from onyx.server.manage.llm.models import BifrostModelsRequest
|
||||
from onyx.server.manage.llm.models import CustomProviderOption
|
||||
from onyx.server.manage.llm.models import DefaultModel
|
||||
from onyx.server.manage.llm.models import LitellmFinalModelResponse
|
||||
from onyx.server.manage.llm.models import LitellmModelDetails
|
||||
@@ -250,6 +253,29 @@ def _validate_llm_provider_change(
|
||||
)
|
||||
|
||||
|
||||
@admin_router.get("/custom-provider-names")
|
||||
def fetch_custom_provider_names(
|
||||
_: User = Depends(require_permission(Permission.FULL_ADMIN_PANEL_ACCESS)),
|
||||
) -> list[CustomProviderOption]:
|
||||
"""Returns the sorted list of LiteLLM provider names that can be used
|
||||
with the custom provider modal (i.e. everything that is not already
|
||||
covered by a well-known provider modal)."""
|
||||
import litellm
|
||||
|
||||
well_known = {p.value for p in WELL_KNOWN_PROVIDER_NAMES}
|
||||
return sorted(
|
||||
(
|
||||
CustomProviderOption(
|
||||
value=name,
|
||||
label=PROVIDER_DISPLAY_NAMES.get(name, name.replace("_", " ").title()),
|
||||
)
|
||||
for name in litellm.models_by_provider.keys()
|
||||
if name not in well_known
|
||||
),
|
||||
key=lambda o: o.label.lower(),
|
||||
)
|
||||
|
||||
|
||||
@admin_router.get("/built-in/options")
|
||||
def fetch_llm_options(
|
||||
_: User = Depends(require_permission(Permission.FULL_ADMIN_PANEL_ACCESS)),
|
||||
|
||||
@@ -28,6 +28,13 @@ if TYPE_CHECKING:
|
||||
T = TypeVar("T", "LLMProviderDescriptor", "LLMProviderView", "VisionProviderResponse")
|
||||
|
||||
|
||||
class CustomProviderOption(BaseModel):
|
||||
"""A provider slug + human-friendly label for the custom-provider picker."""
|
||||
|
||||
value: str
|
||||
label: str
|
||||
|
||||
|
||||
class TestLLMRequest(BaseModel):
|
||||
# provider level
|
||||
id: int | None = None
|
||||
|
||||
72
backend/onyx/server/metrics/pruning_metrics.py
Normal file
72
backend/onyx/server/metrics/pruning_metrics.py
Normal file
@@ -0,0 +1,72 @@
|
||||
"""Pruning-specific Prometheus metrics.
|
||||
|
||||
Tracks three pruning pipeline phases for connector_pruning_generator_task:
|
||||
1. Document ID enumeration duration (extract_ids_from_runnable_connector)
|
||||
2. Diff + dispatch duration (DB lookup, set diff, generate_tasks)
|
||||
3. Rate limit errors during enumeration
|
||||
|
||||
All metrics are labeled by connector_type to identify which connector sources
|
||||
are the most expensive to prune. cc_pair_id is intentionally excluded to avoid
|
||||
unbounded cardinality.
|
||||
|
||||
Usage:
|
||||
from onyx.server.metrics.pruning_metrics import (
|
||||
observe_pruning_enumeration_duration,
|
||||
observe_pruning_diff_duration,
|
||||
inc_pruning_rate_limit_error,
|
||||
)
|
||||
"""
|
||||
|
||||
from prometheus_client import Counter
|
||||
from prometheus_client import Histogram
|
||||
|
||||
from onyx.utils.logger import setup_logger
|
||||
|
||||
logger = setup_logger()
|
||||
|
||||
PRUNING_ENUMERATION_DURATION = Histogram(
|
||||
"onyx_pruning_enumeration_duration_seconds",
|
||||
"Duration of document ID enumeration from the source connector during pruning",
|
||||
["connector_type"],
|
||||
buckets=[1, 5, 15, 30, 60, 120, 300, 600, 1800, 3600],
|
||||
)
|
||||
|
||||
PRUNING_DIFF_DURATION = Histogram(
|
||||
"onyx_pruning_diff_duration_seconds",
|
||||
"Duration of diff computation and subtask dispatch during pruning",
|
||||
["connector_type"],
|
||||
buckets=[1, 5, 15, 30, 60, 120, 300, 600, 1800, 3600],
|
||||
)
|
||||
|
||||
PRUNING_RATE_LIMIT_ERRORS = Counter(
|
||||
"onyx_pruning_rate_limit_errors_total",
|
||||
"Total rate limit errors encountered during pruning document ID enumeration",
|
||||
["connector_type"],
|
||||
)
|
||||
|
||||
|
||||
def observe_pruning_enumeration_duration(
|
||||
duration_seconds: float, connector_type: str
|
||||
) -> None:
|
||||
try:
|
||||
PRUNING_ENUMERATION_DURATION.labels(connector_type=connector_type).observe(
|
||||
duration_seconds
|
||||
)
|
||||
except Exception:
|
||||
logger.debug("Failed to record pruning enumeration duration", exc_info=True)
|
||||
|
||||
|
||||
def observe_pruning_diff_duration(duration_seconds: float, connector_type: str) -> None:
|
||||
try:
|
||||
PRUNING_DIFF_DURATION.labels(connector_type=connector_type).observe(
|
||||
duration_seconds
|
||||
)
|
||||
except Exception:
|
||||
logger.debug("Failed to record pruning diff duration", exc_info=True)
|
||||
|
||||
|
||||
def inc_pruning_rate_limit_error(connector_type: str) -> None:
|
||||
try:
|
||||
PRUNING_RATE_LIMIT_ERRORS.labels(connector_type=connector_type).inc()
|
||||
except Exception:
|
||||
logger.debug("Failed to record pruning rate limit error", exc_info=True)
|
||||
@@ -263,7 +263,7 @@ oauthlib==3.2.2
|
||||
# via
|
||||
# kubernetes
|
||||
# requests-oauthlib
|
||||
onyx-devtools==0.7.2
|
||||
onyx-devtools==0.7.3
|
||||
# via onyx
|
||||
openai==2.14.0
|
||||
# via
|
||||
|
||||
0
backend/tests/unit/background/__init__.py
Normal file
0
backend/tests/unit/background/__init__.py
Normal file
0
backend/tests/unit/background/celery/__init__.py
Normal file
0
backend/tests/unit/background/celery/__init__.py
Normal file
149
backend/tests/unit/background/celery/test_celery_utils.py
Normal file
149
backend/tests/unit/background/celery/test_celery_utils.py
Normal file
@@ -0,0 +1,149 @@
|
||||
"""Unit tests for extract_ids_from_runnable_connector metrics instrumentation."""
|
||||
|
||||
from collections.abc import Iterator
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from onyx.background.celery.celery_utils import extract_ids_from_runnable_connector
|
||||
from onyx.connectors.interfaces import SlimConnector
|
||||
from onyx.connectors.models import SlimDocument
|
||||
from onyx.server.metrics.pruning_metrics import PRUNING_ENUMERATION_DURATION
|
||||
from onyx.server.metrics.pruning_metrics import PRUNING_RATE_LIMIT_ERRORS
|
||||
|
||||
|
||||
def _make_slim_connector(doc_ids: list[str]) -> SlimConnector:
|
||||
"""Mock SlimConnector that yields the given doc IDs in one batch."""
|
||||
connector = MagicMock(spec=SlimConnector)
|
||||
docs = [
|
||||
MagicMock(spec=SlimDocument, id=doc_id, parent_hierarchy_raw_node_id=None)
|
||||
for doc_id in doc_ids
|
||||
]
|
||||
connector.retrieve_all_slim_docs.return_value = iter([docs])
|
||||
return connector
|
||||
|
||||
|
||||
def _raising_connector(message: str) -> SlimConnector:
|
||||
"""Mock SlimConnector whose generator raises with the given message."""
|
||||
connector = MagicMock(spec=SlimConnector)
|
||||
|
||||
def raising_iter() -> Iterator:
|
||||
raise Exception(message)
|
||||
yield
|
||||
|
||||
connector.retrieve_all_slim_docs.return_value = raising_iter()
|
||||
return connector
|
||||
|
||||
|
||||
class TestEnumerationDuration:
|
||||
def test_recorded_on_success(self) -> None:
|
||||
connector = _make_slim_connector(["doc1"])
|
||||
before = PRUNING_ENUMERATION_DURATION.labels(
|
||||
connector_type="google_drive"
|
||||
)._sum.get()
|
||||
|
||||
extract_ids_from_runnable_connector(connector, connector_type="google_drive")
|
||||
|
||||
after = PRUNING_ENUMERATION_DURATION.labels(
|
||||
connector_type="google_drive"
|
||||
)._sum.get()
|
||||
assert after >= before # duration observed (non-negative)
|
||||
|
||||
def test_recorded_on_exception(self) -> None:
|
||||
connector = _raising_connector("unexpected error")
|
||||
before = PRUNING_ENUMERATION_DURATION.labels(
|
||||
connector_type="confluence"
|
||||
)._sum.get()
|
||||
|
||||
with pytest.raises(Exception):
|
||||
extract_ids_from_runnable_connector(connector, connector_type="confluence")
|
||||
|
||||
after = PRUNING_ENUMERATION_DURATION.labels(
|
||||
connector_type="confluence"
|
||||
)._sum.get()
|
||||
assert after >= before # duration observed even on exception
|
||||
|
||||
|
||||
class TestRateLimitDetection:
|
||||
def test_increments_on_rate_limit_message(self) -> None:
|
||||
connector = _raising_connector("rate limit exceeded")
|
||||
before = PRUNING_RATE_LIMIT_ERRORS.labels(
|
||||
connector_type="google_drive"
|
||||
)._value.get()
|
||||
|
||||
with pytest.raises(Exception, match="rate limit exceeded"):
|
||||
extract_ids_from_runnable_connector(
|
||||
connector, connector_type="google_drive"
|
||||
)
|
||||
|
||||
after = PRUNING_RATE_LIMIT_ERRORS.labels(
|
||||
connector_type="google_drive"
|
||||
)._value.get()
|
||||
assert after == before + 1
|
||||
|
||||
def test_increments_on_429_in_message(self) -> None:
|
||||
connector = _raising_connector("HTTP 429 Too Many Requests")
|
||||
before = PRUNING_RATE_LIMIT_ERRORS.labels(
|
||||
connector_type="confluence"
|
||||
)._value.get()
|
||||
|
||||
with pytest.raises(Exception, match="429"):
|
||||
extract_ids_from_runnable_connector(connector, connector_type="confluence")
|
||||
|
||||
after = PRUNING_RATE_LIMIT_ERRORS.labels(
|
||||
connector_type="confluence"
|
||||
)._value.get()
|
||||
assert after == before + 1
|
||||
|
||||
def test_does_not_increment_on_non_rate_limit_exception(self) -> None:
|
||||
connector = _raising_connector("connection timeout")
|
||||
before = PRUNING_RATE_LIMIT_ERRORS.labels(connector_type="slack")._value.get()
|
||||
|
||||
with pytest.raises(Exception, match="connection timeout"):
|
||||
extract_ids_from_runnable_connector(connector, connector_type="slack")
|
||||
|
||||
after = PRUNING_RATE_LIMIT_ERRORS.labels(connector_type="slack")._value.get()
|
||||
assert after == before
|
||||
|
||||
def test_rate_limit_detection_is_case_insensitive(self) -> None:
|
||||
connector = _raising_connector("RATE LIMIT exceeded")
|
||||
before = PRUNING_RATE_LIMIT_ERRORS.labels(connector_type="jira")._value.get()
|
||||
|
||||
with pytest.raises(Exception):
|
||||
extract_ids_from_runnable_connector(connector, connector_type="jira")
|
||||
|
||||
after = PRUNING_RATE_LIMIT_ERRORS.labels(connector_type="jira")._value.get()
|
||||
assert after == before + 1
|
||||
|
||||
def test_connector_type_label_matches_input(self) -> None:
|
||||
connector = _raising_connector("rate limit exceeded")
|
||||
before_gd = PRUNING_RATE_LIMIT_ERRORS.labels(
|
||||
connector_type="google_drive"
|
||||
)._value.get()
|
||||
before_jira = PRUNING_RATE_LIMIT_ERRORS.labels(
|
||||
connector_type="jira"
|
||||
)._value.get()
|
||||
|
||||
with pytest.raises(Exception):
|
||||
extract_ids_from_runnable_connector(
|
||||
connector, connector_type="google_drive"
|
||||
)
|
||||
|
||||
assert (
|
||||
PRUNING_RATE_LIMIT_ERRORS.labels(connector_type="google_drive")._value.get()
|
||||
== before_gd + 1
|
||||
)
|
||||
assert (
|
||||
PRUNING_RATE_LIMIT_ERRORS.labels(connector_type="jira")._value.get()
|
||||
== before_jira
|
||||
)
|
||||
|
||||
def test_defaults_to_unknown_connector_type(self) -> None:
|
||||
connector = _raising_connector("rate limit exceeded")
|
||||
before = PRUNING_RATE_LIMIT_ERRORS.labels(connector_type="unknown")._value.get()
|
||||
|
||||
with pytest.raises(Exception):
|
||||
extract_ids_from_runnable_connector(connector)
|
||||
|
||||
after = PRUNING_RATE_LIMIT_ERRORS.labels(connector_type="unknown")._value.get()
|
||||
assert after == before + 1
|
||||
128
backend/tests/unit/server/metrics/test_pruning_metrics.py
Normal file
128
backend/tests/unit/server/metrics/test_pruning_metrics.py
Normal file
@@ -0,0 +1,128 @@
|
||||
"""Tests for pruning-specific Prometheus metrics."""
|
||||
|
||||
import pytest
|
||||
|
||||
from onyx.server.metrics.pruning_metrics import inc_pruning_rate_limit_error
|
||||
from onyx.server.metrics.pruning_metrics import observe_pruning_diff_duration
|
||||
from onyx.server.metrics.pruning_metrics import observe_pruning_enumeration_duration
|
||||
from onyx.server.metrics.pruning_metrics import PRUNING_DIFF_DURATION
|
||||
from onyx.server.metrics.pruning_metrics import PRUNING_ENUMERATION_DURATION
|
||||
from onyx.server.metrics.pruning_metrics import PRUNING_RATE_LIMIT_ERRORS
|
||||
|
||||
|
||||
class TestObservePruningEnumerationDuration:
|
||||
def test_observes_duration(self) -> None:
|
||||
before = PRUNING_ENUMERATION_DURATION.labels(
|
||||
connector_type="google_drive"
|
||||
)._sum.get()
|
||||
|
||||
observe_pruning_enumeration_duration(10.0, "google_drive")
|
||||
|
||||
after = PRUNING_ENUMERATION_DURATION.labels(
|
||||
connector_type="google_drive"
|
||||
)._sum.get()
|
||||
assert after == pytest.approx(before + 10.0)
|
||||
|
||||
def test_labels_by_connector_type(self) -> None:
|
||||
before_gd = PRUNING_ENUMERATION_DURATION.labels(
|
||||
connector_type="google_drive"
|
||||
)._sum.get()
|
||||
before_conf = PRUNING_ENUMERATION_DURATION.labels(
|
||||
connector_type="confluence"
|
||||
)._sum.get()
|
||||
|
||||
observe_pruning_enumeration_duration(5.0, "google_drive")
|
||||
|
||||
after_gd = PRUNING_ENUMERATION_DURATION.labels(
|
||||
connector_type="google_drive"
|
||||
)._sum.get()
|
||||
after_conf = PRUNING_ENUMERATION_DURATION.labels(
|
||||
connector_type="confluence"
|
||||
)._sum.get()
|
||||
|
||||
assert after_gd == pytest.approx(before_gd + 5.0)
|
||||
assert after_conf == pytest.approx(before_conf)
|
||||
|
||||
def test_does_not_raise_on_exception(self, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(
|
||||
PRUNING_ENUMERATION_DURATION,
|
||||
"labels",
|
||||
lambda **_: (_ for _ in ()).throw(RuntimeError("boom")),
|
||||
)
|
||||
observe_pruning_enumeration_duration(1.0, "google_drive")
|
||||
|
||||
|
||||
class TestObservePruningDiffDuration:
|
||||
def test_observes_duration(self) -> None:
|
||||
before = PRUNING_DIFF_DURATION.labels(connector_type="confluence")._sum.get()
|
||||
|
||||
observe_pruning_diff_duration(3.0, "confluence")
|
||||
|
||||
after = PRUNING_DIFF_DURATION.labels(connector_type="confluence")._sum.get()
|
||||
assert after == pytest.approx(before + 3.0)
|
||||
|
||||
def test_labels_by_connector_type(self) -> None:
|
||||
before_conf = PRUNING_DIFF_DURATION.labels(
|
||||
connector_type="confluence"
|
||||
)._sum.get()
|
||||
before_slack = PRUNING_DIFF_DURATION.labels(connector_type="slack")._sum.get()
|
||||
|
||||
observe_pruning_diff_duration(2.0, "confluence")
|
||||
|
||||
after_conf = PRUNING_DIFF_DURATION.labels(
|
||||
connector_type="confluence"
|
||||
)._sum.get()
|
||||
after_slack = PRUNING_DIFF_DURATION.labels(connector_type="slack")._sum.get()
|
||||
|
||||
assert after_conf == pytest.approx(before_conf + 2.0)
|
||||
assert after_slack == pytest.approx(before_slack)
|
||||
|
||||
def test_does_not_raise_on_exception(self, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(
|
||||
PRUNING_DIFF_DURATION,
|
||||
"labels",
|
||||
lambda **_: (_ for _ in ()).throw(RuntimeError("boom")),
|
||||
)
|
||||
observe_pruning_diff_duration(1.0, "confluence")
|
||||
|
||||
|
||||
class TestIncPruningRateLimitError:
|
||||
def test_increments_counter(self) -> None:
|
||||
before = PRUNING_RATE_LIMIT_ERRORS.labels(
|
||||
connector_type="google_drive"
|
||||
)._value.get()
|
||||
|
||||
inc_pruning_rate_limit_error("google_drive")
|
||||
|
||||
after = PRUNING_RATE_LIMIT_ERRORS.labels(
|
||||
connector_type="google_drive"
|
||||
)._value.get()
|
||||
assert after == before + 1
|
||||
|
||||
def test_labels_by_connector_type(self) -> None:
|
||||
before_gd = PRUNING_RATE_LIMIT_ERRORS.labels(
|
||||
connector_type="google_drive"
|
||||
)._value.get()
|
||||
before_jira = PRUNING_RATE_LIMIT_ERRORS.labels(
|
||||
connector_type="jira"
|
||||
)._value.get()
|
||||
|
||||
inc_pruning_rate_limit_error("google_drive")
|
||||
|
||||
after_gd = PRUNING_RATE_LIMIT_ERRORS.labels(
|
||||
connector_type="google_drive"
|
||||
)._value.get()
|
||||
after_jira = PRUNING_RATE_LIMIT_ERRORS.labels(
|
||||
connector_type="jira"
|
||||
)._value.get()
|
||||
|
||||
assert after_gd == before_gd + 1
|
||||
assert after_jira == before_jira
|
||||
|
||||
def test_does_not_raise_on_exception(self, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(
|
||||
PRUNING_RATE_LIMIT_ERRORS,
|
||||
"labels",
|
||||
lambda **_: (_ for _ in ()).throw(RuntimeError("boom")),
|
||||
)
|
||||
inc_pruning_rate_limit_error("google_drive")
|
||||
@@ -19,6 +19,6 @@ dependencies:
|
||||
version: 5.4.0
|
||||
- name: code-interpreter
|
||||
repository: https://onyx-dot-app.github.io/python-sandbox/
|
||||
version: 0.3.2
|
||||
digest: sha256:74908ea45ace2b4be913ff762772e6d87e40bab64e92c6662aa51730eaeb9d87
|
||||
generated: "2026-04-06T15:34:02.597166-07:00"
|
||||
version: 0.3.3
|
||||
digest: sha256:a57f29088b1624a72f6c70e4c3ccc2f2aad675e4624278c4e9be92083d6d5dad
|
||||
generated: "2026-04-08T16:47:29.33368-07:00"
|
||||
|
||||
@@ -45,6 +45,6 @@ dependencies:
|
||||
repository: https://charts.min.io/
|
||||
condition: minio.enabled
|
||||
- name: code-interpreter
|
||||
version: 0.3.2
|
||||
version: 0.3.3
|
||||
repository: https://onyx-dot-app.github.io/python-sandbox/
|
||||
condition: codeInterpreter.enabled
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
{{- /* Metrics port must match the default in metrics_server.py (_DEFAULT_PORTS).
|
||||
Do NOT use PROMETHEUS_METRICS_PORT env var in Helm — each worker needs its own port. */ -}}
|
||||
{{- if gt (int .Values.celery_worker_heavy.replicaCount) 0 }}
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: {{ include "onyx.fullname" . }}-celery-worker-heavy-metrics
|
||||
labels:
|
||||
{{- include "onyx.labels" . | nindent 4 }}
|
||||
{{- if .Values.celery_worker_heavy.deploymentLabels }}
|
||||
{{- toYaml .Values.celery_worker_heavy.deploymentLabels | nindent 4 }}
|
||||
{{- end }}
|
||||
metrics: "true"
|
||||
spec:
|
||||
type: ClusterIP
|
||||
ports:
|
||||
- port: 9094
|
||||
targetPort: metrics
|
||||
protocol: TCP
|
||||
name: metrics
|
||||
selector:
|
||||
{{- include "onyx.selectorLabels" . | nindent 4 }}
|
||||
{{- if .Values.celery_worker_heavy.deploymentLabels }}
|
||||
{{- toYaml .Values.celery_worker_heavy.deploymentLabels | nindent 4 }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
@@ -148,7 +148,7 @@ dev = [
|
||||
"matplotlib==3.10.8",
|
||||
"mypy-extensions==1.0.0",
|
||||
"mypy==1.13.0",
|
||||
"onyx-devtools==0.7.2",
|
||||
"onyx-devtools==0.7.3",
|
||||
"openapi-generator-cli==7.17.0",
|
||||
"pandas-stubs~=2.3.3",
|
||||
"pre-commit==3.2.2",
|
||||
|
||||
19
tools/ods/cmd/deploy.go
Normal file
19
tools/ods/cmd/deploy.go
Normal file
@@ -0,0 +1,19 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// NewDeployCommand creates the parent `ods deploy` command. Subcommands hang
|
||||
// off it (e.g. `ods deploy edge`) and represent ad-hoc deployment workflows.
|
||||
func NewDeployCommand() *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "deploy",
|
||||
Short: "Trigger ad-hoc deployments",
|
||||
Long: "Trigger ad-hoc deployments to Onyx-managed environments.",
|
||||
}
|
||||
|
||||
cmd.AddCommand(NewDeployEdgeCommand())
|
||||
|
||||
return cmd
|
||||
}
|
||||
353
tools/ods/cmd/deploy_edge.go
Normal file
353
tools/ods/cmd/deploy_edge.go
Normal file
@@ -0,0 +1,353 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/onyx-dot-app/onyx/tools/ods/internal/config"
|
||||
"github.com/onyx-dot-app/onyx/tools/ods/internal/git"
|
||||
"github.com/onyx-dot-app/onyx/tools/ods/internal/paths"
|
||||
"github.com/onyx-dot-app/onyx/tools/ods/internal/prompt"
|
||||
)
|
||||
|
||||
const (
|
||||
onyxRepo = "onyx-dot-app/onyx"
|
||||
deploymentWorkflowFile = "deployment.yml"
|
||||
edgeTagName = "edge"
|
||||
|
||||
// Polling configuration. Build runs typically take 20-30 minutes; deploys
|
||||
// are much shorter. The "discover" phase polls fast for a short window
|
||||
// because the run usually appears within seconds of pushing the tag /
|
||||
// dispatching the workflow.
|
||||
runDiscoveryInterval = 5 * time.Second
|
||||
runDiscoveryTimeout = 2 * time.Minute
|
||||
runProgressInterval = 30 * time.Second
|
||||
buildPollTimeout = 60 * time.Minute
|
||||
deployPollTimeout = 30 * time.Minute
|
||||
)
|
||||
|
||||
// DeployEdgeOptions holds options for the deploy edge command.
|
||||
type DeployEdgeOptions struct {
|
||||
TargetRepo string
|
||||
TargetWorkflow string
|
||||
DryRun bool
|
||||
Yes bool
|
||||
NoWaitDeploy bool
|
||||
}
|
||||
|
||||
// NewDeployEdgeCommand creates the `ods deploy edge` command.
|
||||
func NewDeployEdgeCommand() *cobra.Command {
|
||||
opts := &DeployEdgeOptions{}
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "edge",
|
||||
Short: "Build edge images off main and deploy to the configured target",
|
||||
Long: `Build edge images off origin/main and dispatch the configured deploy workflow.
|
||||
|
||||
This command will:
|
||||
1. Force-push the 'edge' tag to origin/main, triggering the build
|
||||
2. Wait for the build workflow to finish
|
||||
3. Dispatch the configured deploy workflow with version_tag=edge
|
||||
4. Wait for the deploy workflow to finish
|
||||
|
||||
All GitHub operations run through the gh CLI, so authorization is enforced
|
||||
by your gh credentials and GitHub's repo/workflow permissions.
|
||||
|
||||
On first run, you'll be prompted for the deploy target repo and workflow
|
||||
filename. These are saved to the ods config file (~/.config/onyx-dev/config.json
|
||||
on Linux/macOS) and reused on subsequent runs. Pass --target-repo or
|
||||
--target-workflow to override the saved values.
|
||||
|
||||
Example usage:
|
||||
|
||||
$ ods deploy edge`,
|
||||
Args: cobra.NoArgs,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
deployEdge(opts)
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().StringVar(&opts.TargetRepo, "target-repo", "", "GitHub repo (owner/name) hosting the deploy workflow; overrides saved config")
|
||||
cmd.Flags().StringVar(&opts.TargetWorkflow, "target-workflow", "", "Filename of the deploy workflow within the target repo; overrides saved config")
|
||||
cmd.Flags().BoolVar(&opts.DryRun, "dry-run", false, "Perform local operations only; skip pushing the tag and dispatching workflows")
|
||||
cmd.Flags().BoolVar(&opts.Yes, "yes", false, "Skip the confirmation prompt")
|
||||
cmd.Flags().BoolVar(&opts.NoWaitDeploy, "no-wait-deploy", false, "Do not wait for the deploy workflow to finish after dispatching it")
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
func deployEdge(opts *DeployEdgeOptions) {
|
||||
git.CheckGitHubCLI()
|
||||
|
||||
deployRepo, deployWorkflow := resolveDeployTarget(opts)
|
||||
|
||||
if opts.DryRun {
|
||||
log.Warning("=== DRY RUN MODE: tag push and workflow dispatch will be skipped (read-only gh and git fetch still run) ===")
|
||||
}
|
||||
|
||||
if !opts.Yes {
|
||||
msg := "About to force-push tag 'edge' to origin/main and trigger an ad-hoc deploy. Continue? (Y/n): "
|
||||
if !prompt.Confirm(msg) {
|
||||
log.Info("Exiting...")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Capture the most recent existing edge build run id BEFORE pushing, so we
|
||||
// can reliably identify the new run we trigger and not pick up a stale one.
|
||||
priorBuildRunID, err := latestWorkflowRunID(onyxRepo, deploymentWorkflowFile, "push", edgeTagName)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to query existing deployment runs: %v", err)
|
||||
}
|
||||
log.Debugf("Most recent prior edge build run id: %d", priorBuildRunID)
|
||||
|
||||
log.Info("Fetching origin/main...")
|
||||
if err := git.RunCommand("fetch", "origin", "main"); err != nil {
|
||||
log.Fatalf("Failed to fetch origin/main: %v", err)
|
||||
}
|
||||
|
||||
if opts.DryRun {
|
||||
log.Warnf("[DRY RUN] Would move local '%s' tag to origin/main", edgeTagName)
|
||||
log.Warnf("[DRY RUN] Would force-push tag '%s' to origin", edgeTagName)
|
||||
log.Warn("[DRY RUN] Would wait for build then dispatch the configured deploy workflow")
|
||||
return
|
||||
}
|
||||
|
||||
log.Infof("Moving local '%s' tag to origin/main...", edgeTagName)
|
||||
if err := git.RunCommand("tag", "-f", edgeTagName, "origin/main"); err != nil {
|
||||
log.Fatalf("Failed to move local tag: %v", err)
|
||||
}
|
||||
|
||||
log.Infof("Force-pushing tag '%s' to origin...", edgeTagName)
|
||||
if err := git.RunCommand("push", "-f", "origin", edgeTagName); err != nil {
|
||||
log.Fatalf("Failed to push edge tag: %v", err)
|
||||
}
|
||||
|
||||
// Find the new build run, then poll it to completion.
|
||||
log.Info("Waiting for build workflow to start...")
|
||||
buildRun, err := waitForNewRun(onyxRepo, deploymentWorkflowFile, "push", edgeTagName, priorBuildRunID)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to find triggered build run: %v", err)
|
||||
}
|
||||
log.Infof("Build run started: %s", buildRun.URL)
|
||||
|
||||
if err := waitForRunCompletion(onyxRepo, buildRun.DatabaseID, buildPollTimeout, "build"); err != nil {
|
||||
log.Fatalf("Build did not complete successfully: %v", err)
|
||||
}
|
||||
log.Info("Build completed successfully.")
|
||||
|
||||
// Dispatch the deploy workflow.
|
||||
priorDeployRunID, err := latestWorkflowRunID(deployRepo, deployWorkflow, "workflow_dispatch", "")
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to query existing deploy runs: %v", err)
|
||||
}
|
||||
log.Debugf("Most recent prior deploy run id: %d", priorDeployRunID)
|
||||
|
||||
log.Info("Dispatching deploy workflow with version_tag=edge...")
|
||||
if err := dispatchWorkflow(deployRepo, deployWorkflow, map[string]string{"version_tag": edgeTagName}); err != nil {
|
||||
log.Fatalf("Failed to dispatch deploy workflow: %v", err)
|
||||
}
|
||||
|
||||
deployRun, err := waitForNewRun(deployRepo, deployWorkflow, "workflow_dispatch", "", priorDeployRunID)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to find dispatched deploy run: %v", err)
|
||||
}
|
||||
log.Infof("Deploy run started: %s", deployRun.URL)
|
||||
log.Info("A kickoff Slack message will appear in #monitor-deployments.")
|
||||
|
||||
if opts.NoWaitDeploy {
|
||||
log.Info("--no-wait-deploy set; not waiting for deploy completion.")
|
||||
return
|
||||
}
|
||||
|
||||
if err := waitForRunCompletion(deployRepo, deployRun.DatabaseID, deployPollTimeout, "deploy"); err != nil {
|
||||
log.Fatalf("Deploy did not complete successfully: %v", err)
|
||||
}
|
||||
log.Info("Deploy completed successfully.")
|
||||
}
|
||||
|
||||
// resolveDeployTarget returns the deploy target repo and workflow to use,
|
||||
// preferring explicit flags, then saved config, then prompting the user on
|
||||
// first-time setup. Any newly-prompted values are persisted back to the
|
||||
// config file so subsequent runs are non-interactive.
|
||||
func resolveDeployTarget(opts *DeployEdgeOptions) (string, string) {
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to load ods config: %v", err)
|
||||
}
|
||||
|
||||
repo := opts.TargetRepo
|
||||
if repo == "" {
|
||||
repo = cfg.DeployEdge.TargetRepo
|
||||
}
|
||||
workflow := opts.TargetWorkflow
|
||||
if workflow == "" {
|
||||
workflow = cfg.DeployEdge.TargetWorkflow
|
||||
}
|
||||
|
||||
prompted := false
|
||||
if repo == "" {
|
||||
log.Infof("First-time setup: ods will save your deploy target to %s", paths.ConfigFilePath())
|
||||
repo = prompt.String("Deploy target repo (owner/name): ")
|
||||
prompted = true
|
||||
}
|
||||
if workflow == "" {
|
||||
workflow = prompt.String("Deploy workflow filename (e.g. some-workflow.yml): ")
|
||||
prompted = true
|
||||
}
|
||||
|
||||
if prompted {
|
||||
cfg.DeployEdge.TargetRepo = repo
|
||||
cfg.DeployEdge.TargetWorkflow = workflow
|
||||
if err := config.Save(cfg); err != nil {
|
||||
log.Fatalf("Failed to save ods config: %v", err)
|
||||
}
|
||||
log.Infof("Saved deploy target to %s", paths.ConfigFilePath())
|
||||
}
|
||||
|
||||
return repo, workflow
|
||||
}
|
||||
|
||||
// workflowRun is a partial representation of a `gh run list` JSON entry.
|
||||
type workflowRun struct {
|
||||
DatabaseID int64 `json:"databaseId"`
|
||||
Status string `json:"status"`
|
||||
Conclusion string `json:"conclusion"`
|
||||
URL string `json:"url"`
|
||||
Event string `json:"event"`
|
||||
HeadBranch string `json:"headBranch"`
|
||||
}
|
||||
|
||||
// latestWorkflowRunID returns the highest databaseId for runs of the given
|
||||
// workflow filtered by event (and optional branch). Returns 0 if no runs
|
||||
// exist yet, which is a valid state.
|
||||
func latestWorkflowRunID(repo, workflowFile, event, branch string) (int64, error) {
|
||||
runs, err := listWorkflowRuns(repo, workflowFile, event, branch, 10)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var maxID int64
|
||||
for _, r := range runs {
|
||||
if r.DatabaseID > maxID {
|
||||
maxID = r.DatabaseID
|
||||
}
|
||||
}
|
||||
return maxID, nil
|
||||
}
|
||||
|
||||
func listWorkflowRuns(repo, workflowFile, event, branch string, limit int) ([]workflowRun, error) {
|
||||
args := []string{
|
||||
"run", "list",
|
||||
"-R", repo,
|
||||
"--workflow", workflowFile,
|
||||
"--limit", fmt.Sprintf("%d", limit),
|
||||
"--json", "databaseId,status,conclusion,url,event,headBranch",
|
||||
}
|
||||
if event != "" {
|
||||
args = append(args, "--event", event)
|
||||
}
|
||||
if branch != "" {
|
||||
args = append(args, "--branch", branch)
|
||||
}
|
||||
cmd := exec.Command("gh", args...)
|
||||
output, err := cmd.Output()
|
||||
if err != nil {
|
||||
if exitErr, ok := err.(*exec.ExitError); ok {
|
||||
return nil, fmt.Errorf("gh run list failed: %w: %s", err, string(exitErr.Stderr))
|
||||
}
|
||||
return nil, fmt.Errorf("gh run list failed: %w", err)
|
||||
}
|
||||
var runs []workflowRun
|
||||
if err := json.Unmarshal(output, &runs); err != nil {
|
||||
return nil, fmt.Errorf("failed to parse gh run list output: %w", err)
|
||||
}
|
||||
// Sort newest-first by databaseId for predictable iteration.
|
||||
sort.Slice(runs, func(i, j int) bool { return runs[i].DatabaseID > runs[j].DatabaseID })
|
||||
return runs, nil
|
||||
}
|
||||
|
||||
// waitForNewRun polls until a workflow run with databaseId > priorRunID
|
||||
// appears, or the discovery timeout fires.
|
||||
func waitForNewRun(repo, workflowFile, event, branch string, priorRunID int64) (*workflowRun, error) {
|
||||
deadline := time.Now().Add(runDiscoveryTimeout)
|
||||
for {
|
||||
runs, err := listWorkflowRuns(repo, workflowFile, event, branch, 5)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, r := range runs {
|
||||
if r.DatabaseID > priorRunID {
|
||||
return &r, nil
|
||||
}
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
return nil, fmt.Errorf("no new run appeared within %s", runDiscoveryTimeout)
|
||||
}
|
||||
time.Sleep(runDiscoveryInterval)
|
||||
}
|
||||
}
|
||||
|
||||
// waitForRunCompletion polls a specific run until it reaches a terminal
|
||||
// status. Returns an error if the run does not conclude with success or the
|
||||
// timeout fires.
|
||||
func waitForRunCompletion(repo string, runID int64, timeout time.Duration, label string) error {
|
||||
deadline := time.Now().Add(timeout)
|
||||
for {
|
||||
run, err := getRun(repo, runID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
log.Infof("[%s] run %d status=%s conclusion=%s", label, runID, run.Status, run.Conclusion)
|
||||
if run.Status == "completed" {
|
||||
if run.Conclusion == "success" {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("%s run %d concluded with status %q (see %s)", label, runID, run.Conclusion, run.URL)
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
return fmt.Errorf("%s run %d did not complete within %s (see %s)", label, runID, timeout, run.URL)
|
||||
}
|
||||
time.Sleep(runProgressInterval)
|
||||
}
|
||||
}
|
||||
|
||||
func getRun(repo string, runID int64) (*workflowRun, error) {
|
||||
cmd := exec.Command(
|
||||
"gh", "run", "view", fmt.Sprintf("%d", runID),
|
||||
"-R", repo,
|
||||
"--json", "databaseId,status,conclusion,url,event,headBranch",
|
||||
)
|
||||
output, err := cmd.Output()
|
||||
if err != nil {
|
||||
if exitErr, ok := err.(*exec.ExitError); ok {
|
||||
return nil, fmt.Errorf("gh run view failed: %w: %s", err, string(exitErr.Stderr))
|
||||
}
|
||||
return nil, fmt.Errorf("gh run view failed: %w", err)
|
||||
}
|
||||
var run workflowRun
|
||||
if err := json.Unmarshal(output, &run); err != nil {
|
||||
return nil, fmt.Errorf("failed to parse gh run view output: %w", err)
|
||||
}
|
||||
return &run, nil
|
||||
}
|
||||
|
||||
// dispatchWorkflow fires a workflow_dispatch event for the given workflow with
|
||||
// the supplied string inputs.
|
||||
func dispatchWorkflow(repo, workflowFile string, inputs map[string]string) error {
|
||||
args := []string{"workflow", "run", workflowFile, "-R", repo}
|
||||
for k, v := range inputs {
|
||||
args = append(args, "-f", fmt.Sprintf("%s=%s", k, v))
|
||||
}
|
||||
cmd := exec.Command("gh", args...)
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("gh workflow run failed: %w: %s", err, string(output))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -45,6 +45,7 @@ func NewRootCommand() *cobra.Command {
|
||||
cmd.AddCommand(NewCheckLazyImportsCommand())
|
||||
cmd.AddCommand(NewCherryPickCommand())
|
||||
cmd.AddCommand(NewDBCommand())
|
||||
cmd.AddCommand(NewDeployCommand())
|
||||
cmd.AddCommand(NewOpenAPICommand())
|
||||
cmd.AddCommand(NewComposeCommand())
|
||||
cmd.AddCommand(NewLogsCommand())
|
||||
|
||||
56
tools/ods/internal/config/config.go
Normal file
56
tools/ods/internal/config/config.go
Normal file
@@ -0,0 +1,56 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/onyx-dot-app/onyx/tools/ods/internal/paths"
|
||||
)
|
||||
|
||||
// DeployEdgeConfig holds the persisted settings for `ods deploy edge`.
|
||||
type DeployEdgeConfig struct {
|
||||
TargetRepo string `json:"target_repo,omitempty"`
|
||||
TargetWorkflow string `json:"target_workflow,omitempty"`
|
||||
}
|
||||
|
||||
// Config is the top-level on-disk schema for ~/.config/onyx-dev/config.json.
|
||||
// New per-command sections should be added as additional fields.
|
||||
type Config struct {
|
||||
DeployEdge DeployEdgeConfig `json:"deploy_edge,omitempty"`
|
||||
}
|
||||
|
||||
// Load reads the config file. Returns a zero-valued Config if the file does
|
||||
// not exist (a fresh first-run state, not an error).
|
||||
func Load() (*Config, error) {
|
||||
path := paths.ConfigFilePath()
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return &Config{}, nil
|
||||
}
|
||||
return nil, fmt.Errorf("failed to read config file %s: %w", path, err)
|
||||
}
|
||||
var cfg Config
|
||||
if err := json.Unmarshal(data, &cfg); err != nil {
|
||||
return nil, fmt.Errorf("failed to parse config file %s: %w", path, err)
|
||||
}
|
||||
return &cfg, nil
|
||||
}
|
||||
|
||||
// Save persists the config to disk, creating the parent directory if needed.
|
||||
func Save(cfg *Config) error {
|
||||
if err := paths.EnsureConfigDir(); err != nil {
|
||||
return fmt.Errorf("failed to create config directory: %w", err)
|
||||
}
|
||||
data, err := json.MarshalIndent(cfg, "", " ")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal config: %w", err)
|
||||
}
|
||||
path := paths.ConfigFilePath()
|
||||
if err := os.WriteFile(path, data, 0644); err != nil {
|
||||
return fmt.Errorf("failed to write config file %s: %w", path, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -47,6 +47,43 @@ func DataDir() string {
|
||||
return filepath.Join(base, "onyx-dev")
|
||||
}
|
||||
|
||||
// ConfigDir returns the per-user config directory for onyx-dev tools.
|
||||
// On Linux/macOS: ~/.config/onyx-dev/ (respects XDG_CONFIG_HOME)
|
||||
// On Windows: %APPDATA%/onyx-dev/
|
||||
func ConfigDir() string {
|
||||
var base string
|
||||
if runtime.GOOS == "windows" {
|
||||
base = os.Getenv("APPDATA")
|
||||
if base == "" {
|
||||
base = os.Getenv("USERPROFILE")
|
||||
if base == "" {
|
||||
log.Fatalf("Cannot determine config directory: APPDATA and USERPROFILE are not set")
|
||||
}
|
||||
base = filepath.Join(base, "AppData", "Roaming")
|
||||
}
|
||||
} else {
|
||||
base = os.Getenv("XDG_CONFIG_HOME")
|
||||
if base == "" {
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil || home == "" {
|
||||
log.Fatalf("Cannot determine config directory: XDG_CONFIG_HOME not set and home directory unknown: %v", err)
|
||||
}
|
||||
base = filepath.Join(home, ".config")
|
||||
}
|
||||
}
|
||||
return filepath.Join(base, "onyx-dev")
|
||||
}
|
||||
|
||||
// ConfigFilePath returns the path to the ods config file.
|
||||
func ConfigFilePath() string {
|
||||
return filepath.Join(ConfigDir(), "config.json")
|
||||
}
|
||||
|
||||
// EnsureConfigDir creates the config directory if it doesn't exist.
|
||||
func EnsureConfigDir() error {
|
||||
return os.MkdirAll(ConfigDir(), 0755)
|
||||
}
|
||||
|
||||
// SnapshotsDir returns the directory for database snapshots.
|
||||
func SnapshotsDir() string {
|
||||
return filepath.Join(DataDir(), "snapshots")
|
||||
|
||||
@@ -12,6 +12,23 @@ import (
|
||||
// reader is the input reader, can be replaced for testing
|
||||
var reader = bufio.NewReader(os.Stdin)
|
||||
|
||||
// String prompts the user for a free-form line of input. Re-prompts until a
|
||||
// non-empty value is entered.
|
||||
func String(prompt string) string {
|
||||
for {
|
||||
fmt.Print(prompt)
|
||||
response, err := reader.ReadString('\n')
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to read input: %v", err)
|
||||
}
|
||||
response = strings.TrimSpace(response)
|
||||
if response != "" {
|
||||
return response
|
||||
}
|
||||
fmt.Println("Value cannot be empty.")
|
||||
}
|
||||
}
|
||||
|
||||
// Confirm prompts the user with a yes/no question and returns true for yes, false for no.
|
||||
// It will keep prompting until a valid response is given.
|
||||
// Empty input (just pressing Enter) defaults to yes.
|
||||
|
||||
16
uv.lock
generated
16
uv.lock
generated
@@ -4459,7 +4459,7 @@ requires-dist = [
|
||||
{ name = "numpy", marker = "extra == 'model-server'", specifier = "==2.4.1" },
|
||||
{ name = "oauthlib", marker = "extra == 'backend'", specifier = "==3.2.2" },
|
||||
{ name = "office365-rest-python-client", marker = "extra == 'backend'", specifier = "==2.6.2" },
|
||||
{ name = "onyx-devtools", marker = "extra == 'dev'", specifier = "==0.7.2" },
|
||||
{ name = "onyx-devtools", marker = "extra == 'dev'", specifier = "==0.7.3" },
|
||||
{ name = "openai", specifier = "==2.14.0" },
|
||||
{ name = "openapi-generator-cli", marker = "extra == 'dev'", specifier = "==7.17.0" },
|
||||
{ name = "openinference-instrumentation", marker = "extra == 'backend'", specifier = "==0.1.42" },
|
||||
@@ -4564,19 +4564,19 @@ requires-dist = [{ name = "onyx", extras = ["backend", "dev", "ee"], editable =
|
||||
|
||||
[[package]]
|
||||
name = "onyx-devtools"
|
||||
version = "0.7.2"
|
||||
version = "0.7.3"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "fastapi" },
|
||||
{ name = "openapi-generator-cli" },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/22/b0/765ed49157470e8ccc8ab89e6a896ade50cde3aa2a494662ad4db92a48c4/onyx_devtools-0.7.2-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:553a2b5e61b29b7913c991c8d5aed78f930f0f81a0f42229c6a8de2b1e8ff57e", size = 4203859, upload-time = "2026-03-27T15:09:49.63Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f7/9d/bba0a44a16d2fc27e5441aaf10727e10514e7a49bce70eca02bced566eb9/onyx_devtools-0.7.2-py3-none-macosx_11_0_arm64.whl", hash = "sha256:5cf0782dca8b3d861de9e18e65e990cfce5161cd559df44d8fabd3fefd54fdcd", size = 3879750, upload-time = "2026-03-27T15:09:42.413Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/4d/d8/c5725e8af14c74fe0aeed29e4746400bb3c0a078fd1240df729dc6432b84/onyx_devtools-0.7.2-py3-none-manylinux_2_17_aarch64.whl", hash = "sha256:9a0d67373e16b4fbb38a5290c0d9dfd4cfa837e5da0c165b32841b9d37f7455b", size = 3743529, upload-time = "2026-03-27T15:09:44.546Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/1a/82/b7c398a21dbc3e14fd7a29e49caa86b1bc0f8d7c75c051514785441ab779/onyx_devtools-0.7.2-py3-none-manylinux_2_17_x86_64.whl", hash = "sha256:794af14b2de575d0ae41b94551399eca8f8ba9b950c5db7acb7612767fd228f9", size = 4166562, upload-time = "2026-03-27T15:09:49.471Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/26/76/be129e2baafc91fe792d919b1f4d73fc943ba9c2b728a60f1fb98e0c115a/onyx_devtools-0.7.2-py3-none-win_amd64.whl", hash = "sha256:83b3eb84df58d865e4f714222a5fab3ea464836e2c8690569454a940bbb651ff", size = 4282270, upload-time = "2026-03-27T15:09:44.676Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/3b/72/29b8c8dbcf069c56475f00511f04c4aaa5ba3faba1dfc8276107d4b3ef7f/onyx_devtools-0.7.2-py3-none-win_arm64.whl", hash = "sha256:62f0836624ee6a5b31e64fd93162e7fce142ac8a4f959607e411824bc2b88174", size = 3823053, upload-time = "2026-03-27T15:09:43.546Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/72/64/c75be8ab325896cc64bccd0e1e139a03ce305bf05598967922d380fc4694/onyx_devtools-0.7.3-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:675e2fdbd8d291fba4b8a6dfcf2bc94c56d22d11f395a9f0d0c3c0e5b39d7f9b", size = 4220613, upload-time = "2026-04-09T00:04:36.624Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ae/1f/589ff6bd446c4498f5bcdfd2a315709e91fc15edf5440c91ff64cbf0800f/onyx_devtools-0.7.3-py3-none-macosx_11_0_arm64.whl", hash = "sha256:bf3993de8ba02d6c2f1ab12b5b9b965e005040b37502f97db8a7d88d9b0cde4b", size = 3897867, upload-time = "2026-04-09T00:04:40.781Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/10/c0/53c9173eefc13218707282c5b99753960d039684994c3b3caf90ce286094/onyx_devtools-0.7.3-py3-none-manylinux_2_17_aarch64.whl", hash = "sha256:6138a94084bed05c674ad210a0bc4006c43bc4384e8eb54d469233de85c72bd7", size = 3762408, upload-time = "2026-04-09T00:04:41.592Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d2/37/69fadb65112854a596d200f704da94b837817d4dd0f46cb4482dc0309c94/onyx_devtools-0.7.3-py3-none-manylinux_2_17_x86_64.whl", hash = "sha256:90dac91b0cdc32eb8861f6e83545009a34c439fd3c41fc7dd499acd0105b660e", size = 4184427, upload-time = "2026-04-09T00:04:41.525Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/bd/45/91c829ccb45f1a15e7c9641eccc6dd154adb540e03c7dee2a8f28cea24d0/onyx_devtools-0.7.3-py3-none-win_amd64.whl", hash = "sha256:abc68d70bec06e349481beec4b212de28a1a8b7ed6ef3b41daf7093ee10b44f3", size = 4299935, upload-time = "2026-04-09T00:04:40.262Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/cc/30/c5adcb8e3b46b71d8d92c3f9ee0c1d0bc5e2adc9f46e93931f21b36a3ee4/onyx_devtools-0.7.3-py3-none-win_arm64.whl", hash = "sha256:9e4411cadc5e81fabc9ed991402e3b4b40f02800681299c277b2142e5af0dcee", size = 3840228, upload-time = "2026-04-09T00:04:39.708Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -14,21 +14,23 @@ All scripts in this directory should be run from the **opal package root** (`web
|
||||
web/lib/opal/
|
||||
├── scripts/ # SVG conversion tooling (this directory)
|
||||
│ ├── convert-svg.sh # Converts SVGs into React components
|
||||
│ └── icon-template.js # Shared SVGR template (used for both icons and illustrations)
|
||||
│ └── icon-template.js # Shared SVGR template (used for icons, logos, and illustrations)
|
||||
├── src/
|
||||
│ ├── icons/ # Small, single-colour icons (stroke = currentColor)
|
||||
│ ├── logos/ # Brand/vendor logos (original colours preserved)
|
||||
│ └── illustrations/ # Larger, multi-colour illustrations (colours preserved)
|
||||
└── package.json
|
||||
```
|
||||
|
||||
## Icons vs Illustrations
|
||||
## Icons vs Logos vs Illustrations
|
||||
|
||||
| | Icons | Illustrations |
|
||||
|---|---|---|
|
||||
| **Import path** | `@opal/icons` | `@opal/illustrations` |
|
||||
| **Location** | `src/icons/` | `src/illustrations/` |
|
||||
| **Colour** | Overridable via `currentColor` | Fixed — original SVG colours preserved |
|
||||
| **Script flag** | (none) | `--illustration` |
|
||||
| | Icons | Logos | Illustrations |
|
||||
|---|---|---|---|
|
||||
| **Import path** | `@opal/icons` | `@opal/logos` | `@opal/illustrations` |
|
||||
| **Location** | `src/icons/` | `src/logos/` | `src/illustrations/` |
|
||||
| **Colour** | Overridable via `currentColor` | Fixed — original brand colours preserved | Fixed — original SVG colours preserved |
|
||||
| **Script flag** | (none) | `--logo` | `--illustration` |
|
||||
| **Use case** | UI elements, actions, navigation | Provider logos, platform logos, brand marks | Empty states, error pages, placeholders |
|
||||
|
||||
## Files in This Directory
|
||||
|
||||
@@ -49,12 +51,19 @@ Converts an SVG into a React component. Behaviour depends on the mode:
|
||||
- Adds `width={size}`, `height={size}`, and `stroke="currentColor"`
|
||||
- Result is colour-overridable via CSS `color` property
|
||||
|
||||
**Logo mode** (`--logo`):
|
||||
- Strips only `width` and `height` attributes (all colours preserved)
|
||||
- Adds `width={size}` and `height={size}`
|
||||
- Does **not** add `stroke="currentColor"` — logos keep their original brand colours
|
||||
|
||||
**Illustration mode** (`--illustration`):
|
||||
- Strips only `width` and `height` attributes (all colours preserved)
|
||||
- Adds `width={size}` and `height={size}`
|
||||
- Does **not** add `stroke="currentColor"` — illustrations keep their original colours
|
||||
|
||||
Both modes automatically delete the source SVG file after successful conversion.
|
||||
Both `--logo` and `--illustration` produce the same output — the distinction is purely organizational (different directories, different barrel exports).
|
||||
|
||||
All modes automatically delete the source SVG file after successful conversion.
|
||||
|
||||
## Adding New SVGs
|
||||
|
||||
@@ -70,6 +79,18 @@ Then add the export to `src/icons/index.ts`:
|
||||
export { default as SvgMyIcon } from "@opal/icons/my-icon";
|
||||
```
|
||||
|
||||
### Logos
|
||||
|
||||
```sh
|
||||
# From web/lib/opal/
|
||||
./scripts/convert-svg.sh --logo src/logos/my-logo.svg
|
||||
```
|
||||
|
||||
Then add the export to `src/logos/index.ts`:
|
||||
```ts
|
||||
export { default as SvgMyLogo } from "@opal/logos/my-logo";
|
||||
```
|
||||
|
||||
### Illustrations
|
||||
|
||||
```sh
|
||||
@@ -91,7 +112,7 @@ If you prefer to run the SVGR command directly:
|
||||
bunx @svgr/cli <file>.svg --typescript --svgo-config '{"plugins":[{"name":"removeAttrs","params":{"attrs":["stroke","stroke-opacity","width","height"]}}]}' --template scripts/icon-template.js > <file>.tsx
|
||||
```
|
||||
|
||||
**For illustrations** (preserves colours):
|
||||
**For logos and illustrations** (preserves colours):
|
||||
```sh
|
||||
bunx @svgr/cli <file>.svg --typescript --svgo-config '{"plugins":[{"name":"removeAttrs","params":{"attrs":["width","height"]}}]}' --template scripts/icon-template.js > <file>.tsx
|
||||
```
|
||||
|
||||
@@ -4,30 +4,36 @@
|
||||
#
|
||||
# By default, converts to a colour-overridable icon (stroke colours stripped, replaced with currentColor).
|
||||
# With --illustration, converts to a fixed-colour illustration (all original colours preserved).
|
||||
# With --logo, converts to a fixed-colour logo (all original colours preserved, same as illustration).
|
||||
#
|
||||
# Usage (from the opal package root — web/lib/opal/):
|
||||
# ./scripts/convert-svg.sh src/icons/<filename.svg>
|
||||
# ./scripts/convert-svg.sh --illustration src/illustrations/<filename.svg>
|
||||
# ./scripts/convert-svg.sh --logo src/logos/<filename.svg>
|
||||
|
||||
ILLUSTRATION=false
|
||||
MODE="icon"
|
||||
|
||||
# Parse flags
|
||||
while [[ "$1" == --* ]]; do
|
||||
case "$1" in
|
||||
--illustration)
|
||||
ILLUSTRATION=true
|
||||
MODE="illustration"
|
||||
shift
|
||||
;;
|
||||
--logo)
|
||||
MODE="logo"
|
||||
shift
|
||||
;;
|
||||
*)
|
||||
echo "Unknown flag: $1" >&2
|
||||
echo "Usage: ./scripts/convert-svg.sh [--illustration] <filename.svg>" >&2
|
||||
echo "Usage: ./scripts/convert-svg.sh [--illustration | --logo] <filename.svg>" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
if [ -z "$1" ]; then
|
||||
echo "Usage: ./scripts/convert-svg.sh [--illustration] <filename.svg>" >&2
|
||||
echo "Usage: ./scripts/convert-svg.sh [--illustration | --logo] <filename.svg>" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -49,12 +55,12 @@ fi
|
||||
BASE_NAME="${SVG_FILE%.svg}"
|
||||
|
||||
# Build the SVGO config based on mode
|
||||
if [ "$ILLUSTRATION" = true ]; then
|
||||
# Illustrations: only strip width and height (preserve all colours)
|
||||
SVGO_CONFIG='{"plugins":[{"name":"removeAttrs","params":{"attrs":["width","height"]}}]}'
|
||||
else
|
||||
if [ "$MODE" = "icon" ]; then
|
||||
# Icons: strip stroke, stroke-opacity, width, and height
|
||||
SVGO_CONFIG='{"plugins":[{"name":"removeAttrs","params":{"attrs":["stroke","stroke-opacity","width","height"]}}]}'
|
||||
else
|
||||
# Illustrations and logos: only strip width and height (preserve all colours)
|
||||
SVGO_CONFIG='{"plugins":[{"name":"removeAttrs","params":{"attrs":["width","height"]}}]}'
|
||||
fi
|
||||
|
||||
# Resolve the template path relative to this script (not the caller's CWD)
|
||||
@@ -85,7 +91,7 @@ if [ $? -eq 0 ]; then
|
||||
fi
|
||||
|
||||
# Icons additionally get stroke="currentColor"
|
||||
if [ "$ILLUSTRATION" = false ]; then
|
||||
if [ "$MODE" = "icon" ]; then
|
||||
perl -i -pe 's/\{\.\.\.props\}/stroke="currentColor" {...props}/g' "${BASE_NAME}.tsx"
|
||||
if [ $? -ne 0 ]; then
|
||||
echo "Error: Failed to add stroke attribute" >&2
|
||||
@@ -106,7 +112,7 @@ if [ $? -eq 0 ]; then
|
||||
fi
|
||||
|
||||
# For icons, also verify stroke="currentColor" was added
|
||||
if [ "$ILLUSTRATION" = false ]; then
|
||||
if [ "$MODE" = "icon" ]; then
|
||||
if ! grep -q 'stroke="currentColor"' "${BASE_NAME}.tsx"; then
|
||||
echo "Error: Post-processing did not add stroke=\"currentColor\"" >&2
|
||||
exit 1
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
import type { IconProps } from "@opal/types";
|
||||
const SvgDiscordMono = ({ size, ...props }: IconProps) => (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 52 52"
|
||||
fill="currentColor"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
stroke="currentColor"
|
||||
{...props}
|
||||
>
|
||||
<path d="M32.7571 7.80005C32.288 8.63286 31.8668 9.4944 31.4839 10.3751C27.8463 9.82945 24.1417 9.82945 20.4946 10.3751C20.1213 9.4944 19.6905 8.63286 19.2214 7.80005C15.804 8.384 12.4727 9.40825 9.31379 10.8537C3.05329 20.1296 1.35894 29.1661 2.20134 38.0782C5.86763 40.7872 9.97429 42.8549 14.349 44.1759C15.3349 42.8549 16.2061 41.4477 16.9527 39.9831C15.536 39.4566 14.1671 38.7961 12.8556 38.0303C13.2002 37.7814 13.5353 37.523 13.8608 37.2741C21.5476 40.8925 30.4501 40.8925 38.1465 37.2741C38.4719 37.5421 38.807 37.8006 39.1516 38.0303C37.8401 38.8057 36.4713 39.4566 35.0449 39.9927C35.7916 41.4573 36.6627 42.8645 37.6487 44.1855C42.0233 42.8645 46.1299 40.8064 49.7965 38.0973C50.7918 27.7589 48.0924 18.799 42.6646 10.8633C39.5154 9.41784 36.1841 8.39355 32.7666 7.81919L32.7571 7.80005ZM18.0248 32.5931C15.6604 32.5931 13.698 30.4488 13.698 27.7972C13.698 25.1456 15.5838 22.9918 18.0153 22.9918C20.4468 22.9918 22.3804 25.1552 22.3421 27.7972C22.3038 30.4393 20.4372 32.5931 18.0248 32.5931ZM33.9728 32.5931C31.5988 32.5931 29.6556 30.4488 29.6556 27.7972C29.6556 25.1456 31.5414 22.9918 33.9728 22.9918C36.4043 22.9918 38.3284 25.1552 38.29 27.7972C38.2518 30.4393 36.3851 32.5931 33.9728 32.5931Z" />
|
||||
</svg>
|
||||
);
|
||||
export default SvgDiscordMono;
|
||||
19
web/lib/opal/src/icons/discord.tsx
Normal file
19
web/lib/opal/src/icons/discord.tsx
Normal file
@@ -0,0 +1,19 @@
|
||||
import type { IconProps } from "@opal/types";
|
||||
|
||||
const SvgDiscord = ({ size, ...props }: IconProps) => (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 16 16"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
stroke="currentColor"
|
||||
strokeWidth={1.5}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
{...props}
|
||||
>
|
||||
<path d="M5.5 12.5C5.5 12.5 4.88936 13.6396 4.60178 13.9974C3.32584 13.6396 2.12806 13.0796 1.05872 12.3459C0.813023 9.93224 1.30721 6.33924 3.13319 3.82703C4.05454 3.43555 5.00325 3.15815 6 3C6.1368 3.22555 6.39111 3.76148 6.5 4C7.56375 3.85223 8.43903 3.85223 9.5 4C9.61167 3.76148 9.86319 3.22555 10 3C10.9968 3.15556 11.942 3.43815 12.8605 3.82963C14.4436 5.97887 15.2309 9.55113 14.9406 12.3511C13.8712 13.0848 12.6735 13.6422 11.3975 14C11.11 13.6422 10.5 12.5 10.5 12.5M5.5 12.5C5.14663 12.3965 4.25 12 4.25 12M5.5 12.5C7.12611 12.9761 8.87249 12.9759 10.5 12.5M10.5 12.5C10.854 12.3965 11.75 12 11.75 12M5.66002 10C5.02612 10 4.5 9.44167 4.5 8.75125C4.5 8.06083 5.00558 7.5 5.65746 7.5C6.30934 7.5 6.82775 8.06331 6.81749 8.75125C6.80722 9.43918 6.30677 10 5.66002 10ZM10.3424 10C9.70591 10 9.18493 9.44167 9.18493 8.75125C9.18493 8.06083 9.69052 7.5 10.3424 7.5C10.9943 7.5 11.5101 8.06331 11.4998 8.75125C11.4896 9.43918 10.9891 10 10.3424 10Z" />
|
||||
</svg>
|
||||
);
|
||||
export default SvgDiscord;
|
||||
44
web/lib/opal/src/icons/icons.stories.tsx
Normal file
44
web/lib/opal/src/icons/icons.stories.tsx
Normal file
@@ -0,0 +1,44 @@
|
||||
import React from "react";
|
||||
import type { Meta, StoryObj } from "@storybook/react";
|
||||
import * as Icons from "@opal/icons";
|
||||
|
||||
const icons = Object.entries(Icons).map(([name, Component]) => ({
|
||||
name: name.replace(/^Svg/, ""),
|
||||
Component,
|
||||
}));
|
||||
|
||||
const meta: Meta = {
|
||||
title: "opal/icons/All Icons",
|
||||
tags: ["autodocs"],
|
||||
};
|
||||
|
||||
export default meta;
|
||||
type Story = StoryObj;
|
||||
|
||||
export const AllIcons: Story = {
|
||||
render: () => (
|
||||
<div
|
||||
style={{
|
||||
display: "grid",
|
||||
gridTemplateColumns: "repeat(auto-fill, 100px)",
|
||||
gap: 16,
|
||||
}}
|
||||
>
|
||||
{icons.map(({ name, Component }) => (
|
||||
<div
|
||||
key={name}
|
||||
style={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
gap: 8,
|
||||
padding: 8,
|
||||
}}
|
||||
>
|
||||
<Component size={24} />
|
||||
<span style={{ fontSize: 11, textAlign: "center" }}>{name}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
};
|
||||
@@ -19,12 +19,9 @@ export { default as SvgArrowUpRight } from "@opal/icons/arrow-up-right";
|
||||
export { default as SvgArrowWallRight } from "@opal/icons/arrow-wall-right";
|
||||
export { default as SvgAudio } from "@opal/icons/audio";
|
||||
export { default as SvgAudioEqSmall } from "@opal/icons/audio-eq-small";
|
||||
export { default as SvgAws } from "@opal/icons/aws";
|
||||
export { default as SvgAzure } from "@opal/icons/azure";
|
||||
export { default as SvgBarChart } from "@opal/icons/bar-chart";
|
||||
export { default as SvgBarChartSmall } from "@opal/icons/bar-chart-small";
|
||||
export { default as SvgBell } from "@opal/icons/bell";
|
||||
export { default as SvgBifrost } from "@opal/icons/bifrost";
|
||||
export { default as SvgBlocks } from "@opal/icons/blocks";
|
||||
export { default as SvgBookOpen } from "@opal/icons/book-open";
|
||||
export { default as SvgBookmark } from "@opal/icons/bookmark";
|
||||
@@ -45,7 +42,6 @@ export { default as SvgChevronRight } from "@opal/icons/chevron-right";
|
||||
export { default as SvgChevronUp } from "@opal/icons/chevron-up";
|
||||
export { default as SvgChevronUpSmall } from "@opal/icons/chevron-up-small";
|
||||
export { default as SvgCircle } from "@opal/icons/circle";
|
||||
export { default as SvgClaude } from "@opal/icons/claude";
|
||||
export { default as SvgClipboard } from "@opal/icons/clipboard";
|
||||
export { default as SvgClock } from "@opal/icons/clock";
|
||||
export { default as SvgClockHandsSmall } from "@opal/icons/clock-hands-small";
|
||||
@@ -59,8 +55,8 @@ export { default as SvgCurate } from "@opal/icons/curate";
|
||||
export { default as SvgCreditCard } from "@opal/icons/credit-card";
|
||||
export { default as SvgDashboard } from "@opal/icons/dashboard";
|
||||
export { default as SvgDevKit } from "@opal/icons/dev-kit";
|
||||
export { default as SvgDiscord } from "@opal/icons/discord";
|
||||
export { default as SvgDownload } from "@opal/icons/download";
|
||||
export { default as SvgDiscordMono } from "@opal/icons/DiscordMono";
|
||||
export { default as SvgDownloadCloud } from "@opal/icons/download-cloud";
|
||||
export { default as SvgEdit } from "@opal/icons/edit";
|
||||
export { default as SvgEditBig } from "@opal/icons/edit-big";
|
||||
@@ -84,7 +80,6 @@ export { default as SvgFolderIn } from "@opal/icons/folder-in";
|
||||
export { default as SvgFolderOpen } from "@opal/icons/folder-open";
|
||||
export { default as SvgFolderPartialOpen } from "@opal/icons/folder-partial-open";
|
||||
export { default as SvgFolderPlus } from "@opal/icons/folder-plus";
|
||||
export { default as SvgGemini } from "@opal/icons/gemini";
|
||||
export { default as SvgGlobe } from "@opal/icons/globe";
|
||||
export { default as SvgHandle } from "@opal/icons/handle";
|
||||
export { default as SvgHardDrive } from "@opal/icons/hard-drive";
|
||||
@@ -105,8 +100,6 @@ export { default as SvgLightbulbSimple } from "@opal/icons/lightbulb-simple";
|
||||
export { default as SvgLineChartUp } from "@opal/icons/line-chart-up";
|
||||
export { default as SvgLink } from "@opal/icons/link";
|
||||
export { default as SvgLinkedDots } from "@opal/icons/linked-dots";
|
||||
export { default as SvgLitellm } from "@opal/icons/litellm";
|
||||
export { default as SvgLmStudio } from "@opal/icons/lm-studio";
|
||||
export { default as SvgLoader } from "@opal/icons/loader";
|
||||
export { default as SvgLock } from "@opal/icons/lock";
|
||||
export { default as SvgLogOut } from "@opal/icons/log-out";
|
||||
@@ -122,13 +115,7 @@ export { default as SvgMoreHorizontal } from "@opal/icons/more-horizontal";
|
||||
export { default as SvgMusicSmall } from "@opal/icons/music-small";
|
||||
export { default as SvgNetworkGraph } from "@opal/icons/network-graph";
|
||||
export { default as SvgNotificationBubble } from "@opal/icons/notification-bubble";
|
||||
export { default as SvgOllama } from "@opal/icons/ollama";
|
||||
export { default as SvgOnyxLogo } from "@opal/icons/onyx-logo";
|
||||
export { default as SvgOnyxLogoTyped } from "@opal/icons/onyx-logo-typed";
|
||||
export { default as SvgOnyxOctagon } from "@opal/icons/onyx-octagon";
|
||||
export { default as SvgOnyxTyped } from "@opal/icons/onyx-typed";
|
||||
export { default as SvgOpenai } from "@opal/icons/openai";
|
||||
export { default as SvgOpenrouter } from "@opal/icons/openrouter";
|
||||
export { default as SvgOrganization } from "@opal/icons/organization";
|
||||
export { default as SvgPaintBrush } from "@opal/icons/paint-brush";
|
||||
export { default as SvgPaperclip } from "@opal/icons/paperclip";
|
||||
|
||||
@@ -8,63 +8,19 @@ const SvgSlack = ({ size, ...props }: IconProps) => (
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
stroke="currentColor"
|
||||
strokeWidth={1.5}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
{...props}
|
||||
>
|
||||
<g clipPath="url(#clip0_259_269)">
|
||||
<path
|
||||
d="M9.66666 6.66665C9.11333 6.66665 8.66666 6.21998 8.66666 5.66665V2.33331C8.66666 1.77998 9.11333 1.33331 9.66666 1.33331C10.22 1.33331 10.6667 1.77998 10.6667 2.33331V5.66665C10.6667 6.21998 10.22 6.66665 9.66666 6.66665Z"
|
||||
strokeWidth={1.5}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
<path
|
||||
d="M13.6667 6.66665H12.6667V5.66665C12.6667 5.11331 13.1133 4.66665 13.6667 4.66665C14.22 4.66665 14.6667 5.11331 14.6667 5.66665C14.6667 6.21998 14.22 6.66665 13.6667 6.66665Z"
|
||||
strokeWidth={1.5}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
<path
|
||||
d="M6.33333 9.33331C6.88666 9.33331 7.33333 9.77998 7.33333 10.3333V13.6666C7.33333 14.22 6.88666 14.6666 6.33333 14.6666C5.78 14.6666 5.33333 14.22 5.33333 13.6666V10.3333C5.33333 9.77998 5.78 9.33331 6.33333 9.33331Z"
|
||||
strokeWidth={1.5}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
<path
|
||||
d="M2.33333 9.33331H3.33333V10.3333C3.33333 10.8866 2.88666 11.3333 2.33333 11.3333C1.77999 11.3333 1.33333 10.8866 1.33333 10.3333C1.33333 9.77998 1.77999 9.33331 2.33333 9.33331Z"
|
||||
strokeWidth={1.5}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
<path
|
||||
d="M9.33333 9.66665C9.33333 9.11331 9.78 8.66665 10.3333 8.66665H13.6667C14.22 8.66665 14.6667 9.11331 14.6667 9.66665C14.6667 10.22 14.22 10.6666 13.6667 10.6666H10.3333C9.78 10.6666 9.33333 10.22 9.33333 9.66665Z"
|
||||
strokeWidth={1.5}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
<path
|
||||
d="M10.3333 12.6666H9.33333V13.6666C9.33333 14.22 9.78 14.6666 10.3333 14.6666C10.8867 14.6666 11.3333 14.22 11.3333 13.6666C11.3333 13.1133 10.8867 12.6666 10.3333 12.6666Z"
|
||||
strokeWidth={1.5}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
<path
|
||||
d="M6.66666 6.33331C6.66666 5.77998 6.22 5.33331 5.66666 5.33331H2.33333C1.77999 5.33331 1.33333 5.77998 1.33333 6.33331C1.33333 6.88665 1.77999 7.33331 2.33333 7.33331H5.66666C6.22 7.33331 6.66666 6.88665 6.66666 6.33331Z"
|
||||
strokeWidth={1.5}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
<path
|
||||
d="M5.66666 3.33331H6.66666V2.33331C6.66666 1.77998 6.22 1.33331 5.66666 1.33331C5.11333 1.33331 4.66666 1.77998 4.66666 2.33331C4.66666 2.88665 5.11333 3.33331 5.66666 3.33331Z"
|
||||
strokeWidth={1.5}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</g>
|
||||
<defs>
|
||||
<clipPath id="clip0_259_269">
|
||||
<rect width={16} height={16} fill="white" />
|
||||
</clipPath>
|
||||
</defs>
|
||||
<path d="M9.66668 6.66671C9.11334 6.66671 8.66668 6.22004 8.66668 5.66671V2.33337C8.66668 1.78004 9.11334 1.33337 9.66668 1.33337C10.22 1.33337 10.6667 1.78004 10.6667 2.33337V5.66671C10.6667 6.22004 10.22 6.66671 9.66668 6.66671Z" />
|
||||
<path d="M13.6667 6.66671H12.6667V5.66671C12.6667 5.11337 13.1133 4.66671 13.6667 4.66671C14.22 4.66671 14.6667 5.11337 14.6667 5.66671C14.6667 6.22004 14.22 6.66671 13.6667 6.66671Z" />
|
||||
<path d="M6.33334 9.33337C6.88668 9.33337 7.33334 9.78004 7.33334 10.3334V13.6667C7.33334 14.22 6.88668 14.6667 6.33334 14.6667C5.78001 14.6667 5.33334 14.22 5.33334 13.6667V10.3334C5.33334 9.78004 5.78001 9.33337 6.33334 9.33337Z" />
|
||||
<path d="M2.33334 9.33337H3.33334V10.3334C3.33334 10.8867 2.88668 11.3334 2.33334 11.3334C1.78001 11.3334 1.33334 10.8867 1.33334 10.3334C1.33334 9.78004 1.78001 9.33337 2.33334 9.33337Z" />
|
||||
<path d="M9.33334 9.66671C9.33334 9.11337 9.78001 8.66671 10.3333 8.66671H13.6667C14.22 8.66671 14.6667 9.11337 14.6667 9.66671C14.6667 10.22 14.22 10.6667 13.6667 10.6667H10.3333C9.78001 10.6667 9.33334 10.22 9.33334 9.66671Z" />
|
||||
<path d="M10.3333 12.6667H9.33334V13.6667C9.33334 14.22 9.78001 14.6667 10.3333 14.6667C10.8867 14.6667 11.3333 14.22 11.3333 13.6667C11.3333 13.1134 10.8867 12.6667 10.3333 12.6667Z" />
|
||||
<path d="M6.66668 6.33337C6.66668 5.78004 6.22001 5.33337 5.66668 5.33337H2.33334C1.78001 5.33337 1.33334 5.78004 1.33334 6.33337C1.33334 6.88671 1.78001 7.33337 2.33334 7.33337H5.66668C6.22001 7.33337 6.66668 6.88671 6.66668 6.33337Z" />
|
||||
<path d="M5.66668 3.33337H6.66668V2.33337C6.66668 1.78004 6.22001 1.33337 5.66668 1.33337C5.11334 1.33337 4.66668 1.78004 4.66668 2.33337C4.66668 2.88671 5.11334 3.33337 5.66668 3.33337Z" />
|
||||
</svg>
|
||||
);
|
||||
export default SvgSlack;
|
||||
|
||||
46
web/lib/opal/src/illustrations/illustrations.stories.tsx
Normal file
46
web/lib/opal/src/illustrations/illustrations.stories.tsx
Normal file
@@ -0,0 +1,46 @@
|
||||
import React from "react";
|
||||
import type { Meta, StoryObj } from "@storybook/react";
|
||||
import * as Illustrations from "@opal/illustrations";
|
||||
|
||||
const illustrations = Object.entries(Illustrations).map(
|
||||
([name, Component]) => ({
|
||||
name: name.replace(/^Svg/, ""),
|
||||
Component,
|
||||
})
|
||||
);
|
||||
|
||||
const meta: Meta = {
|
||||
title: "opal/illustrations/All Illustrations",
|
||||
tags: ["autodocs"],
|
||||
};
|
||||
|
||||
export default meta;
|
||||
type Story = StoryObj;
|
||||
|
||||
export const AllIllustrations: Story = {
|
||||
render: () => (
|
||||
<div
|
||||
style={{
|
||||
display: "grid",
|
||||
gridTemplateColumns: "repeat(auto-fill, 140px)",
|
||||
gap: 24,
|
||||
}}
|
||||
>
|
||||
{illustrations.map(({ name, Component }) => (
|
||||
<div
|
||||
key={name}
|
||||
style={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
gap: 8,
|
||||
padding: 8,
|
||||
}}
|
||||
>
|
||||
<Component size={80} />
|
||||
<span style={{ fontSize: 11, textAlign: "center" }}>{name}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
};
|
||||
17
web/lib/opal/src/logos/anthropic.tsx
Normal file
17
web/lib/opal/src/logos/anthropic.tsx
Normal file
@@ -0,0 +1,17 @@
|
||||
import type { IconProps } from "@opal/types";
|
||||
const SvgAnthropic = ({ size, ...props }: IconProps) => (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 52 52"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
{...props}
|
||||
>
|
||||
<path
|
||||
d="M36.1779 9.78003H29.1432L41.9653 42.2095H49L36.1779 9.78003ZM15.8221 9.78003L3 42.2095H10.1844L12.8286 35.4243H26.2495L28.8438 42.2095H36.0282L23.2061 9.78003H15.8221ZM15.1236 29.3874L19.5141 18.0121L23.9046 29.3874H15.1236Z"
|
||||
fill="currentColor"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
export default SvgAnthropic;
|
||||
17
web/lib/opal/src/logos/deepseek.tsx
Normal file
17
web/lib/opal/src/logos/deepseek.tsx
Normal file
@@ -0,0 +1,17 @@
|
||||
import type { IconProps } from "@opal/types";
|
||||
const SvgDeepseek = ({ size, ...props }: IconProps) => (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 52 52"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
{...props}
|
||||
>
|
||||
<path
|
||||
d="M50.4754 11.5882C49.9458 11.3287 49.7177 11.8233 49.408 12.0745C49.3021 12.1556 49.2125 12.2609 49.1228 12.3581C48.3487 13.1848 47.4443 13.728 46.2628 13.6631C44.5354 13.5657 43.0605 14.1089 41.7568 15.4302C41.4797 13.801 40.559 12.8281 39.1575 12.2041C38.4243 11.8799 37.6828 11.5556 37.1693 10.8504C36.8108 10.348 36.713 9.78867 36.5338 9.23745C36.4196 8.90517 36.3056 8.56462 35.9226 8.50786C35.507 8.44309 35.3441 8.79147 35.1811 9.08346C34.5292 10.275 34.2767 11.5882 34.301 12.9175C34.3581 15.9085 35.6211 18.2914 38.1307 19.9856C38.4159 20.1801 38.4892 20.3745 38.3996 20.6584C38.2285 21.242 38.0247 21.8093 37.8456 22.3929C37.7314 22.7659 37.5602 22.8469 37.1611 22.6846C35.784 22.1093 34.5943 21.2581 33.5432 20.2288C31.7587 18.5023 30.1454 16.5975 28.1328 15.106C27.6602 14.7574 27.1876 14.4333 26.6986 14.1251C24.6452 12.1313 26.9676 10.4938 27.5053 10.2994C28.0675 10.0968 27.7009 9.39954 25.8838 9.40782C24.0667 9.41582 22.4045 10.0238 20.286 10.8344C19.9764 10.956 19.6503 11.045 19.3163 11.118C17.3933 10.7533 15.397 10.6721 13.311 10.9073C9.38354 11.3449 6.24657 13.2012 3.94062 16.3705C1.17028 20.1801 0.518441 24.5084 1.31698 29.0233C2.15627 33.7812 4.58437 37.7206 8.31632 40.8008C12.1868 43.9943 16.6439 45.5587 21.7284 45.2588C24.8166 45.0806 28.2551 44.6672 32.1337 41.3845C33.1114 41.8708 34.1382 42.0652 35.8412 42.2111C37.1531 42.3327 38.4161 42.1463 39.3938 41.9438C40.9257 41.6195 40.8198 40.201 40.2657 39.9416C35.7761 37.8504 36.7619 38.7015 35.8657 38.0124C38.1471 35.3134 41.5858 32.5087 42.9302 23.4222C43.0361 22.7009 42.9465 22.2469 42.9302 21.6633C42.922 21.3068 43.0035 21.1691 43.411 21.1284C44.5354 20.9987 45.6272 20.6908 46.6295 20.1396C49.5385 18.5509 50.7117 15.9409 50.9888 12.8121C51.0296 12.3338 50.9807 11.8393 50.4754 11.5882ZM25.1262 39.747C20.775 36.3266 18.6647 35.1998 17.7928 35.2484C16.978 35.2971 17.1247 36.2292 17.3038 36.8372C17.4913 37.4369 17.7358 37.8504 18.0779 38.3772C18.3142 38.7258 18.4773 39.2444 17.8417 39.6336C16.4402 40.501 14.0038 39.3418 13.8897 39.2851C11.0542 37.6152 8.68303 35.4104 7.01255 32.3953C5.39919 29.4933 4.46222 26.3809 4.30733 23.0576C4.26659 22.2552 4.50288 21.9713 5.30142 21.8256C6.35253 21.631 7.43629 21.5904 8.4874 21.7444C12.9283 22.3929 16.709 24.3788 19.8786 27.5238C21.6875 29.315 23.0564 31.4551 24.4662 33.5463C25.9654 35.7671 27.5787 37.8828 29.6321 39.6174C30.3573 40.2253 30.9358 40.6872 31.4899 41.0278C29.8196 41.2142 27.0329 41.2548 25.1262 39.747ZM27.2121 26.3323C27.2121 25.9756 27.4973 25.692 27.856 25.692C27.9374 25.692 28.0108 25.708 28.076 25.7323C28.1656 25.7648 28.2471 25.8135 28.3123 25.8863C28.4264 25.9999 28.4915 26.1619 28.4915 26.3322C28.4915 26.6888 28.2064 26.9724 27.8479 26.9724C27.4895 26.9724 27.2121 26.6889 27.2121 26.3323ZM33.69 29.6556C33.2745 29.8259 32.8589 29.9716 32.4597 29.9879C31.8404 30.0203 31.1641 29.7689 30.7975 29.461C30.2271 28.9827 29.8197 28.7153 29.6486 27.8804C29.5752 27.5238 29.6159 26.9725 29.6812 26.6565C29.8278 25.9756 29.6649 25.538 29.1842 25.1407C28.793 24.8164 28.296 24.7273 27.75 24.7273C27.5463 24.7273 27.359 24.6381 27.2204 24.5652C26.9922 24.4517 26.8049 24.168 26.9841 23.8195C27.0411 23.7061 27.3183 23.4304 27.3835 23.3819C28.125 22.9603 28.9805 23.0981 29.7709 23.4142C30.5043 23.7141 31.0584 24.2654 31.8568 25.0434C32.6717 25.9836 32.8183 26.2432 33.2828 26.9482C33.6496 27.4995 33.9836 28.0668 34.2117 28.7153C34.3502 29.1207 34.1708 29.4529 33.69 29.6556Z"
|
||||
fill="#4D6BFE"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
export default SvgDeepseek;
|
||||
17
web/lib/opal/src/logos/discord.tsx
Normal file
17
web/lib/opal/src/logos/discord.tsx
Normal file
@@ -0,0 +1,17 @@
|
||||
import type { IconProps } from "@opal/types";
|
||||
const SvgDiscordMono = ({ size, ...props }: IconProps) => (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 52 52"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
{...props}
|
||||
>
|
||||
<path
|
||||
d="M32.7571 7.80005C32.288 8.63286 31.8668 9.4944 31.4839 10.3751C27.8463 9.82945 24.1417 9.82945 20.4946 10.3751C20.1213 9.4944 19.6905 8.63286 19.2214 7.80005C15.804 8.384 12.4727 9.40825 9.31379 10.8537C3.05329 20.1296 1.35894 29.1661 2.20134 38.0782C5.86763 40.7872 9.97429 42.8549 14.349 44.1759C15.3349 42.8549 16.2061 41.4477 16.9527 39.9831C15.536 39.4566 14.1671 38.7961 12.8556 38.0303C13.2002 37.7814 13.5353 37.523 13.8608 37.2741C21.5476 40.8925 30.4501 40.8925 38.1465 37.2741C38.4719 37.5421 38.807 37.8006 39.1516 38.0303C37.8401 38.8057 36.4713 39.4566 35.0449 39.9927C35.7916 41.4573 36.6627 42.8645 37.6487 44.1855C42.0233 42.8645 46.1299 40.8064 49.7965 38.0973C50.7918 27.7589 48.0924 18.799 42.6646 10.8633C39.5154 9.41784 36.1841 8.39355 32.7666 7.81919L32.7571 7.80005ZM18.0248 32.5931C15.6604 32.5931 13.698 30.4488 13.698 27.7972C13.698 25.1456 15.5838 22.9918 18.0153 22.9918C20.4468 22.9918 22.3804 25.1552 22.3421 27.7972C22.3038 30.4393 20.4372 32.5931 18.0248 32.5931ZM33.9728 32.5931C31.5988 32.5931 29.6556 30.4488 29.6556 27.7972C29.6556 25.1456 31.5414 22.9918 33.9728 22.9918C36.4043 22.9918 38.3284 25.1552 38.29 27.7972C38.2518 30.4393 36.3851 32.5931 33.9728 32.5931Z"
|
||||
fill="#5865F2"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
export default SvgDiscordMono;
|
||||
33
web/lib/opal/src/logos/google.tsx
Normal file
33
web/lib/opal/src/logos/google.tsx
Normal file
@@ -0,0 +1,33 @@
|
||||
import type { IconProps } from "@opal/types";
|
||||
const SvgGoogle = ({ size, ...props }: IconProps) => (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 52 52"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
{...props}
|
||||
>
|
||||
<path
|
||||
d="M26.4758 21.5474H48.9506C49.2333 23.1186 49.4 24.8471 49.4 26.5493C49.4 33.5757 47.0924 39.5382 42.3041 44.2244C38.0758 48.3709 32.7153 50 26.4758 50C19.4411 50 13.3274 47.1642 8.85118 42.6473C4.41266 38.1688 2.6 32.1174 2.6 26C2.6 19.8826 4.41266 13.8312 8.85118 9.35266C13.3274 4.83583 19.4411 2 26.4758 2C32.9333 2 38.3468 4.36633 42.4994 8.27151L35.6726 15.1286C33.0902 12.6396 29.9845 11.5201 26.4871 11.5201C20.2689 11.5201 14.9692 15.7628 13.0825 21.4432C12.6042 22.8835 12.3419 24.4084 12.3419 26.0015C12.3419 27.5946 12.6042 29.1195 13.0825 30.5598C14.9692 36.2402 20.2689 40.4829 26.4871 40.4829C29.6527 40.4829 32.3416 39.7368 34.4897 38.4527C37.0882 36.8883 38.8266 34.4622 39.3995 31.5747H26.4758V21.5474Z"
|
||||
fill="#4285F4"
|
||||
/>
|
||||
<path
|
||||
d="M26.4758 21.5474V31.5747H39.3995C38.8266 34.4622 37.0882 36.8883 34.4897 38.4527L34.49 38.4525L42.3041 44.2244C47.0924 39.5382 49.4 33.5757 49.4 26.5493C49.4 24.8471 49.2333 23.1186 48.9506 21.5474H26.4758Z"
|
||||
fill="#4285F4"
|
||||
/>
|
||||
<path
|
||||
d="M13.0825 30.5598C12.6042 29.1195 12.3419 27.5946 12.3419 26.0015C12.3419 24.4084 12.6042 22.8835 13.0825 21.4432L5.12352 15.2415C3.49286 18.5013 2.6 22.1138 2.6 26C2.6 29.8862 3.49286 33.4987 5.12352 36.7585L13.0825 30.5598Z"
|
||||
fill="#FBBC05"
|
||||
/>
|
||||
<path
|
||||
d="M26.4758 11.5201C29.9845 11.5201 33.0902 12.6396 35.6726 15.1286L42.4994 8.27151C38.3468 4.36633 32.9333 2 26.4758 2C19.4411 2 13.3274 4.83583 8.85118 9.35266C4.41266 13.8312 2.6 19.8826 2.6 26C2.6 22.1138 3.49286 18.5013 5.12352 15.2415L13.0825 21.4432C14.9692 15.7628 20.2689 11.5201 26.4871 11.5201H26.4758Z"
|
||||
fill="#EA4335"
|
||||
/>
|
||||
<path
|
||||
d="M13.0825 30.5598L5.12352 36.7585C6.87664 40.2742 9.47433 43.3014 12.6417 45.5624C16.5474 48.3504 21.3134 50 26.4758 50C32.7153 50 38.0758 48.3709 42.3041 44.2244L34.49 38.4525C32.3416 39.7368 29.6527 40.4829 26.4871 40.4829C20.2689 40.4829 14.9692 36.2402 13.0825 30.5598Z"
|
||||
fill="#34A853"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
export default SvgGoogle;
|
||||
21
web/lib/opal/src/logos/index.ts
Normal file
21
web/lib/opal/src/logos/index.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
export { default as SvgAnthropic } from "@opal/logos/anthropic";
|
||||
export { default as SvgAws } from "@opal/logos/aws";
|
||||
export { default as SvgAzure } from "@opal/logos/azure";
|
||||
export { default as SvgBifrost } from "@opal/logos/bifrost";
|
||||
export { default as SvgClaude } from "@opal/logos/claude";
|
||||
export { default as SvgDeepseek } from "@opal/logos/deepseek";
|
||||
export { default as SvgDiscord } from "@opal/logos/discord";
|
||||
export { default as SvgGemini } from "@opal/logos/gemini";
|
||||
export { default as SvgGoogle } from "@opal/logos/google";
|
||||
export { default as SvgLitellm } from "@opal/logos/litellm";
|
||||
export { default as SvgLmStudio } from "@opal/logos/lm-studio";
|
||||
export { default as SvgMicrosoft } from "@opal/logos/microsoft";
|
||||
export { default as SvgMistral } from "@opal/logos/mistral";
|
||||
export { default as SvgOllama } from "@opal/logos/ollama";
|
||||
export { default as SvgOnyxLogo } from "@opal/logos/onyx-logo";
|
||||
export { default as SvgOnyxLogoTyped } from "@opal/logos/onyx-logo-typed";
|
||||
export { default as SvgOnyxTyped } from "@opal/logos/onyx-typed";
|
||||
export { default as SvgOpenai } from "@opal/logos/openai";
|
||||
export { default as SvgOpenrouter } from "@opal/logos/openrouter";
|
||||
export { default as SvgQwen } from "@opal/logos/qwen";
|
||||
export { default as SvgSlack } from "@opal/logos/slack";
|
||||
44
web/lib/opal/src/logos/logos.stories.tsx
Normal file
44
web/lib/opal/src/logos/logos.stories.tsx
Normal file
@@ -0,0 +1,44 @@
|
||||
import React from "react";
|
||||
import type { Meta, StoryObj } from "@storybook/react";
|
||||
import * as Logos from "@opal/logos";
|
||||
|
||||
const logos = Object.entries(Logos).map(([name, Component]) => ({
|
||||
name: name.replace(/^Svg/, ""),
|
||||
Component,
|
||||
}));
|
||||
|
||||
const meta: Meta = {
|
||||
title: "opal/logos/All Logos",
|
||||
tags: ["autodocs"],
|
||||
};
|
||||
|
||||
export default meta;
|
||||
type Story = StoryObj;
|
||||
|
||||
export const AllLogos: Story = {
|
||||
render: () => (
|
||||
<div
|
||||
style={{
|
||||
display: "grid",
|
||||
gridTemplateColumns: "repeat(auto-fill, 120px)",
|
||||
gap: 16,
|
||||
}}
|
||||
>
|
||||
{logos.map(({ name, Component }) => (
|
||||
<div
|
||||
key={name}
|
||||
style={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
gap: 8,
|
||||
padding: 8,
|
||||
}}
|
||||
>
|
||||
<Component size={32} />
|
||||
<span style={{ fontSize: 11, textAlign: "center" }}>{name}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
};
|
||||
17
web/lib/opal/src/logos/microsoft.tsx
Normal file
17
web/lib/opal/src/logos/microsoft.tsx
Normal file
@@ -0,0 +1,17 @@
|
||||
import type { IconProps } from "@opal/types";
|
||||
const SvgMicrosoft = ({ size, ...props }: IconProps) => (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 52 52"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
{...props}
|
||||
>
|
||||
<path d="M5 5H25V25H5V5Z" fill="#F35325" />
|
||||
<path d="M27 5H47V25H27V5Z" fill="#81BC06" />
|
||||
<path d="M5 27H25V47H5V27Z" fill="#05A6F0" />
|
||||
<path d="M27 27H47V47H27V27Z" fill="#FFBA08" />
|
||||
</svg>
|
||||
);
|
||||
export default SvgMicrosoft;
|
||||
29
web/lib/opal/src/logos/mistral.tsx
Normal file
29
web/lib/opal/src/logos/mistral.tsx
Normal file
@@ -0,0 +1,29 @@
|
||||
import type { IconProps } from "@opal/types";
|
||||
const SvgMistral = ({ size, ...props }: IconProps) => (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 52 52"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
{...props}
|
||||
>
|
||||
<path d="M15.5004 8H8.50043V15H15.5004V8Z" fill="#FFD800" />
|
||||
<path d="M43.5004 8H36.5004L36.5001 15H43.5004V8Z" fill="#FFD800" />
|
||||
<path d="M22.5004 15H15.5004H8.50043V22H22.5004V15Z" fill="#FFAF00" />
|
||||
<path d="M43.5004 15H36.5001H29.4998V22H43.5004V15Z" fill="#FFAF00" />
|
||||
<path
|
||||
d="M43.5004 22H29.4998H22.5004H8.50043V29H15.5004H22.5004H29.4998H36.5001H43.5004V22Z"
|
||||
fill="#FF8205"
|
||||
/>
|
||||
<path d="M15.5004 29H8.50043L8.50021 36H15.5004V29Z" fill="#FA500F" />
|
||||
<path d="M29.4998 29H22.5004V36H29.4998V29Z" fill="#FA500F" />
|
||||
<path
|
||||
d="M43.5004 29H36.5001L36.5004 36H43.5002L43.5004 29Z"
|
||||
fill="#FA500F"
|
||||
/>
|
||||
<path d="M22.5004 36H15.5004H8.50021H1.5V43H22.5004V36Z" fill="#E10500" />
|
||||
<path d="M50.5 36H43.5002H36.5004H29.4998V43H50.5V36Z" fill="#E10500" />
|
||||
</svg>
|
||||
);
|
||||
export default SvgMistral;
|
||||
@@ -1,5 +1,5 @@
|
||||
import SvgOnyxLogo from "@opal/icons/onyx-logo";
|
||||
import SvgOnyxTyped from "@opal/icons/onyx-typed";
|
||||
import SvgOnyxLogo from "@opal/logos/onyx-logo";
|
||||
import SvgOnyxTyped from "@opal/logos/onyx-typed";
|
||||
import { cn } from "@opal/utils";
|
||||
|
||||
interface OnyxLogoTypedProps {
|
||||
36
web/lib/opal/src/logos/qwen.tsx
Normal file
36
web/lib/opal/src/logos/qwen.tsx
Normal file
@@ -0,0 +1,36 @@
|
||||
import type { IconProps } from "@opal/types";
|
||||
const SvgQwen = ({ size, ...props }: IconProps) => (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 52 52"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
{...props}
|
||||
>
|
||||
<path
|
||||
d="M27.3186 2.74182C28.176 4.24727 29.0291 5.75708 29.88 7.26908C29.9488 7.39001 30.0834 7.46804 30.2225 7.46763H42.3358C42.7155 7.46763 43.0384 7.70762 43.3089 8.18108L46.4812 13.7883C46.8958 14.5236 47.0049 14.8312 46.5336 15.6145C45.9663 16.5527 45.4143 17.4996 44.8754 18.4509L44.0747 19.8865C43.8434 20.3141 43.5882 20.4974 43.9874 21.0036L49.7735 31.1207C50.1488 31.7774 50.0157 32.1985 49.6797 32.8007C48.7263 34.5134 47.7554 36.213 46.767 37.9061C46.4201 38.4996 45.999 38.7243 45.2834 38.7134C43.5882 38.6785 41.8973 38.6916 40.2064 38.7483C40.1339 38.752 40.0655 38.7942 40.0297 38.8574C38.0788 42.314 36.1115 45.7613 34.1279 49.1992C33.7592 49.8385 33.2988 49.9912 32.5461 49.9934C30.3709 49.9999 28.1782 50.0021 25.9637 49.9977C25.5513 49.9966 25.1534 49.7647 24.9491 49.4065L22.0364 44.3381C22.0026 44.2718 21.9298 44.2288 21.8554 44.2312H10.689C10.0671 44.2967 9.48242 44.229 8.93261 44.0305L5.4352 37.9868C5.22833 37.629 5.22663 37.1681 5.43084 36.8087L8.06426 32.1832C8.13928 32.0524 8.13928 31.8842 8.06426 31.7534C6.10931 28.3688 4.17585 24.972 2.24979 21.5709C1.9007 20.8945 1.87234 20.4887 2.45706 19.4654C3.47159 17.6916 4.47958 15.92 5.4832 14.1505C5.7712 13.64 6.14647 13.4218 6.75737 13.4196C8.64024 13.4117 10.5231 13.411 12.406 13.4174C12.5011 13.4167 12.5927 13.3628 12.6395 13.28L18.8008 2.53205C18.9864 2.20711 19.3474 2.00139 19.7216 2.00003L25.3549 2C26.0989 1.99996 26.9346 2.06982 27.3186 2.74182ZM19.7172 3.68654L13.4642 14.6283C13.4041 14.7315 13.289 14.798 13.1696 14.7985H6.91664C6.79446 14.7985 6.76391 14.8531 6.82718 14.96L19.5034 37.1185C19.5579 37.2101 19.5317 37.2538 19.4292 37.2559L13.3311 37.2887C13.1528 37.2827 12.9781 37.384 12.8947 37.5418L10.0148 42.5817C9.91878 42.7519 9.96896 42.8392 10.1631 42.8392L22.6343 42.8567C22.7346 42.8567 22.8088 42.9003 22.8612 42.9897L25.9222 48.3439C26.0226 48.5206 26.1229 48.5228 26.2255 48.3439L37.1475 29.2312L38.8559 26.216C38.9007 26.1358 39.0205 26.1358 39.0653 26.216L42.1722 31.7359C42.2188 31.8186 42.3108 31.8718 42.4056 31.8712L48.4339 31.8276C48.4954 31.8281 48.5403 31.7503 48.5103 31.6967L42.1831 20.6C42.1376 20.5258 42.1376 20.4276 42.1831 20.3534L42.8224 19.2472L45.266 14.9338C45.3183 14.8443 45.2921 14.7985 45.1896 14.7985H19.8917C19.763 14.7985 19.7325 14.7418 19.7979 14.6305L22.9266 9.16508C22.9501 9.12783 22.9625 9.08472 22.9625 9.04071C22.9625 8.99671 22.9501 8.95359 22.9266 8.91635L19.9463 3.68872C19.898 3.60117 19.7672 3.60001 19.7172 3.68654ZM33.5564 21.1192C33.6549 21.1199 33.6803 21.1635 33.6283 21.2501L26.112 34.4501C26.1013 34.4696 26.0855 34.4858 26.0663 34.4969C26.0471 34.5081 26.0252 34.5138 26.0029 34.5134C25.9808 34.5133 25.9591 34.5074 25.94 34.4963C25.9208 34.4852 25.9049 34.4693 25.8939 34.4501L18.3601 21.2894C18.3165 21.2152 18.3383 21.176 18.4212 21.1716L33.5564 21.1192Z"
|
||||
fill="url(#paint0_linear_3448_616)"
|
||||
/>
|
||||
<path
|
||||
fillRule="evenodd"
|
||||
clipRule="evenodd"
|
||||
d="M19.7172 3.68654L13.4642 14.6283C13.4041 14.7315 13.289 14.798 13.1696 14.7985H6.91664C6.79446 14.7985 6.76391 14.8531 6.82718 14.96L19.5034 37.1185C19.5579 37.2101 19.5317 37.2538 19.4292 37.2559L13.3311 37.2887C13.1528 37.2827 12.9781 37.384 12.8947 37.5418L10.0148 42.5817C9.91878 42.7519 9.96896 42.8392 10.1631 42.8392L22.6343 42.8567C22.7346 42.8567 22.8088 42.9003 22.8612 42.9897L25.9222 48.3439C26.0226 48.5206 26.1229 48.5228 26.2255 48.3439L37.1475 29.2312L38.8559 26.216C38.9007 26.1358 39.0205 26.1358 39.0653 26.216L42.1722 31.7359C42.2188 31.8186 42.3108 31.8718 42.4056 31.8712L48.4339 31.8276C48.4954 31.8281 48.5403 31.7503 48.5103 31.6967L42.1831 20.6C42.1376 20.5258 42.1376 20.4276 42.1831 20.3534L42.8224 19.2472L45.266 14.9338C45.3183 14.8443 45.2921 14.7985 45.1896 14.7985H19.8917C19.763 14.7985 19.7325 14.7418 19.7979 14.6305L22.9266 9.16508C22.9501 9.12783 22.9625 9.08472 22.9625 9.04071C22.9625 8.99671 22.9501 8.95359 22.9266 8.91635L19.9463 3.68872C19.898 3.60117 19.7672 3.60001 19.7172 3.68654ZM33.5564 21.1192C33.5556 21.1192 33.5549 21.1192 33.5541 21.1192L18.4212 21.1716C18.3383 21.176 18.3165 21.2152 18.3601 21.2894L25.8939 34.4501C25.9049 34.4693 25.9208 34.4852 25.94 34.4963C25.9591 34.5074 25.9808 34.5133 26.0029 34.5134C26.0252 34.5138 26.0471 34.5081 26.0663 34.4969C26.0855 34.4858 26.1013 34.4696 26.112 34.4501L33.6283 21.2501C33.6803 21.1635 33.6549 21.1199 33.5564 21.1192Z"
|
||||
fill="white"
|
||||
/>
|
||||
<defs>
|
||||
<linearGradient
|
||||
id="paint0_linear_3448_616"
|
||||
x1={2}
|
||||
y1={1.99971}
|
||||
x2={4802}
|
||||
y2={1.99971}
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop stopColor="#6336E7" stopOpacity={0.84} />
|
||||
<stop offset={1} stopColor="#6F69F7" stopOpacity={0.84} />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
</svg>
|
||||
);
|
||||
export default SvgQwen;
|
||||
29
web/lib/opal/src/logos/slack.tsx
Normal file
29
web/lib/opal/src/logos/slack.tsx
Normal file
@@ -0,0 +1,29 @@
|
||||
import type { IconProps } from "@opal/types";
|
||||
const SvgSlack = ({ size, ...props }: IconProps) => (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 52 52"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
{...props}
|
||||
>
|
||||
<path
|
||||
d="M12.6977 32.0796C12.6977 34.7532 10.5386 36.914 7.86714 36.914C5.1957 36.914 3.0366 34.7532 3.0366 32.0796C3.0366 29.406 5.1957 27.2452 7.86714 27.2452H12.6977V32.0796ZM15.113 32.0796C15.113 29.406 17.2721 27.2452 19.9435 27.2452C22.615 27.2452 24.7741 29.406 24.7741 32.0796V44.1656C24.7741 46.8392 22.615 49 19.9435 49C17.2721 49 15.113 46.8392 15.113 44.1656V32.0796Z"
|
||||
fill="#E01E5A"
|
||||
/>
|
||||
<path
|
||||
d="M19.9435 12.6688C17.2721 12.6688 15.113 10.508 15.113 7.83439C15.113 5.16083 17.2721 3 19.9435 3C22.615 3 24.7741 5.16083 24.7741 7.83439V12.6688H19.9435ZM19.9435 15.1226C22.615 15.1226 24.7741 17.2834 24.7741 19.957C24.7741 22.6306 22.615 24.7914 19.9435 24.7914H7.83055C5.15911 24.7914 3 22.6306 3 19.957C3 17.2834 5.15911 15.1226 7.83055 15.1226H19.9435Z"
|
||||
fill="#36C5F0"
|
||||
/>
|
||||
<path
|
||||
d="M39.3023 19.957C39.3023 17.2834 41.4614 15.1226 44.1329 15.1226C46.8043 15.1226 48.9634 17.2834 48.9634 19.957C48.9634 22.6306 46.8043 24.7914 44.1329 24.7914H39.3023V19.957ZM36.887 19.957C36.887 22.6306 34.7279 24.7914 32.0565 24.7914C29.385 24.7914 27.2259 22.6306 27.2259 19.957V7.83439C27.2259 5.16083 29.385 3 32.0565 3C34.7279 3 36.887 5.16083 36.887 7.83439V19.957Z"
|
||||
fill="#2EB67D"
|
||||
/>
|
||||
<path
|
||||
d="M32.0565 39.3312C34.7279 39.3312 36.887 41.492 36.887 44.1656C36.887 46.8392 34.7279 49 32.0565 49C29.385 49 27.2259 46.8392 27.2259 44.1656V39.3312H32.0565ZM32.0565 36.914C29.385 36.914 27.2259 34.7532 27.2259 32.0796C27.2259 29.406 29.385 27.2452 32.0565 27.2452H44.1694C46.8409 27.2452 49 29.406 49 32.0796C49 34.7532 46.8409 36.914 44.1694 36.914H32.0565Z"
|
||||
fill="#ECB22E"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
export default SvgSlack;
|
||||
@@ -5,7 +5,7 @@ import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { SlackTokensForm } from "./SlackTokensForm";
|
||||
import * as SettingsLayouts from "@/layouts/settings-layouts";
|
||||
import { SvgSlack } from "@opal/icons";
|
||||
import { SvgSlack } from "@opal/logos";
|
||||
|
||||
export function NewSlackBotForm() {
|
||||
const [formValues] = useState({
|
||||
|
||||
@@ -5,7 +5,7 @@ import { SlackChannelConfigCreationForm } from "@/app/admin/bots/[bot-id]/channe
|
||||
import { ErrorCallout } from "@/components/ErrorCallout";
|
||||
import SimpleLoader from "@/refresh-components/loaders/SimpleLoader";
|
||||
import * as SettingsLayouts from "@/layouts/settings-layouts";
|
||||
import { SvgSlack } from "@opal/icons";
|
||||
import { SvgSlack } from "@opal/logos";
|
||||
import { useSlackChannelConfigs } from "@/app/admin/bots/[bot-id]/hooks";
|
||||
import { useDocumentSets } from "@/app/admin/documents/sets/hooks";
|
||||
import { useAgents } from "@/hooks/useAgents";
|
||||
|
||||
@@ -5,7 +5,7 @@ import { SlackChannelConfigCreationForm } from "@/app/admin/bots/[bot-id]/channe
|
||||
import { ErrorCallout } from "@/components/ErrorCallout";
|
||||
import SimpleLoader from "@/refresh-components/loaders/SimpleLoader";
|
||||
import * as SettingsLayouts from "@/layouts/settings-layouts";
|
||||
import { SvgSlack } from "@opal/icons";
|
||||
import { SvgSlack } from "@opal/logos";
|
||||
import { useDocumentSets } from "@/app/admin/documents/sets/hooks";
|
||||
import { useAgents } from "@/hooks/useAgents";
|
||||
import { useStandardAnswerCategories } from "@/app/ee/admin/standard-answer/hooks";
|
||||
|
||||
@@ -7,7 +7,7 @@ import SlackChannelConfigsTable from "./SlackChannelConfigsTable";
|
||||
import { useSlackBot, useSlackChannelConfigsByBot } from "./hooks";
|
||||
import { ExistingSlackBotForm } from "../SlackBotUpdateForm";
|
||||
import * as SettingsLayouts from "@/layouts/settings-layouts";
|
||||
import { SvgSlack } from "@opal/icons";
|
||||
import { SvgSlack } from "@opal/logos";
|
||||
import { getErrorMsg } from "@/lib/error";
|
||||
|
||||
function SlackBotEditContent({ botId }: { botId: string }) {
|
||||
|
||||
@@ -1,163 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { ArrayHelpers, FieldArray, FormikProps, useField } from "formik";
|
||||
import { ModelConfiguration } from "@/interfaces/llm";
|
||||
import { ManualErrorMessage, TextFormField } from "@/components/Field";
|
||||
import { useEffect, useState } from "react";
|
||||
import CreateButton from "@/refresh-components/buttons/CreateButton";
|
||||
import { Button } from "@opal/components";
|
||||
import { SvgX } from "@opal/icons";
|
||||
import Text from "@/refresh-components/texts/Text";
|
||||
|
||||
function ModelConfigurationRow({
|
||||
name,
|
||||
index,
|
||||
arrayHelpers,
|
||||
formikProps,
|
||||
setError,
|
||||
}: {
|
||||
name: string;
|
||||
index: number;
|
||||
arrayHelpers: ArrayHelpers;
|
||||
formikProps: FormikProps<{ model_configurations: ModelConfiguration[] }>;
|
||||
setError: (value: string | null) => void;
|
||||
}) {
|
||||
const [, input] = useField(`${name}[${index}]`);
|
||||
useEffect(() => {
|
||||
if (!input.touched) return;
|
||||
setError((input.error as { name: string } | undefined)?.name ?? null);
|
||||
}, [input.touched, input.error]);
|
||||
|
||||
return (
|
||||
<div key={index} className="flex flex-row w-full gap-4">
|
||||
<div
|
||||
className={`flex flex-[2] ${
|
||||
input.touched && input.error ? "border-2 border-error rounded-lg" : ""
|
||||
}`}
|
||||
>
|
||||
<TextFormField
|
||||
name={`${name}[${index}].name`}
|
||||
label=""
|
||||
placeholder={`model-name-${index + 1}`}
|
||||
removeLabel
|
||||
hideError
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-[1]">
|
||||
<TextFormField
|
||||
name={`${name}[${index}].max_input_tokens`}
|
||||
label=""
|
||||
placeholder="Default"
|
||||
removeLabel
|
||||
hideError
|
||||
type="number"
|
||||
min={1}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col justify-center">
|
||||
<Button
|
||||
disabled={formikProps.values.model_configurations.length <= 1}
|
||||
onClick={() => {
|
||||
if (formikProps.values.model_configurations.length > 1) {
|
||||
setError(null);
|
||||
arrayHelpers.remove(index);
|
||||
}
|
||||
}}
|
||||
icon={SvgX}
|
||||
prominence="secondary"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ModelConfigurationField({
|
||||
name,
|
||||
formikProps,
|
||||
}: {
|
||||
name: string;
|
||||
formikProps: FormikProps<{ model_configurations: ModelConfiguration[] }>;
|
||||
}) {
|
||||
const [errorMap, setErrorMap] = useState<{ [index: number]: string }>({});
|
||||
const [finalError, setFinalError] = useState<string | undefined>();
|
||||
|
||||
return (
|
||||
<div className="pb-5 flex flex-col w-full">
|
||||
<div className="flex flex-col">
|
||||
<Text as="p" mainUiAction>
|
||||
Model Configurations
|
||||
</Text>
|
||||
<Text as="p" secondaryBody text03>
|
||||
Add models and customize the number of input tokens that they accept.
|
||||
</Text>
|
||||
</div>
|
||||
<FieldArray
|
||||
name={name}
|
||||
render={(arrayHelpers: ArrayHelpers) => (
|
||||
<div className="flex flex-col">
|
||||
<div className="flex flex-col gap-4 py-4">
|
||||
<div className="flex">
|
||||
<Text as="p" secondaryBody className="flex flex-[2]">
|
||||
Model Name
|
||||
</Text>
|
||||
<Text as="p" secondaryBody className="flex flex-[1]">
|
||||
Max Input Tokens
|
||||
</Text>
|
||||
<div className="w-10" />
|
||||
</div>
|
||||
{formikProps.values.model_configurations.map((_, index) => (
|
||||
<ModelConfigurationRow
|
||||
key={index}
|
||||
name={name}
|
||||
formikProps={formikProps}
|
||||
arrayHelpers={arrayHelpers}
|
||||
index={index}
|
||||
setError={(message: string | null) => {
|
||||
const newErrors = { ...errorMap };
|
||||
if (message) {
|
||||
newErrors[index] = message;
|
||||
} else {
|
||||
delete newErrors[index];
|
||||
for (const key in newErrors) {
|
||||
const numKey = Number(key);
|
||||
if (numKey > index) {
|
||||
const errorValue = newErrors[key];
|
||||
if (errorValue !== undefined) {
|
||||
// Ensure the value is not undefined
|
||||
newErrors[numKey - 1] = errorValue;
|
||||
delete newErrors[numKey];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
setErrorMap(newErrors);
|
||||
setFinalError(
|
||||
Object.values(newErrors).filter((item) => item)[0]
|
||||
);
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
{finalError && (
|
||||
<ManualErrorMessage>{finalError}</ManualErrorMessage>
|
||||
)}
|
||||
<div className="mt-3">
|
||||
<CreateButton
|
||||
onClick={() => {
|
||||
arrayHelpers.push({
|
||||
name: "",
|
||||
is_visible: true,
|
||||
// Use null so Yup.number().nullable() accepts empty inputs
|
||||
max_input_tokens: null,
|
||||
});
|
||||
}}
|
||||
>
|
||||
Add New
|
||||
</CreateButton>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
18
web/src/app/admin/configuration/llm/ModelIcon.tsx
Normal file
18
web/src/app/admin/configuration/llm/ModelIcon.tsx
Normal file
@@ -0,0 +1,18 @@
|
||||
import { defaultTailwindCSS } from "@/components/icons/icons";
|
||||
import { getModelIcon } from "@/lib/llmConfig/providers";
|
||||
import { IconProps } from "@opal/types";
|
||||
|
||||
export interface ModelIconProps extends IconProps {
|
||||
provider: string;
|
||||
modelName?: string;
|
||||
}
|
||||
|
||||
export default function ModelIcon({
|
||||
provider,
|
||||
modelName,
|
||||
size = 16,
|
||||
className = defaultTailwindCSS,
|
||||
}: ModelIconProps) {
|
||||
const Icon = getModelIcon(provider, modelName);
|
||||
return <Icon size={size} className={className} />;
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
import { defaultTailwindCSS, IconProps } from "@/components/icons/icons";
|
||||
import { getProviderIcon } from "@/app/admin/configuration/llm/utils";
|
||||
|
||||
export interface ProviderIconProps extends IconProps {
|
||||
provider: string;
|
||||
modelName?: string;
|
||||
}
|
||||
|
||||
export const ProviderIcon = ({
|
||||
provider,
|
||||
modelName,
|
||||
size = 16,
|
||||
className = defaultTailwindCSS,
|
||||
}: ProviderIconProps) => {
|
||||
const Icon = getProviderIcon(provider, modelName);
|
||||
return <Icon size={size} className={className} />;
|
||||
};
|
||||
@@ -1,622 +0,0 @@
|
||||
import { JSX } from "react";
|
||||
import {
|
||||
AnthropicIcon,
|
||||
AmazonIcon,
|
||||
AzureIcon,
|
||||
CPUIcon,
|
||||
MicrosoftIconSVG,
|
||||
MistralIcon,
|
||||
MetaIcon,
|
||||
GeminiIcon,
|
||||
IconProps,
|
||||
DeepseekIcon,
|
||||
OpenAISVG,
|
||||
QwenIcon,
|
||||
OllamaIcon,
|
||||
LMStudioIcon,
|
||||
LiteLLMIcon,
|
||||
ZAIIcon,
|
||||
} from "@/components/icons/icons";
|
||||
import {
|
||||
OllamaModelResponse,
|
||||
OpenRouterModelResponse,
|
||||
BedrockModelResponse,
|
||||
LMStudioModelResponse,
|
||||
LiteLLMProxyModelResponse,
|
||||
BifrostModelResponse,
|
||||
ModelConfiguration,
|
||||
LLMProviderName,
|
||||
BedrockFetchParams,
|
||||
OllamaFetchParams,
|
||||
LMStudioFetchParams,
|
||||
OpenRouterFetchParams,
|
||||
LiteLLMProxyFetchParams,
|
||||
BifrostFetchParams,
|
||||
OpenAICompatibleFetchParams,
|
||||
OpenAICompatibleModelResponse,
|
||||
} from "@/interfaces/llm";
|
||||
import { SvgAws, SvgBifrost, SvgOpenrouter, SvgPlug } from "@opal/icons";
|
||||
|
||||
// Aggregator providers that host models from multiple vendors
|
||||
export const AGGREGATOR_PROVIDERS = new Set([
|
||||
"bedrock",
|
||||
"bedrock_converse",
|
||||
"openrouter",
|
||||
"ollama_chat",
|
||||
"lm_studio",
|
||||
"litellm_proxy",
|
||||
"bifrost",
|
||||
"openai_compatible",
|
||||
"vertex_ai",
|
||||
]);
|
||||
|
||||
export const getProviderIcon = (
|
||||
providerName: string,
|
||||
modelName?: string
|
||||
): (({ size, className }: IconProps) => JSX.Element) => {
|
||||
const iconMap: Record<
|
||||
string,
|
||||
({ size, className }: IconProps) => JSX.Element
|
||||
> = {
|
||||
amazon: AmazonIcon,
|
||||
phi: MicrosoftIconSVG,
|
||||
mistral: MistralIcon,
|
||||
ministral: MistralIcon,
|
||||
llama: MetaIcon,
|
||||
ollama_chat: OllamaIcon,
|
||||
ollama: OllamaIcon,
|
||||
lm_studio: LMStudioIcon,
|
||||
gemini: GeminiIcon,
|
||||
deepseek: DeepseekIcon,
|
||||
claude: AnthropicIcon,
|
||||
anthropic: AnthropicIcon,
|
||||
openai: OpenAISVG,
|
||||
// Azure OpenAI should display the Azure logo
|
||||
azure: AzureIcon,
|
||||
microsoft: MicrosoftIconSVG,
|
||||
meta: MetaIcon,
|
||||
google: GeminiIcon,
|
||||
qwen: QwenIcon,
|
||||
qwq: QwenIcon,
|
||||
zai: ZAIIcon,
|
||||
// Cloud providers - use AWS icon for Bedrock
|
||||
bedrock: SvgAws,
|
||||
bedrock_converse: SvgAws,
|
||||
openrouter: SvgOpenrouter,
|
||||
litellm_proxy: LiteLLMIcon,
|
||||
bifrost: SvgBifrost,
|
||||
openai_compatible: SvgPlug,
|
||||
vertex_ai: GeminiIcon,
|
||||
};
|
||||
|
||||
const lowerProviderName = providerName.toLowerCase();
|
||||
|
||||
// For aggregator providers (bedrock, openrouter, vertex_ai), prioritize showing
|
||||
// the vendor icon based on model name (e.g., show Claude icon for Bedrock Claude models)
|
||||
if (AGGREGATOR_PROVIDERS.has(lowerProviderName) && modelName) {
|
||||
const lowerModelName = modelName.toLowerCase();
|
||||
for (const [key, icon] of Object.entries(iconMap)) {
|
||||
if (lowerModelName.includes(key)) {
|
||||
return icon;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check if provider name directly matches an icon
|
||||
if (lowerProviderName in iconMap) {
|
||||
const icon = iconMap[lowerProviderName];
|
||||
if (icon) {
|
||||
return icon;
|
||||
}
|
||||
}
|
||||
|
||||
// For non-aggregator providers, check if model name contains any of the keys
|
||||
if (modelName) {
|
||||
const lowerModelName = modelName.toLowerCase();
|
||||
for (const [key, icon] of Object.entries(iconMap)) {
|
||||
if (lowerModelName.includes(key)) {
|
||||
return icon;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to CPU icon if no matches
|
||||
return CPUIcon;
|
||||
};
|
||||
|
||||
export const isAnthropic = (provider: string, modelName?: string) =>
|
||||
provider === LLMProviderName.ANTHROPIC ||
|
||||
!!modelName?.toLowerCase().includes("claude");
|
||||
|
||||
/**
|
||||
* Fetches Bedrock models directly without any form state dependencies.
|
||||
* Uses snake_case params to match API structure.
|
||||
*/
|
||||
export const fetchBedrockModels = async (
|
||||
params: BedrockFetchParams
|
||||
): Promise<{ models: ModelConfiguration[]; error?: string }> => {
|
||||
if (!params.aws_region_name) {
|
||||
return { models: [], error: "AWS region is required" };
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/admin/llm/bedrock/available-models", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
aws_region_name: params.aws_region_name,
|
||||
aws_access_key_id: params.aws_access_key_id,
|
||||
aws_secret_access_key: params.aws_secret_access_key,
|
||||
aws_bearer_token_bedrock: params.aws_bearer_token_bedrock,
|
||||
provider_name: params.provider_name,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
let errorMessage = "Failed to fetch models";
|
||||
try {
|
||||
const errorData = await response.json();
|
||||
errorMessage = errorData.detail || errorData.message || errorMessage;
|
||||
} catch {
|
||||
// ignore JSON parsing errors
|
||||
}
|
||||
return { models: [], error: errorMessage };
|
||||
}
|
||||
|
||||
const data: BedrockModelResponse[] = await response.json();
|
||||
const models: ModelConfiguration[] = data.map((modelData) => ({
|
||||
name: modelData.name,
|
||||
display_name: modelData.display_name,
|
||||
is_visible: false,
|
||||
max_input_tokens: modelData.max_input_tokens,
|
||||
supports_image_input: modelData.supports_image_input,
|
||||
supports_reasoning: false,
|
||||
}));
|
||||
|
||||
return { models };
|
||||
} catch (error) {
|
||||
const errorMessage =
|
||||
error instanceof Error ? error.message : "Unknown error";
|
||||
return { models: [], error: errorMessage };
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches Ollama models directly without any form state dependencies.
|
||||
* Uses snake_case params to match API structure.
|
||||
*/
|
||||
export const fetchOllamaModels = async (
|
||||
params: OllamaFetchParams
|
||||
): Promise<{ models: ModelConfiguration[]; error?: string }> => {
|
||||
const apiBase = params.api_base;
|
||||
if (!apiBase) {
|
||||
return { models: [], error: "API Base is required" };
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/admin/llm/ollama/available-models", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
api_base: apiBase,
|
||||
provider_name: params.provider_name,
|
||||
}),
|
||||
signal: params.signal,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
let errorMessage = "Failed to fetch models";
|
||||
try {
|
||||
const errorData = await response.json();
|
||||
errorMessage = errorData.detail || errorData.message || errorMessage;
|
||||
} catch {
|
||||
// ignore JSON parsing errors
|
||||
}
|
||||
return { models: [], error: errorMessage };
|
||||
}
|
||||
|
||||
const data: OllamaModelResponse[] = await response.json();
|
||||
const models: ModelConfiguration[] = data.map((modelData) => ({
|
||||
name: modelData.name,
|
||||
display_name: modelData.display_name,
|
||||
is_visible: true,
|
||||
max_input_tokens: modelData.max_input_tokens,
|
||||
supports_image_input: modelData.supports_image_input,
|
||||
supports_reasoning: false,
|
||||
}));
|
||||
|
||||
return { models };
|
||||
} catch (error) {
|
||||
const errorMessage =
|
||||
error instanceof Error ? error.message : "Unknown error";
|
||||
return { models: [], error: errorMessage };
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches OpenRouter models directly without any form state dependencies.
|
||||
* Uses snake_case params to match API structure.
|
||||
*/
|
||||
export const fetchOpenRouterModels = async (
|
||||
params: OpenRouterFetchParams
|
||||
): Promise<{ models: ModelConfiguration[]; error?: string }> => {
|
||||
const apiBase = params.api_base;
|
||||
const apiKey = params.api_key;
|
||||
if (!apiBase) {
|
||||
return { models: [], error: "API Base is required" };
|
||||
}
|
||||
if (!apiKey) {
|
||||
return { models: [], error: "API Key is required" };
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/admin/llm/openrouter/available-models", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
api_base: apiBase,
|
||||
api_key: apiKey,
|
||||
provider_name: params.provider_name,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
let errorMessage = "Failed to fetch models";
|
||||
try {
|
||||
const errorData = await response.json();
|
||||
errorMessage = errorData.detail || errorData.message || errorMessage;
|
||||
} catch (jsonError) {
|
||||
console.warn(
|
||||
"Failed to parse OpenRouter model fetch error response",
|
||||
jsonError
|
||||
);
|
||||
}
|
||||
return { models: [], error: errorMessage };
|
||||
}
|
||||
|
||||
const data: OpenRouterModelResponse[] = await response.json();
|
||||
const models: ModelConfiguration[] = data.map((modelData) => ({
|
||||
name: modelData.name,
|
||||
display_name: modelData.display_name,
|
||||
is_visible: true,
|
||||
max_input_tokens: modelData.max_input_tokens,
|
||||
supports_image_input: modelData.supports_image_input,
|
||||
supports_reasoning: false,
|
||||
}));
|
||||
|
||||
return { models };
|
||||
} catch (error) {
|
||||
const errorMessage =
|
||||
error instanceof Error ? error.message : "Unknown error";
|
||||
return { models: [], error: errorMessage };
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches LM Studio models directly without any form state dependencies.
|
||||
* Uses snake_case params to match API structure.
|
||||
*/
|
||||
export const fetchLMStudioModels = async (
|
||||
params: LMStudioFetchParams
|
||||
): Promise<{ models: ModelConfiguration[]; error?: string }> => {
|
||||
const apiBase = params.api_base;
|
||||
if (!apiBase) {
|
||||
return { models: [], error: "API Base is required" };
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/admin/llm/lm-studio/available-models", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
api_base: apiBase,
|
||||
api_key: params.api_key,
|
||||
api_key_changed: params.api_key_changed ?? false,
|
||||
provider_name: params.provider_name,
|
||||
}),
|
||||
signal: params.signal,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
let errorMessage = "Failed to fetch models";
|
||||
try {
|
||||
const errorData = await response.json();
|
||||
errorMessage = errorData.detail || errorData.message || errorMessage;
|
||||
} catch (jsonError) {
|
||||
console.warn(
|
||||
"Failed to parse LM Studio model fetch error response",
|
||||
jsonError
|
||||
);
|
||||
}
|
||||
return { models: [], error: errorMessage };
|
||||
}
|
||||
|
||||
const data: LMStudioModelResponse[] = await response.json();
|
||||
const models: ModelConfiguration[] = data.map((modelData) => ({
|
||||
name: modelData.name,
|
||||
display_name: modelData.display_name,
|
||||
is_visible: true,
|
||||
max_input_tokens: modelData.max_input_tokens,
|
||||
supports_image_input: modelData.supports_image_input,
|
||||
supports_reasoning: modelData.supports_reasoning,
|
||||
}));
|
||||
|
||||
return { models };
|
||||
} catch (error) {
|
||||
const errorMessage =
|
||||
error instanceof Error ? error.message : "Unknown error";
|
||||
return { models: [], error: errorMessage };
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches Bifrost models directly without any form state dependencies.
|
||||
* Uses snake_case params to match API structure.
|
||||
*/
|
||||
export const fetchBifrostModels = async (
|
||||
params: BifrostFetchParams
|
||||
): Promise<{ models: ModelConfiguration[]; error?: string }> => {
|
||||
const apiBase = params.api_base;
|
||||
if (!apiBase) {
|
||||
return { models: [], error: "API Base is required" };
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/admin/llm/bifrost/available-models", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
api_base: apiBase,
|
||||
api_key: params.api_key,
|
||||
provider_name: params.provider_name,
|
||||
}),
|
||||
signal: params.signal,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
let errorMessage = "Failed to fetch models";
|
||||
try {
|
||||
const errorData = await response.json();
|
||||
errorMessage = errorData.detail || errorData.message || errorMessage;
|
||||
} catch (jsonError) {
|
||||
console.warn(
|
||||
"Failed to parse Bifrost model fetch error response",
|
||||
jsonError
|
||||
);
|
||||
}
|
||||
return { models: [], error: errorMessage };
|
||||
}
|
||||
|
||||
const data: BifrostModelResponse[] = await response.json();
|
||||
const models: ModelConfiguration[] = data.map((modelData) => ({
|
||||
name: modelData.name,
|
||||
display_name: modelData.display_name,
|
||||
is_visible: true,
|
||||
max_input_tokens: modelData.max_input_tokens,
|
||||
supports_image_input: modelData.supports_image_input,
|
||||
supports_reasoning: modelData.supports_reasoning,
|
||||
}));
|
||||
|
||||
return { models };
|
||||
} catch (error) {
|
||||
const errorMessage =
|
||||
error instanceof Error ? error.message : "Unknown error";
|
||||
return { models: [], error: errorMessage };
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches models from a generic OpenAI-compatible server.
|
||||
* Uses snake_case params to match API structure.
|
||||
*/
|
||||
export const fetchOpenAICompatibleModels = async (
|
||||
params: OpenAICompatibleFetchParams
|
||||
): Promise<{ models: ModelConfiguration[]; error?: string }> => {
|
||||
const apiBase = params.api_base;
|
||||
if (!apiBase) {
|
||||
return { models: [], error: "API Base is required" };
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(
|
||||
"/api/admin/llm/openai-compatible/available-models",
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
api_base: apiBase,
|
||||
api_key: params.api_key,
|
||||
provider_name: params.provider_name,
|
||||
}),
|
||||
signal: params.signal,
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
let errorMessage = "Failed to fetch models";
|
||||
try {
|
||||
const errorData = await response.json();
|
||||
errorMessage = errorData.detail || errorData.message || errorMessage;
|
||||
} catch {
|
||||
// ignore JSON parsing errors
|
||||
}
|
||||
return { models: [], error: errorMessage };
|
||||
}
|
||||
|
||||
const data: OpenAICompatibleModelResponse[] = await response.json();
|
||||
const models: ModelConfiguration[] = data.map((modelData) => ({
|
||||
name: modelData.name,
|
||||
display_name: modelData.display_name,
|
||||
is_visible: true,
|
||||
max_input_tokens: modelData.max_input_tokens,
|
||||
supports_image_input: modelData.supports_image_input,
|
||||
supports_reasoning: modelData.supports_reasoning,
|
||||
}));
|
||||
|
||||
return { models };
|
||||
} catch (error) {
|
||||
const errorMessage =
|
||||
error instanceof Error ? error.message : "Unknown error";
|
||||
return { models: [], error: errorMessage };
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches LiteLLM Proxy models directly without any form state dependencies.
|
||||
* Uses snake_case params to match API structure.
|
||||
*/
|
||||
export const fetchLiteLLMProxyModels = async (
|
||||
params: LiteLLMProxyFetchParams
|
||||
): Promise<{ models: ModelConfiguration[]; error?: string }> => {
|
||||
const apiBase = params.api_base;
|
||||
const apiKey = params.api_key;
|
||||
if (!apiBase) {
|
||||
return { models: [], error: "API Base is required" };
|
||||
}
|
||||
if (!apiKey) {
|
||||
return { models: [], error: "API Key is required" };
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/admin/llm/litellm/available-models", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
api_base: apiBase,
|
||||
api_key: apiKey,
|
||||
provider_name: params.provider_name,
|
||||
}),
|
||||
signal: params.signal,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
let errorMessage = "Failed to fetch models";
|
||||
try {
|
||||
const errorData = await response.json();
|
||||
errorMessage = errorData.detail || errorData.message || errorMessage;
|
||||
} catch {
|
||||
// ignore JSON parsing errors
|
||||
}
|
||||
return { models: [], error: errorMessage };
|
||||
}
|
||||
|
||||
const data: LiteLLMProxyModelResponse[] = await response.json();
|
||||
const models: ModelConfiguration[] = data.map((modelData) => ({
|
||||
name: modelData.model_name,
|
||||
display_name: modelData.model_name,
|
||||
is_visible: true,
|
||||
max_input_tokens: null,
|
||||
supports_image_input: false,
|
||||
supports_reasoning: false,
|
||||
}));
|
||||
|
||||
return { models };
|
||||
} catch (error) {
|
||||
const errorMessage =
|
||||
error instanceof Error ? error.message : "Unknown error";
|
||||
return { models: [], error: errorMessage };
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches models for a provider. Accepts form values directly and maps them
|
||||
* to the expected fetch params format internally.
|
||||
*/
|
||||
export const fetchModels = async (
|
||||
providerName: string,
|
||||
formValues: {
|
||||
api_base?: string;
|
||||
api_key?: string;
|
||||
api_key_changed?: boolean;
|
||||
name?: string;
|
||||
custom_config?: Record<string, string>;
|
||||
model_configurations?: ModelConfiguration[];
|
||||
},
|
||||
signal?: AbortSignal
|
||||
) => {
|
||||
const customConfig = formValues.custom_config || {};
|
||||
|
||||
switch (providerName) {
|
||||
case LLMProviderName.BEDROCK:
|
||||
return fetchBedrockModels({
|
||||
aws_region_name: customConfig.AWS_REGION_NAME || "",
|
||||
aws_access_key_id: customConfig.AWS_ACCESS_KEY_ID,
|
||||
aws_secret_access_key: customConfig.AWS_SECRET_ACCESS_KEY,
|
||||
aws_bearer_token_bedrock: customConfig.AWS_BEARER_TOKEN_BEDROCK,
|
||||
provider_name: formValues.name,
|
||||
});
|
||||
case LLMProviderName.OLLAMA_CHAT:
|
||||
return fetchOllamaModels({
|
||||
api_base: formValues.api_base,
|
||||
provider_name: formValues.name,
|
||||
signal,
|
||||
});
|
||||
case LLMProviderName.LM_STUDIO:
|
||||
return fetchLMStudioModels({
|
||||
api_base: formValues.api_base,
|
||||
api_key: formValues.custom_config?.LM_STUDIO_API_KEY,
|
||||
api_key_changed: formValues.api_key_changed ?? false,
|
||||
provider_name: formValues.name,
|
||||
signal,
|
||||
});
|
||||
case LLMProviderName.OPENROUTER:
|
||||
return fetchOpenRouterModels({
|
||||
api_base: formValues.api_base,
|
||||
api_key: formValues.api_key,
|
||||
provider_name: formValues.name,
|
||||
});
|
||||
case LLMProviderName.LITELLM_PROXY:
|
||||
return fetchLiteLLMProxyModels({
|
||||
api_base: formValues.api_base,
|
||||
api_key: formValues.api_key,
|
||||
provider_name: formValues.name,
|
||||
signal,
|
||||
});
|
||||
case LLMProviderName.BIFROST:
|
||||
return fetchBifrostModels({
|
||||
api_base: formValues.api_base,
|
||||
api_key: formValues.api_key,
|
||||
provider_name: formValues.name,
|
||||
signal,
|
||||
});
|
||||
case LLMProviderName.OPENAI_COMPATIBLE:
|
||||
return fetchOpenAICompatibleModels({
|
||||
api_base: formValues.api_base,
|
||||
api_key: formValues.api_key,
|
||||
provider_name: formValues.name,
|
||||
signal,
|
||||
});
|
||||
default:
|
||||
return { models: [], error: `Unknown provider: ${providerName}` };
|
||||
}
|
||||
};
|
||||
|
||||
export function canProviderFetchModels(providerName?: string) {
|
||||
if (!providerName) return false;
|
||||
switch (providerName) {
|
||||
case LLMProviderName.BEDROCK:
|
||||
case LLMProviderName.OLLAMA_CHAT:
|
||||
case LLMProviderName.LM_STUDIO:
|
||||
case LLMProviderName.OPENROUTER:
|
||||
case LLMProviderName.LITELLM_PROXY:
|
||||
case LLMProviderName.BIFROST:
|
||||
case LLMProviderName.OPENAI_COMPATIBLE:
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,8 @@ import InputComboBox from "@/refresh-components/inputs/InputComboBox";
|
||||
import { FormField } from "@/refresh-components/form/FormField";
|
||||
import { Vertical, Horizontal } from "@/layouts/input-layouts";
|
||||
import { Section } from "@/layouts/general-layouts";
|
||||
import { SvgArrowExchange, SvgOnyxLogo } from "@opal/icons";
|
||||
import { SvgArrowExchange } from "@opal/icons";
|
||||
import { SvgOnyxLogo } from "@opal/logos";
|
||||
import { Disabled } from "@opal/core";
|
||||
import type { IconProps } from "@opal/types";
|
||||
import { VoiceProviderView } from "@/hooks/useVoiceProviders";
|
||||
@@ -401,7 +402,7 @@ export default function VoiceProviderSetupModal({
|
||||
options={existingApiKeyOptions}
|
||||
separatorLabel="Reuse OpenAI API Keys"
|
||||
strict={false}
|
||||
showAddPrefix
|
||||
createPrefix="Add"
|
||||
/>
|
||||
) : (
|
||||
<PasswordInputTypeIn
|
||||
|
||||
@@ -5,7 +5,7 @@ import { Button } from "@opal/components";
|
||||
import { Text } from "@opal/components";
|
||||
import { ContentAction } from "@opal/layouts";
|
||||
import { SvgEyeOff, SvgX } from "@opal/icons";
|
||||
import { getProviderIcon } from "@/app/admin/configuration/llm/utils";
|
||||
import { getModelIcon } from "@/lib/llmConfig/providers";
|
||||
import AgentMessage, {
|
||||
AgentMessageProps,
|
||||
} from "@/app/app/message/messageComponents/AgentMessage";
|
||||
@@ -71,7 +71,7 @@ export default function MultiModelPanel({
|
||||
errorStackTrace,
|
||||
errorDetails,
|
||||
}: MultiModelPanelProps) {
|
||||
const ProviderIcon = getProviderIcon(provider, modelName);
|
||||
const ModelIcon = getModelIcon(provider, modelName);
|
||||
|
||||
const handlePanelClick = useCallback(() => {
|
||||
if (!isHidden && !isPreferred) onSelect();
|
||||
@@ -88,7 +88,7 @@ export default function MultiModelPanel({
|
||||
sizePreset="main-ui"
|
||||
variant="body"
|
||||
paddingVariant="lg"
|
||||
icon={ProviderIcon}
|
||||
icon={ModelIcon}
|
||||
title={isHidden ? markdown(`~~${displayName}~~`) : displayName}
|
||||
rightChildren={
|
||||
<div className="flex items-center gap-1 px-2">
|
||||
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
isRecommendedModel,
|
||||
} from "@/app/craft/onboarding/constants";
|
||||
import { ToggleWarningModal } from "./ToggleWarningModal";
|
||||
import { getProviderIcon } from "@/app/admin/configuration/llm/utils";
|
||||
import { getModelIcon } from "@/lib/llmConfig/providers";
|
||||
import { Section } from "@/layouts/general-layouts";
|
||||
import {
|
||||
Accordion,
|
||||
@@ -365,9 +365,7 @@ export function BuildLLMPopover({
|
||||
const isExpanded = expandedGroups.includes(
|
||||
group.providerKey
|
||||
);
|
||||
const ProviderIcon = getProviderIcon(
|
||||
group.providerKey
|
||||
);
|
||||
const ModelIcon = getModelIcon(group.providerKey);
|
||||
|
||||
return (
|
||||
<AccordionItem
|
||||
@@ -379,7 +377,7 @@ export function BuildLLMPopover({
|
||||
<AccordionTrigger className="flex items-center rounded-08 hover:no-underline hover:bg-background-tint-02 group [&>svg]:hidden w-full py-1">
|
||||
<div className="flex items-center gap-1 shrink-0">
|
||||
<div className="flex items-center justify-center size-5 shrink-0">
|
||||
<ProviderIcon size={16} />
|
||||
<ModelIcon size={16} />
|
||||
</div>
|
||||
<Text
|
||||
secondaryBody
|
||||
|
||||
@@ -48,7 +48,7 @@ import NotAllowedModal from "@/app/craft/onboarding/components/NotAllowedModal";
|
||||
import { useOnboarding } from "@/app/craft/onboarding/BuildOnboardingProvider";
|
||||
import { useLLMProviders } from "@/hooks/useLLMProviders";
|
||||
import { useUser } from "@/providers/UserProvider";
|
||||
import { getProviderIcon } from "@/app/admin/configuration/llm/utils";
|
||||
import { getModelIcon } from "@/lib/llmConfig/providers";
|
||||
import {
|
||||
getBuildUserPersona,
|
||||
getPersonaInfo,
|
||||
@@ -475,10 +475,10 @@ export default function BuildConfigPage() {
|
||||
>
|
||||
{pendingLlmSelection?.provider &&
|
||||
(() => {
|
||||
const ProviderIcon = getProviderIcon(
|
||||
const ModelIcon = getModelIcon(
|
||||
pendingLlmSelection.provider
|
||||
);
|
||||
return <ProviderIcon className="w-4 h-4" />;
|
||||
return <ModelIcon className="w-4 h-4" />;
|
||||
})()}
|
||||
<Text mainUiAction>{pendingLlmDisplayName}</Text>
|
||||
<SvgChevronDown className="w-4 h-4 text-text-03" />
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* Tests logo icons to ensure they render correctly with proper accessibility
|
||||
* and support various display sizes.
|
||||
*/
|
||||
import { SvgBifrost } from "@opal/icons";
|
||||
import { SvgBifrost } from "@opal/logos";
|
||||
import { render } from "@tests/setup/test-utils";
|
||||
import { GithubIcon, GitbookIcon, ConfluenceIcon } from "./icons";
|
||||
|
||||
|
||||
@@ -3,14 +3,14 @@
|
||||
import { useMemo } from "react";
|
||||
import { parseLlmDescriptor, structureValue } from "@/lib/llmConfig/utils";
|
||||
import { DefaultModel, LLMProviderDescriptor } from "@/interfaces/llm";
|
||||
import { getProviderIcon } from "@/app/admin/configuration/llm/utils";
|
||||
import { getModelIcon } from "@/lib/llmConfig/providers";
|
||||
import InputSelect from "@/refresh-components/inputs/InputSelect";
|
||||
import { createIcon } from "@/components/icons/icons";
|
||||
|
||||
interface LLMOption {
|
||||
name: string;
|
||||
value: string;
|
||||
icon: ReturnType<typeof getProviderIcon>;
|
||||
icon: ReturnType<typeof getModelIcon>;
|
||||
modelName: string;
|
||||
providerName: string;
|
||||
provider: string;
|
||||
@@ -85,7 +85,7 @@ export default function LLMSelector({
|
||||
provider.provider,
|
||||
modelConfiguration.name
|
||||
),
|
||||
icon: getProviderIcon(provider.provider, modelConfiguration.name),
|
||||
icon: getModelIcon(provider.provider, modelConfiguration.name),
|
||||
modelName: modelConfiguration.name,
|
||||
providerName: provider.name,
|
||||
provider: provider.provider,
|
||||
|
||||
@@ -160,6 +160,35 @@ export function useWellKnownLLMProvider(providerName: LLMProviderName) {
|
||||
};
|
||||
}
|
||||
|
||||
export interface CustomProviderOption {
|
||||
value: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the list of LiteLLM provider names available for custom provider
|
||||
* configuration (i.e. providers that don't have a dedicated well-known modal).
|
||||
*
|
||||
* Hits `GET /api/admin/llm/custom-provider-names`.
|
||||
*/
|
||||
export function useCustomProviderNames() {
|
||||
const { data, error, isLoading } = useSWR<CustomProviderOption[]>(
|
||||
SWR_KEYS.customProviderNames,
|
||||
errorHandlingFetcher,
|
||||
{
|
||||
revalidateOnFocus: false,
|
||||
revalidateIfStale: false,
|
||||
dedupingInterval: 60000,
|
||||
}
|
||||
);
|
||||
|
||||
return {
|
||||
customProviderNames: data ?? null,
|
||||
isLoading,
|
||||
error,
|
||||
};
|
||||
}
|
||||
|
||||
export function useWellKnownLLMProviders() {
|
||||
const {
|
||||
data: wellKnownLLMProviders,
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
import type {
|
||||
OnboardingState,
|
||||
OnboardingActions,
|
||||
} from "@/interfaces/onboarding";
|
||||
import type { OnboardingActions } from "@/interfaces/onboarding";
|
||||
|
||||
export enum LLMProviderName {
|
||||
OPENAI = "openai",
|
||||
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
SvgBubbleText,
|
||||
SvgClipboard,
|
||||
SvgCpu,
|
||||
SvgDiscordMono,
|
||||
SvgDownload,
|
||||
SvgEmpty,
|
||||
SvgFileText,
|
||||
@@ -24,7 +23,6 @@ import {
|
||||
SvgPaintBrush,
|
||||
SvgProgressBars,
|
||||
SvgSearchMenu,
|
||||
SvgSlack,
|
||||
SvgTerminal,
|
||||
SvgThumbsUp,
|
||||
SvgUploadCloud,
|
||||
@@ -34,6 +32,8 @@ import {
|
||||
SvgUsers,
|
||||
SvgWallet,
|
||||
SvgZoomIn,
|
||||
SvgDiscord,
|
||||
SvgSlack,
|
||||
} from "@opal/icons";
|
||||
|
||||
export interface AdminRouteEntry {
|
||||
@@ -92,7 +92,7 @@ export const ADMIN_ROUTES = {
|
||||
},
|
||||
DISCORD_BOTS: {
|
||||
path: "/admin/discord-bot",
|
||||
icon: SvgDiscordMono,
|
||||
icon: SvgDiscord,
|
||||
title: "Discord Integration",
|
||||
sidebarLabel: "Discord Integration",
|
||||
},
|
||||
|
||||
@@ -32,7 +32,7 @@ import {
|
||||
PersonaLabel,
|
||||
} from "@/app/admin/agents/interfaces";
|
||||
import { DefaultModel, LLMProviderDescriptor } from "@/interfaces/llm";
|
||||
import { isAnthropic } from "@/app/admin/configuration/llm/utils";
|
||||
import { isAnthropic } from "@/lib/llmConfig/svc";
|
||||
import { getSourceMetadataForSources } from "./sources";
|
||||
import { AuthType, NEXT_PUBLIC_CLOUD_ENABLED } from "./constants";
|
||||
import { useUser } from "@/providers/UserProvider";
|
||||
|
||||
@@ -1,21 +1,37 @@
|
||||
import type { IconFunctionComponent } from "@opal/types";
|
||||
import { SvgCpu, SvgPlug, SvgServer } from "@opal/icons";
|
||||
import {
|
||||
SvgBifrost,
|
||||
SvgCpu,
|
||||
SvgOpenai,
|
||||
SvgClaude,
|
||||
SvgOllama,
|
||||
SvgAws,
|
||||
SvgOpenrouter,
|
||||
SvgPlug,
|
||||
SvgServer,
|
||||
SvgAzure,
|
||||
SvgGemini,
|
||||
SvgLitellm,
|
||||
SvgLmStudio,
|
||||
} from "@opal/icons";
|
||||
SvgMicrosoft,
|
||||
SvgMistral,
|
||||
SvgDeepseek,
|
||||
SvgQwen,
|
||||
SvgGoogle,
|
||||
} from "@opal/logos";
|
||||
import { ZAIIcon } from "@/components/icons/icons";
|
||||
import { LLMProviderName } from "@/interfaces/llm";
|
||||
|
||||
export const AGGREGATOR_PROVIDERS = new Set([
|
||||
LLMProviderName.BEDROCK,
|
||||
"bedrock_converse",
|
||||
LLMProviderName.OPENROUTER,
|
||||
LLMProviderName.OLLAMA_CHAT,
|
||||
LLMProviderName.LM_STUDIO,
|
||||
LLMProviderName.LITELLM_PROXY,
|
||||
LLMProviderName.BIFROST,
|
||||
LLMProviderName.OPENAI_COMPATIBLE,
|
||||
LLMProviderName.VERTEX_AI,
|
||||
]);
|
||||
|
||||
const PROVIDER_ICONS: Record<string, IconFunctionComponent> = {
|
||||
[LLMProviderName.OPENAI]: SvgOpenai,
|
||||
[LLMProviderName.ANTHROPIC]: SvgClaude,
|
||||
@@ -81,3 +97,80 @@ export function getProviderDisplayName(providerName: string): string {
|
||||
export function getProviderIcon(providerName: string): IconFunctionComponent {
|
||||
return PROVIDER_ICONS[providerName] ?? SvgCpu;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Model-aware icon resolver (legacy icon set)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const MODEL_ICON_MAP: Record<string, IconFunctionComponent> = {
|
||||
[LLMProviderName.OPENAI]: SvgOpenai,
|
||||
[LLMProviderName.ANTHROPIC]: SvgClaude,
|
||||
[LLMProviderName.OLLAMA_CHAT]: SvgOllama,
|
||||
[LLMProviderName.LM_STUDIO]: SvgLmStudio,
|
||||
[LLMProviderName.OPENROUTER]: SvgOpenrouter,
|
||||
[LLMProviderName.VERTEX_AI]: SvgGemini,
|
||||
[LLMProviderName.BEDROCK]: SvgAws,
|
||||
[LLMProviderName.LITELLM_PROXY]: SvgLitellm,
|
||||
[LLMProviderName.BIFROST]: SvgBifrost,
|
||||
[LLMProviderName.OPENAI_COMPATIBLE]: SvgPlug,
|
||||
|
||||
amazon: SvgAws,
|
||||
phi: SvgMicrosoft,
|
||||
mistral: SvgMistral,
|
||||
ministral: SvgMistral,
|
||||
llama: SvgCpu,
|
||||
ollama: SvgOllama,
|
||||
gemini: SvgGemini,
|
||||
deepseek: SvgDeepseek,
|
||||
claude: SvgClaude,
|
||||
azure: SvgAzure,
|
||||
microsoft: SvgMicrosoft,
|
||||
meta: SvgCpu,
|
||||
google: SvgGoogle,
|
||||
qwen: SvgQwen,
|
||||
qwq: SvgQwen,
|
||||
zai: ZAIIcon,
|
||||
bedrock_converse: SvgAws,
|
||||
};
|
||||
|
||||
/**
|
||||
* Model-aware icon resolver that checks both provider name and model name
|
||||
* to pick the most specific icon (e.g. Claude icon for a Bedrock Claude model).
|
||||
*/
|
||||
export const getModelIcon = (
|
||||
providerName: string,
|
||||
modelName?: string
|
||||
): IconFunctionComponent => {
|
||||
const lowerProviderName = providerName.toLowerCase();
|
||||
|
||||
// For aggregator providers, prioritise showing the vendor icon based on model name
|
||||
if (AGGREGATOR_PROVIDERS.has(lowerProviderName) && modelName) {
|
||||
const lowerModelName = modelName.toLowerCase();
|
||||
for (const [key, icon] of Object.entries(MODEL_ICON_MAP)) {
|
||||
if (lowerModelName.includes(key)) {
|
||||
return icon;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check if provider name directly matches an icon
|
||||
if (lowerProviderName in MODEL_ICON_MAP) {
|
||||
const icon = MODEL_ICON_MAP[lowerProviderName];
|
||||
if (icon) {
|
||||
return icon;
|
||||
}
|
||||
}
|
||||
|
||||
// For non-aggregator providers, check if model name contains any of the keys
|
||||
if (modelName) {
|
||||
const lowerModelName = modelName.toLowerCase();
|
||||
for (const [key, icon] of Object.entries(MODEL_ICON_MAP)) {
|
||||
if (lowerModelName.includes(key)) {
|
||||
return icon;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to CPU icon if no matches
|
||||
return SvgCpu;
|
||||
};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* LLM action functions for mutations.
|
||||
* LLM action functions for mutations and model fetching.
|
||||
*
|
||||
* These are async functions for one-off actions that don't need SWR caching.
|
||||
*
|
||||
@@ -7,12 +7,31 @@
|
||||
* - /api/admin/llm/test/default - Test the default LLM provider connection
|
||||
* - /api/admin/llm/default - Set the default LLM model
|
||||
* - /api/admin/llm/provider/{id} - Delete an LLM provider
|
||||
* - /api/admin/llm/{provider}/available-models - Fetch available models for a provider
|
||||
*/
|
||||
|
||||
import {
|
||||
LLM_ADMIN_URL,
|
||||
LLM_PROVIDERS_ADMIN_URL,
|
||||
} from "@/lib/llmConfig/constants";
|
||||
import {
|
||||
OllamaModelResponse,
|
||||
OpenRouterModelResponse,
|
||||
BedrockModelResponse,
|
||||
LMStudioModelResponse,
|
||||
LiteLLMProxyModelResponse,
|
||||
BifrostModelResponse,
|
||||
ModelConfiguration,
|
||||
LLMProviderName,
|
||||
BedrockFetchParams,
|
||||
OllamaFetchParams,
|
||||
LMStudioFetchParams,
|
||||
OpenRouterFetchParams,
|
||||
LiteLLMProxyFetchParams,
|
||||
BifrostFetchParams,
|
||||
OpenAICompatibleFetchParams,
|
||||
OpenAICompatibleModelResponse,
|
||||
} from "@/interfaces/llm";
|
||||
|
||||
/**
|
||||
* Test the default LLM provider.
|
||||
@@ -57,15 +76,522 @@ export async function setDefaultLlmModel(
|
||||
/**
|
||||
* Delete an LLM provider.
|
||||
* @param providerId - The provider ID to delete
|
||||
* @param force - Force delete even if this is the default provider
|
||||
* @throws Error with the detail message from the API on failure
|
||||
*/
|
||||
export async function deleteLlmProvider(providerId: number): Promise<void> {
|
||||
const response = await fetch(`${LLM_PROVIDERS_ADMIN_URL}/${providerId}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
export async function deleteLlmProvider(
|
||||
providerId: number,
|
||||
force = false
|
||||
): Promise<void> {
|
||||
const url = force
|
||||
? `${LLM_PROVIDERS_ADMIN_URL}/${providerId}?force=true`
|
||||
: `${LLM_PROVIDERS_ADMIN_URL}/${providerId}`;
|
||||
const response = await fetch(url, { method: "DELETE" });
|
||||
|
||||
if (!response.ok) {
|
||||
const errorMsg = (await response.json()).detail;
|
||||
throw new Error(errorMsg);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Aggregator providers & helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Aggregator providers that host models from multiple vendors. */
|
||||
export const AGGREGATOR_PROVIDERS = new Set([
|
||||
"bedrock",
|
||||
"bedrock_converse",
|
||||
"openrouter",
|
||||
"ollama_chat",
|
||||
"lm_studio",
|
||||
"litellm_proxy",
|
||||
"bifrost",
|
||||
"openai_compatible",
|
||||
"vertex_ai",
|
||||
]);
|
||||
|
||||
export const isAnthropic = (provider: string, modelName?: string) =>
|
||||
provider === LLMProviderName.ANTHROPIC ||
|
||||
!!modelName?.toLowerCase().includes("claude");
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Model fetching
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Fetches Bedrock models directly without any form state dependencies.
|
||||
* Uses snake_case params to match API structure.
|
||||
*/
|
||||
export const fetchBedrockModels = async (
|
||||
params: BedrockFetchParams
|
||||
): Promise<{ models: ModelConfiguration[]; error?: string }> => {
|
||||
if (!params.aws_region_name) {
|
||||
return { models: [], error: "AWS region is required" };
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/admin/llm/bedrock/available-models", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
aws_region_name: params.aws_region_name,
|
||||
aws_access_key_id: params.aws_access_key_id,
|
||||
aws_secret_access_key: params.aws_secret_access_key,
|
||||
aws_bearer_token_bedrock: params.aws_bearer_token_bedrock,
|
||||
provider_name: params.provider_name,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
let errorMessage = "Failed to fetch models";
|
||||
try {
|
||||
const errorData = await response.json();
|
||||
errorMessage = errorData.detail || errorData.message || errorMessage;
|
||||
} catch {
|
||||
// ignore JSON parsing errors
|
||||
}
|
||||
return { models: [], error: errorMessage };
|
||||
}
|
||||
|
||||
const data: BedrockModelResponse[] = await response.json();
|
||||
const models: ModelConfiguration[] = data.map((modelData) => ({
|
||||
name: modelData.name,
|
||||
display_name: modelData.display_name,
|
||||
is_visible: false,
|
||||
max_input_tokens: modelData.max_input_tokens,
|
||||
supports_image_input: modelData.supports_image_input,
|
||||
supports_reasoning: false,
|
||||
}));
|
||||
|
||||
return { models };
|
||||
} catch (error) {
|
||||
const errorMessage =
|
||||
error instanceof Error ? error.message : "Unknown error";
|
||||
return { models: [], error: errorMessage };
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches Ollama models directly without any form state dependencies.
|
||||
* Uses snake_case params to match API structure.
|
||||
*/
|
||||
export const fetchOllamaModels = async (
|
||||
params: OllamaFetchParams
|
||||
): Promise<{ models: ModelConfiguration[]; error?: string }> => {
|
||||
const apiBase = params.api_base;
|
||||
if (!apiBase) {
|
||||
return { models: [], error: "API Base is required" };
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/admin/llm/ollama/available-models", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
api_base: apiBase,
|
||||
provider_name: params.provider_name,
|
||||
}),
|
||||
signal: params.signal,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
let errorMessage = "Failed to fetch models";
|
||||
try {
|
||||
const errorData = await response.json();
|
||||
errorMessage = errorData.detail || errorData.message || errorMessage;
|
||||
} catch {
|
||||
// ignore JSON parsing errors
|
||||
}
|
||||
return { models: [], error: errorMessage };
|
||||
}
|
||||
|
||||
const data: OllamaModelResponse[] = await response.json();
|
||||
const models: ModelConfiguration[] = data.map((modelData) => ({
|
||||
name: modelData.name,
|
||||
display_name: modelData.display_name,
|
||||
is_visible: true,
|
||||
max_input_tokens: modelData.max_input_tokens,
|
||||
supports_image_input: modelData.supports_image_input,
|
||||
supports_reasoning: false,
|
||||
}));
|
||||
|
||||
return { models };
|
||||
} catch (error) {
|
||||
const errorMessage =
|
||||
error instanceof Error ? error.message : "Unknown error";
|
||||
return { models: [], error: errorMessage };
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches OpenRouter models directly without any form state dependencies.
|
||||
* Uses snake_case params to match API structure.
|
||||
*/
|
||||
export const fetchOpenRouterModels = async (
|
||||
params: OpenRouterFetchParams
|
||||
): Promise<{ models: ModelConfiguration[]; error?: string }> => {
|
||||
const apiBase = params.api_base;
|
||||
const apiKey = params.api_key;
|
||||
if (!apiBase) {
|
||||
return { models: [], error: "API Base is required" };
|
||||
}
|
||||
if (!apiKey) {
|
||||
return { models: [], error: "API Key is required" };
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/admin/llm/openrouter/available-models", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
api_base: apiBase,
|
||||
api_key: apiKey,
|
||||
provider_name: params.provider_name,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
let errorMessage = "Failed to fetch models";
|
||||
try {
|
||||
const errorData = await response.json();
|
||||
errorMessage = errorData.detail || errorData.message || errorMessage;
|
||||
} catch (jsonError) {
|
||||
console.warn(
|
||||
"Failed to parse OpenRouter model fetch error response",
|
||||
jsonError
|
||||
);
|
||||
}
|
||||
return { models: [], error: errorMessage };
|
||||
}
|
||||
|
||||
const data: OpenRouterModelResponse[] = await response.json();
|
||||
const models: ModelConfiguration[] = data.map((modelData) => ({
|
||||
name: modelData.name,
|
||||
display_name: modelData.display_name,
|
||||
is_visible: true,
|
||||
max_input_tokens: modelData.max_input_tokens,
|
||||
supports_image_input: modelData.supports_image_input,
|
||||
supports_reasoning: false,
|
||||
}));
|
||||
|
||||
return { models };
|
||||
} catch (error) {
|
||||
const errorMessage =
|
||||
error instanceof Error ? error.message : "Unknown error";
|
||||
return { models: [], error: errorMessage };
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches LM Studio models directly without any form state dependencies.
|
||||
* Uses snake_case params to match API structure.
|
||||
*/
|
||||
export const fetchLMStudioModels = async (
|
||||
params: LMStudioFetchParams
|
||||
): Promise<{ models: ModelConfiguration[]; error?: string }> => {
|
||||
const apiBase = params.api_base;
|
||||
if (!apiBase) {
|
||||
return { models: [], error: "API Base is required" };
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/admin/llm/lm-studio/available-models", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
api_base: apiBase,
|
||||
api_key: params.api_key,
|
||||
api_key_changed: params.api_key_changed ?? false,
|
||||
provider_name: params.provider_name,
|
||||
}),
|
||||
signal: params.signal,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
let errorMessage = "Failed to fetch models";
|
||||
try {
|
||||
const errorData = await response.json();
|
||||
errorMessage = errorData.detail || errorData.message || errorMessage;
|
||||
} catch (jsonError) {
|
||||
console.warn(
|
||||
"Failed to parse LM Studio model fetch error response",
|
||||
jsonError
|
||||
);
|
||||
}
|
||||
return { models: [], error: errorMessage };
|
||||
}
|
||||
|
||||
const data: LMStudioModelResponse[] = await response.json();
|
||||
const models: ModelConfiguration[] = data.map((modelData) => ({
|
||||
name: modelData.name,
|
||||
display_name: modelData.display_name,
|
||||
is_visible: true,
|
||||
max_input_tokens: modelData.max_input_tokens,
|
||||
supports_image_input: modelData.supports_image_input,
|
||||
supports_reasoning: modelData.supports_reasoning,
|
||||
}));
|
||||
|
||||
return { models };
|
||||
} catch (error) {
|
||||
const errorMessage =
|
||||
error instanceof Error ? error.message : "Unknown error";
|
||||
return { models: [], error: errorMessage };
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches Bifrost models directly without any form state dependencies.
|
||||
* Uses snake_case params to match API structure.
|
||||
*/
|
||||
export const fetchBifrostModels = async (
|
||||
params: BifrostFetchParams
|
||||
): Promise<{ models: ModelConfiguration[]; error?: string }> => {
|
||||
const apiBase = params.api_base;
|
||||
if (!apiBase) {
|
||||
return { models: [], error: "API Base is required" };
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/admin/llm/bifrost/available-models", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
api_base: apiBase,
|
||||
api_key: params.api_key,
|
||||
provider_name: params.provider_name,
|
||||
}),
|
||||
signal: params.signal,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
let errorMessage = "Failed to fetch models";
|
||||
try {
|
||||
const errorData = await response.json();
|
||||
errorMessage = errorData.detail || errorData.message || errorMessage;
|
||||
} catch (jsonError) {
|
||||
console.warn(
|
||||
"Failed to parse Bifrost model fetch error response",
|
||||
jsonError
|
||||
);
|
||||
}
|
||||
return { models: [], error: errorMessage };
|
||||
}
|
||||
|
||||
const data: BifrostModelResponse[] = await response.json();
|
||||
const models: ModelConfiguration[] = data.map((modelData) => ({
|
||||
name: modelData.name,
|
||||
display_name: modelData.display_name,
|
||||
is_visible: true,
|
||||
max_input_tokens: modelData.max_input_tokens,
|
||||
supports_image_input: modelData.supports_image_input,
|
||||
supports_reasoning: modelData.supports_reasoning,
|
||||
}));
|
||||
|
||||
return { models };
|
||||
} catch (error) {
|
||||
const errorMessage =
|
||||
error instanceof Error ? error.message : "Unknown error";
|
||||
return { models: [], error: errorMessage };
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches models from a generic OpenAI-compatible server.
|
||||
* Uses snake_case params to match API structure.
|
||||
*/
|
||||
export const fetchOpenAICompatibleModels = async (
|
||||
params: OpenAICompatibleFetchParams
|
||||
): Promise<{ models: ModelConfiguration[]; error?: string }> => {
|
||||
const apiBase = params.api_base;
|
||||
if (!apiBase) {
|
||||
return { models: [], error: "API Base is required" };
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(
|
||||
"/api/admin/llm/openai-compatible/available-models",
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
api_base: apiBase,
|
||||
api_key: params.api_key,
|
||||
provider_name: params.provider_name,
|
||||
}),
|
||||
signal: params.signal,
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
let errorMessage = "Failed to fetch models";
|
||||
try {
|
||||
const errorData = await response.json();
|
||||
errorMessage = errorData.detail || errorData.message || errorMessage;
|
||||
} catch {
|
||||
// ignore JSON parsing errors
|
||||
}
|
||||
return { models: [], error: errorMessage };
|
||||
}
|
||||
|
||||
const data: OpenAICompatibleModelResponse[] = await response.json();
|
||||
const models: ModelConfiguration[] = data.map((modelData) => ({
|
||||
name: modelData.name,
|
||||
display_name: modelData.display_name,
|
||||
is_visible: true,
|
||||
max_input_tokens: modelData.max_input_tokens,
|
||||
supports_image_input: modelData.supports_image_input,
|
||||
supports_reasoning: modelData.supports_reasoning,
|
||||
}));
|
||||
|
||||
return { models };
|
||||
} catch (error) {
|
||||
const errorMessage =
|
||||
error instanceof Error ? error.message : "Unknown error";
|
||||
return { models: [], error: errorMessage };
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches LiteLLM Proxy models directly without any form state dependencies.
|
||||
* Uses snake_case params to match API structure.
|
||||
*/
|
||||
export const fetchLiteLLMProxyModels = async (
|
||||
params: LiteLLMProxyFetchParams
|
||||
): Promise<{ models: ModelConfiguration[]; error?: string }> => {
|
||||
const apiBase = params.api_base;
|
||||
const apiKey = params.api_key;
|
||||
if (!apiBase) {
|
||||
return { models: [], error: "API Base is required" };
|
||||
}
|
||||
if (!apiKey) {
|
||||
return { models: [], error: "API Key is required" };
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/admin/llm/litellm/available-models", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
api_base: apiBase,
|
||||
api_key: apiKey,
|
||||
provider_name: params.provider_name,
|
||||
}),
|
||||
signal: params.signal,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
let errorMessage = "Failed to fetch models";
|
||||
try {
|
||||
const errorData = await response.json();
|
||||
errorMessage = errorData.detail || errorData.message || errorMessage;
|
||||
} catch {
|
||||
// ignore JSON parsing errors
|
||||
}
|
||||
return { models: [], error: errorMessage };
|
||||
}
|
||||
|
||||
const data: LiteLLMProxyModelResponse[] = await response.json();
|
||||
const models: ModelConfiguration[] = data.map((modelData) => ({
|
||||
name: modelData.model_name,
|
||||
display_name: modelData.model_name,
|
||||
is_visible: true,
|
||||
max_input_tokens: null,
|
||||
supports_image_input: false,
|
||||
supports_reasoning: false,
|
||||
}));
|
||||
|
||||
return { models };
|
||||
} catch (error) {
|
||||
const errorMessage =
|
||||
error instanceof Error ? error.message : "Unknown error";
|
||||
return { models: [], error: errorMessage };
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches models for a provider. Accepts form values directly and maps them
|
||||
* to the expected fetch params format internally.
|
||||
*/
|
||||
export const fetchModels = async (
|
||||
providerName: string,
|
||||
formValues: {
|
||||
api_base?: string;
|
||||
api_key?: string;
|
||||
api_key_changed?: boolean;
|
||||
name?: string;
|
||||
custom_config?: Record<string, string>;
|
||||
model_configurations?: ModelConfiguration[];
|
||||
},
|
||||
signal?: AbortSignal
|
||||
) => {
|
||||
const customConfig = formValues.custom_config || {};
|
||||
|
||||
switch (providerName) {
|
||||
case LLMProviderName.BEDROCK:
|
||||
return fetchBedrockModels({
|
||||
aws_region_name: customConfig.AWS_REGION_NAME || "",
|
||||
aws_access_key_id: customConfig.AWS_ACCESS_KEY_ID,
|
||||
aws_secret_access_key: customConfig.AWS_SECRET_ACCESS_KEY,
|
||||
aws_bearer_token_bedrock: customConfig.AWS_BEARER_TOKEN_BEDROCK,
|
||||
provider_name: formValues.name,
|
||||
});
|
||||
case LLMProviderName.OLLAMA_CHAT:
|
||||
return fetchOllamaModels({
|
||||
api_base: formValues.api_base,
|
||||
provider_name: formValues.name,
|
||||
signal,
|
||||
});
|
||||
case LLMProviderName.LM_STUDIO:
|
||||
return fetchLMStudioModels({
|
||||
api_base: formValues.api_base,
|
||||
api_key: formValues.custom_config?.LM_STUDIO_API_KEY,
|
||||
api_key_changed: formValues.api_key_changed ?? false,
|
||||
provider_name: formValues.name,
|
||||
signal,
|
||||
});
|
||||
case LLMProviderName.OPENROUTER:
|
||||
return fetchOpenRouterModels({
|
||||
api_base: formValues.api_base,
|
||||
api_key: formValues.api_key,
|
||||
provider_name: formValues.name,
|
||||
});
|
||||
case LLMProviderName.LITELLM_PROXY:
|
||||
return fetchLiteLLMProxyModels({
|
||||
api_base: formValues.api_base,
|
||||
api_key: formValues.api_key,
|
||||
provider_name: formValues.name,
|
||||
signal,
|
||||
});
|
||||
case LLMProviderName.BIFROST:
|
||||
return fetchBifrostModels({
|
||||
api_base: formValues.api_base,
|
||||
api_key: formValues.api_key,
|
||||
provider_name: formValues.name,
|
||||
signal,
|
||||
});
|
||||
case LLMProviderName.OPENAI_COMPATIBLE:
|
||||
return fetchOpenAICompatibleModels({
|
||||
api_base: formValues.api_base,
|
||||
api_key: formValues.api_key,
|
||||
provider_name: formValues.name,
|
||||
signal,
|
||||
});
|
||||
default:
|
||||
return { models: [], error: `Unknown provider: ${providerName}` };
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
import { LLMProviderResponse, VisionProvider } from "@/interfaces/llm";
|
||||
import { LLM_ADMIN_URL } from "@/lib/llmConfig/constants";
|
||||
|
||||
export async function fetchVisionProviders(): Promise<VisionProvider[]> {
|
||||
const response = await fetch(`${LLM_ADMIN_URL}/vision-providers`, {
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
`Failed to fetch vision providers: ${await response.text()}`
|
||||
);
|
||||
}
|
||||
const data = (await response.json()) as LLMProviderResponse<VisionProvider>;
|
||||
return data.providers;
|
||||
}
|
||||
|
||||
export async function setDefaultVisionProvider(
|
||||
providerId: number,
|
||||
visionModel: string
|
||||
): Promise<void> {
|
||||
const response = await fetch(`${LLM_ADMIN_URL}/default-vision`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
provider_id: providerId,
|
||||
model_name: visionModel,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorMsg = await response.text();
|
||||
throw new Error(errorMsg);
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,7 @@ export const SWR_KEYS = {
|
||||
`/api/llm/persona/${personaId}/providers`,
|
||||
adminLlmProviders: "/api/admin/llm/provider",
|
||||
llmProvidersWithImageGen: "/api/admin/llm/provider?include_image_gen=true",
|
||||
customProviderNames: "/api/admin/llm/custom-provider-names",
|
||||
wellKnownLlmProviders: "/api/admin/llm/built-in/options",
|
||||
wellKnownLlmProvider: (providerEndpoint: string) =>
|
||||
`/api/admin/llm/built-in/options/${providerEndpoint}`,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import React, { memo } from "react";
|
||||
import { SvgArrowExchange, SvgOnyxLogo } from "@opal/icons";
|
||||
import { SvgArrowExchange } from "@opal/icons";
|
||||
import { SvgOnyxLogo } from "@opal/logos";
|
||||
|
||||
type ConnectionProviderIconProps = {
|
||||
icon: React.ReactNode;
|
||||
|
||||
@@ -9,7 +9,7 @@ import { cn } from "@/lib/utils";
|
||||
import Text from "@/refresh-components/texts/Text";
|
||||
import Truncated from "@/refresh-components/texts/Truncated";
|
||||
import { useMemo } from "react";
|
||||
import { SvgOnyxLogo, SvgOnyxLogoTyped } from "@opal/icons";
|
||||
import { SvgOnyxLogo, SvgOnyxLogoTyped } from "@opal/logos";
|
||||
|
||||
export interface LogoProps {
|
||||
folded?: boolean;
|
||||
|
||||
@@ -129,8 +129,9 @@ const InputComboBox = ({
|
||||
leftSearchIcon = false,
|
||||
rightSection,
|
||||
separatorLabel = "Other options",
|
||||
showAddPrefix = false,
|
||||
createPrefix,
|
||||
showOtherOptions = false,
|
||||
dropdownMaxHeight,
|
||||
...rest
|
||||
}: WithoutStyles<InputComboBoxProps>) => {
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
@@ -446,7 +447,8 @@ const InputComboBox = ({
|
||||
inputValue={inputValue}
|
||||
allowCreate={!strict}
|
||||
showCreateOption={showCreateOption}
|
||||
showAddPrefix={showAddPrefix}
|
||||
createPrefix={createPrefix}
|
||||
dropdownMaxHeight={dropdownMaxHeight}
|
||||
/>
|
||||
</>
|
||||
|
||||
|
||||
@@ -27,8 +27,10 @@ interface ComboBoxDropdownProps {
|
||||
allowCreate: boolean;
|
||||
/** Whether to show create option (pre-computed by parent) */
|
||||
showCreateOption: boolean;
|
||||
/** Show "Add" prefix in create option */
|
||||
showAddPrefix: boolean;
|
||||
/** Prefix shown before the typed value in the create option (e.g., "Use", "Add") */
|
||||
createPrefix?: string;
|
||||
/** Max height of the dropdown in CSS units. Defaults to "15rem". */
|
||||
dropdownMaxHeight?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -60,7 +62,8 @@ export const ComboBoxDropdown = forwardRef<
|
||||
inputValue,
|
||||
allowCreate,
|
||||
showCreateOption,
|
||||
showAddPrefix,
|
||||
createPrefix,
|
||||
dropdownMaxHeight,
|
||||
},
|
||||
ref
|
||||
) => {
|
||||
@@ -104,12 +107,14 @@ export const ComboBoxDropdown = forwardRef<
|
||||
role="listbox"
|
||||
aria-label={placeholder}
|
||||
className={cn(
|
||||
"z-[10000] bg-background-neutral-00 border border-border-02 rounded-12 shadow-02 max-h-60 overflow-y-auto overflow-x-hidden p-1 pointer-events-auto touch-auto"
|
||||
"z-[10000] bg-background-neutral-00 border border-border-02 rounded-12 shadow-02 overflow-y-auto overflow-x-hidden p-1 pointer-events-auto touch-auto",
|
||||
!dropdownMaxHeight && "max-h-60"
|
||||
)}
|
||||
style={{
|
||||
...floatingStyles,
|
||||
// Ensure the dropdown can scroll independently
|
||||
overscrollBehavior: "contain",
|
||||
...(dropdownMaxHeight ? { maxHeight: dropdownMaxHeight } : {}),
|
||||
}}
|
||||
onWheel={(e) => {
|
||||
// Prevent event from bubbling to prevent any parent scroll blocking
|
||||
@@ -135,7 +140,7 @@ export const ComboBoxDropdown = forwardRef<
|
||||
inputValue={inputValue}
|
||||
allowCreate={allowCreate}
|
||||
showCreateOption={showCreateOption}
|
||||
showAddPrefix={showAddPrefix}
|
||||
createPrefix={createPrefix}
|
||||
/>
|
||||
</div>,
|
||||
document.body
|
||||
|
||||
@@ -24,8 +24,8 @@ interface OptionsListProps {
|
||||
allowCreate: boolean;
|
||||
/** Whether to show create option (pre-computed by parent) */
|
||||
showCreateOption: boolean;
|
||||
/** Show "Add" prefix in create option */
|
||||
showAddPrefix: boolean;
|
||||
/** Prefix shown before the typed value in the create option (e.g., "Use", "Add") */
|
||||
createPrefix?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -47,7 +47,7 @@ export const OptionsList: React.FC<OptionsListProps> = ({
|
||||
inputValue,
|
||||
allowCreate,
|
||||
showCreateOption,
|
||||
showAddPrefix,
|
||||
createPrefix,
|
||||
}) => {
|
||||
// Index offset for other options when create option is shown
|
||||
const indexOffset = showCreateOption ? 1 : 0;
|
||||
@@ -73,7 +73,7 @@ export const OptionsList: React.FC<OptionsListProps> = ({
|
||||
data-index={0}
|
||||
role="option"
|
||||
aria-selected={false}
|
||||
aria-label={`${showAddPrefix ? "Add" : "Create"} "${inputValue}"`}
|
||||
aria-label={`${createPrefix ?? "Create"} "${inputValue}"`}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onSelect({ value: inputValue, label: inputValue });
|
||||
@@ -88,18 +88,18 @@ export const OptionsList: React.FC<OptionsListProps> = ({
|
||||
"flex items-center justify-between rounded-08",
|
||||
highlightedIndex === 0 && "bg-background-tint-02",
|
||||
"hover:bg-background-tint-02",
|
||||
showAddPrefix ? "px-1.5 py-1.5" : "px-3 py-2"
|
||||
createPrefix ? "px-1.5 py-1.5" : "px-3 py-2"
|
||||
)}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
"font-main-ui-action truncate min-w-0",
|
||||
showAddPrefix ? "px-1" : ""
|
||||
createPrefix ? "px-1" : ""
|
||||
)}
|
||||
>
|
||||
{showAddPrefix ? (
|
||||
{createPrefix ? (
|
||||
<>
|
||||
<span className="text-text-03">Add</span>
|
||||
<span className="text-text-03">{createPrefix}</span>
|
||||
<span className="text-text-04">{` ${inputValue}`}</span>
|
||||
</>
|
||||
) : (
|
||||
@@ -109,7 +109,7 @@ export const OptionsList: React.FC<OptionsListProps> = ({
|
||||
<SvgPlus
|
||||
className={cn(
|
||||
"w-4 h-4 flex-shrink-0",
|
||||
showAddPrefix ? "text-text-04 mx-1" : "text-text-03 ml-2"
|
||||
createPrefix ? "text-text-04 mx-1" : "text-text-03 ml-2"
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -40,11 +40,13 @@ export interface InputComboBoxProps
|
||||
rightSection?: React.ReactNode;
|
||||
/** Label for the separator between matched and unmatched options */
|
||||
separatorLabel?: string;
|
||||
/** Show "Add" prefix in create option (e.g., "Add [value]") */
|
||||
showAddPrefix?: boolean;
|
||||
/** Prefix shown before the typed value in the create option (e.g., "Use", "Add"). When omitted, the raw value is shown without a prefix. */
|
||||
createPrefix?: string;
|
||||
/**
|
||||
* When true, keep non-matching options visible under a separator while searching.
|
||||
* Defaults to false so search results are strictly filtered.
|
||||
*/
|
||||
showOtherOptions?: boolean;
|
||||
/** Max height of the dropdown in CSS units. Defaults to "15rem". */
|
||||
dropdownMaxHeight?: string;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import React from "react";
|
||||
import type { IconProps } from "@opal/types";
|
||||
import type { IconProps, RichStr } from "@opal/types";
|
||||
import Text from "@/refresh-components/texts/Text";
|
||||
import { Button } from "@opal/components";
|
||||
import Modal from "@/refresh-components/Modal";
|
||||
@@ -9,8 +9,8 @@ import { useModalClose } from "../contexts/ModalContext";
|
||||
|
||||
export interface ConfirmationModalProps {
|
||||
icon: React.FunctionComponent<IconProps>;
|
||||
title: string;
|
||||
description?: string;
|
||||
title: string | RichStr;
|
||||
description?: string | RichStr;
|
||||
children?: React.ReactNode;
|
||||
|
||||
submit: React.ReactNode;
|
||||
|
||||
@@ -4,11 +4,9 @@ import { useState, useEffect, useCallback, useMemo, useRef } from "react";
|
||||
import Popover from "@/refresh-components/Popover";
|
||||
import { LlmDescriptor, LlmManager } from "@/lib/hooks";
|
||||
import { structureValue } from "@/lib/llmConfig/utils";
|
||||
import {
|
||||
getProviderIcon,
|
||||
AGGREGATOR_PROVIDERS,
|
||||
} from "@/app/admin/configuration/llm/utils";
|
||||
import { LLMProviderDescriptor } from "@/interfaces/llm";
|
||||
import { getModelIcon } from "@/lib/llmConfig/providers";
|
||||
import { AGGREGATOR_PROVIDERS } from "@/lib/llmConfig/svc";
|
||||
|
||||
import { Slider } from "@/components/ui/slider";
|
||||
import { useUser } from "@/providers/UserProvider";
|
||||
import Text from "@/refresh-components/texts/Text";
|
||||
@@ -55,7 +53,7 @@ export function groupLlmOptions(
|
||||
groups.set(groupKey, {
|
||||
displayName,
|
||||
options: [],
|
||||
Icon: getProviderIcon(provider),
|
||||
Icon: getModelIcon(provider),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -193,7 +191,7 @@ export default function LLMPopover({
|
||||
icon={
|
||||
foldable
|
||||
? SvgRefreshCw
|
||||
: getProviderIcon(
|
||||
: getModelIcon(
|
||||
llmManager.currentLlm.provider,
|
||||
llmManager.currentLlm.modelName
|
||||
)
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import { useState, useMemo, useRef } from "react";
|
||||
import Popover from "@/refresh-components/Popover";
|
||||
import { LlmManager } from "@/lib/hooks";
|
||||
import { getProviderIcon } from "@/app/admin/configuration/llm/utils";
|
||||
import { getModelIcon } from "@/lib/llmConfig/providers";
|
||||
import { Button, SelectButton, OpenButton } from "@opal/components";
|
||||
import { SvgPlusCircle, SvgX } from "@opal/icons";
|
||||
import { LLMOption } from "@/refresh-components/popovers/interfaces";
|
||||
@@ -152,7 +152,7 @@ export default function ModelSelector({
|
||||
)}
|
||||
<div className="flex items-center shrink-0">
|
||||
{selectedModels.map((model, index) => {
|
||||
const ProviderIcon = getProviderIcon(
|
||||
const ProviderIcon = getModelIcon(
|
||||
model.provider,
|
||||
model.modelName
|
||||
);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { createTableColumns } from "@opal/components";
|
||||
import { Content } from "@opal/layouts";
|
||||
import { SvgUser, SvgUserManage, SvgGlobe, SvgSlack } from "@opal/icons";
|
||||
import { SvgUser, SvgUserManage, SvgGlobe } from "@opal/icons";
|
||||
import { SvgSlack } from "@opal/logos";
|
||||
import type { IconFunctionComponent } from "@opal/types";
|
||||
import Text from "@/refresh-components/texts/Text";
|
||||
import { UserRole, UserStatus, USER_ROLE_LABELS } from "@/lib/types";
|
||||
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
unsetDefaultImageGenerationConfig,
|
||||
deleteImageGenerationConfig,
|
||||
} from "@/refresh-pages/admin/ImageGenerationPage/svc";
|
||||
import { ProviderIcon } from "@/app/admin/configuration/llm/ProviderIcon";
|
||||
import ModelIcon from "@/app/admin/configuration/llm/ModelIcon";
|
||||
import Message from "@/refresh-components/messages/Message";
|
||||
import ConfirmationModalLayout from "@/refresh-components/layouts/ConfirmationModalLayout";
|
||||
import InputSelect from "@/refresh-components/inputs/InputSelect";
|
||||
@@ -264,7 +264,7 @@ export default function ImageGenerationContent() {
|
||||
sizePreset="main-ui"
|
||||
variant="section"
|
||||
icon={() => (
|
||||
<ProviderIcon
|
||||
<ModelIcon
|
||||
provider={provider.provider_name}
|
||||
size={16}
|
||||
/>
|
||||
@@ -391,7 +391,7 @@ export default function ImageGenerationContent() {
|
||||
key={p.image_provider_id}
|
||||
value={p.image_provider_id}
|
||||
icon={() => (
|
||||
<ProviderIcon
|
||||
<ModelIcon
|
||||
provider={p.provider_name}
|
||||
size={16}
|
||||
/>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import React, { useState, useMemo, useEffect } from "react";
|
||||
import { Form, Formik, FormikProps } from "formik";
|
||||
import ProviderModal from "@/components/modals/ProviderModal";
|
||||
import { ProviderIcon } from "@/app/admin/configuration/llm/ProviderIcon";
|
||||
import ModelIcon from "@/app/admin/configuration/llm/ModelIcon";
|
||||
import ConnectionProviderIcon from "@/refresh-components/ConnectionProviderIcon";
|
||||
import {
|
||||
testImageGenerationApiKey,
|
||||
@@ -246,7 +246,7 @@ export function ImageGenFormWrapper<T extends FormValues>({
|
||||
|
||||
const icon = () => (
|
||||
<ConnectionProviderIcon
|
||||
icon={<ProviderIcon provider={imageProvider.provider_name} size={24} />}
|
||||
icon={<ModelIcon provider={imageProvider.provider_name} size={24} />}
|
||||
/>
|
||||
);
|
||||
|
||||
|
||||
@@ -8,8 +8,8 @@ import {
|
||||
useWellKnownLLMProviders,
|
||||
} from "@/hooks/useLLMProviders";
|
||||
import { ThreeDotsLoader } from "@/components/Loading";
|
||||
import { Content, Card } from "@opal/layouts";
|
||||
import { Button, SelectCard } from "@opal/components";
|
||||
import { Content, Card as CardLayout } from "@opal/layouts";
|
||||
import { Button, SelectCard, Text, Card } from "@opal/components";
|
||||
import { Hoverable } from "@opal/core";
|
||||
import { SvgArrowExchange, SvgSettings, SvgTrash } from "@opal/icons";
|
||||
import * as SettingsLayouts from "@/layouts/settings-layouts";
|
||||
@@ -22,9 +22,7 @@ import {
|
||||
} from "@/lib/llmConfig/providers";
|
||||
import { refreshLlmProviderCaches } from "@/lib/llmConfig/cache";
|
||||
import { deleteLlmProvider, setDefaultLlmModel } from "@/lib/llmConfig/svc";
|
||||
import Text from "@/refresh-components/texts/Text";
|
||||
import { Horizontal as HorizontalInput } from "@/layouts/input-layouts";
|
||||
import LegacyCard from "@/refresh-components/cards/Card";
|
||||
import InputSelect from "@/refresh-components/inputs/InputSelect";
|
||||
import Message from "@/refresh-components/messages/Message";
|
||||
import ConfirmationModalLayout from "@/refresh-components/layouts/ConfirmationModalLayout";
|
||||
@@ -49,6 +47,7 @@ import LiteLLMProxyModal from "@/sections/modals/llmConfig/LiteLLMProxyModal";
|
||||
import BifrostModal from "@/sections/modals/llmConfig/BifrostModal";
|
||||
import OpenAICompatibleModal from "@/sections/modals/llmConfig/OpenAICompatibleModal";
|
||||
import { Section } from "@/layouts/general-layouts";
|
||||
import { markdown } from "@opal/utils";
|
||||
|
||||
const route = ADMIN_ROUTES.LLM_MODELS;
|
||||
|
||||
@@ -141,7 +140,7 @@ function ExistingProviderCard({
|
||||
|
||||
const handleDelete = async () => {
|
||||
try {
|
||||
await deleteLlmProvider(provider.id);
|
||||
await deleteLlmProvider(provider.id, isLastProvider);
|
||||
await refreshLlmProviderCaches(mutate);
|
||||
deleteModal.toggle(false);
|
||||
toast.success("Provider deleted successfully!");
|
||||
@@ -156,24 +155,37 @@ function ExistingProviderCard({
|
||||
{deleteModal.isOpen && (
|
||||
<ConfirmationModalLayout
|
||||
icon={SvgTrash}
|
||||
title={`Delete ${provider.name}`}
|
||||
title={markdown(`Delete *${provider.name}*`)}
|
||||
onClose={() => deleteModal.toggle(false)}
|
||||
submit={
|
||||
<Button variant="danger" onClick={handleDelete}>
|
||||
<Button
|
||||
variant="danger"
|
||||
onClick={handleDelete}
|
||||
disabled={isDefault && !isLastProvider}
|
||||
>
|
||||
Delete
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<Section alignItems="start" gap={0.5}>
|
||||
<Text text03>
|
||||
All LLM models from provider <b>{provider.name}</b> will be
|
||||
removed and unavailable for future chats. Chat history will be
|
||||
preserved.
|
||||
</Text>
|
||||
{isLastProvider && (
|
||||
<Text text03>
|
||||
Connect another provider to continue using chats.
|
||||
{isDefault && !isLastProvider ? (
|
||||
<Text font="main-ui-body" color="text-03">
|
||||
Cannot delete the default provider. Select another provider as
|
||||
the default prior to deleting this one.
|
||||
</Text>
|
||||
) : (
|
||||
<>
|
||||
<Text font="main-ui-body" color="text-03">
|
||||
{markdown(
|
||||
`All LLM models from provider **${provider.name}** will be removed and unavailable for future chats. Chat history will be preserved.`
|
||||
)}
|
||||
</Text>
|
||||
{isLastProvider && (
|
||||
<Text font="main-ui-body" color="text-03">
|
||||
Connect another provider to continue using chats.
|
||||
</Text>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</Section>
|
||||
</ConfirmationModalLayout>
|
||||
@@ -189,7 +201,7 @@ function ExistingProviderCard({
|
||||
rounding="lg"
|
||||
onClick={() => setIsOpen(true)}
|
||||
>
|
||||
<Card.Header
|
||||
<CardLayout.Header
|
||||
icon={getProviderIcon(provider.provider)}
|
||||
title={provider.name}
|
||||
description={getProviderDisplayName(provider.provider)}
|
||||
@@ -259,7 +271,7 @@ function NewProviderCard({
|
||||
rounding="lg"
|
||||
onClick={() => setIsOpen(true)}
|
||||
>
|
||||
<Card.Header
|
||||
<CardLayout.Header
|
||||
icon={getProviderIcon(provider.name)}
|
||||
title={getProviderProductName(provider.name)}
|
||||
description={getProviderDisplayName(provider.name)}
|
||||
@@ -303,7 +315,7 @@ function NewCustomProviderCard({
|
||||
rounding="lg"
|
||||
onClick={() => setIsOpen(true)}
|
||||
>
|
||||
<Card.Header
|
||||
<CardLayout.Header
|
||||
icon={getProviderIcon("custom")}
|
||||
title={getProviderProductName("custom")}
|
||||
description={getProviderDisplayName("custom")}
|
||||
@@ -392,7 +404,7 @@ export default function LLMProviderConfigurationPage() {
|
||||
|
||||
<SettingsLayouts.Body>
|
||||
{hasProviders ? (
|
||||
<LegacyCard>
|
||||
<Card border="solid" rounding="lg">
|
||||
<HorizontalInput
|
||||
title="Default Model"
|
||||
description="This model will be used by Onyx by default in your chats."
|
||||
@@ -423,7 +435,7 @@ export default function LLMProviderConfigurationPage() {
|
||||
</InputSelect.Content>
|
||||
</InputSelect>
|
||||
</HorizontalInput>
|
||||
</LegacyCard>
|
||||
</Card>
|
||||
) : (
|
||||
<Message
|
||||
info
|
||||
|
||||
@@ -1,13 +1,8 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import {
|
||||
SvgCheck,
|
||||
SvgSlack,
|
||||
SvgUser,
|
||||
SvgUserManage,
|
||||
SvgUsers,
|
||||
} from "@opal/icons";
|
||||
import { SvgCheck, SvgUser, SvgUserManage, SvgUsers } from "@opal/icons";
|
||||
import { SvgSlack } from "@opal/logos";
|
||||
import type { IconFunctionComponent } from "@opal/types";
|
||||
import { FilterButton } from "@opal/components";
|
||||
import Popover from "@/refresh-components/Popover";
|
||||
|
||||
@@ -5,13 +5,8 @@ import { UserRole, USER_ROLE_LABELS } from "@/lib/types";
|
||||
import { usePaidEnterpriseFeaturesEnabled } from "@/components/settings/usePaidEnterpriseFeaturesEnabled";
|
||||
import { OpenButton } from "@opal/components";
|
||||
import { Disabled } from "@opal/core";
|
||||
import {
|
||||
SvgCheck,
|
||||
SvgGlobe,
|
||||
SvgUser,
|
||||
SvgSlack,
|
||||
SvgUserManage,
|
||||
} from "@opal/icons";
|
||||
import { SvgCheck, SvgGlobe, SvgUser, SvgUserManage } from "@opal/icons";
|
||||
import { SvgSlack } from "@opal/logos";
|
||||
import type { IconFunctionComponent } from "@opal/types";
|
||||
import Text from "@/refresh-components/texts/Text";
|
||||
import Popover from "@/refresh-components/Popover";
|
||||
|
||||
@@ -8,7 +8,8 @@ import PasswordInputTypeIn from "@/refresh-components/inputs/PasswordInputTypeIn
|
||||
import Modal from "@/refresh-components/Modal";
|
||||
import { Button } from "@opal/components";
|
||||
|
||||
import { SvgArrowExchange, SvgOnyxLogo } from "@opal/icons";
|
||||
import { SvgArrowExchange } from "@opal/icons";
|
||||
import { SvgOnyxLogo } from "@opal/logos";
|
||||
import type { IconProps } from "@opal/types";
|
||||
|
||||
export type WebProviderSetupModalProps = {
|
||||
|
||||
@@ -19,11 +19,11 @@ import {
|
||||
SvgArrowRightCircle,
|
||||
SvgCheckSquare,
|
||||
SvgGlobe,
|
||||
SvgOnyxLogo,
|
||||
SvgSettings,
|
||||
SvgSlash,
|
||||
SvgUnplug,
|
||||
} from "@opal/icons";
|
||||
import { SvgOnyxLogo } from "@opal/logos";
|
||||
import { Button, SelectCard } from "@opal/components";
|
||||
import { Hoverable } from "@opal/core";
|
||||
import { ADMIN_ROUTES } from "@/lib/admin-routes";
|
||||
|
||||
@@ -27,14 +27,13 @@ import {
|
||||
ModelAccessField,
|
||||
ModalWrapper,
|
||||
} from "@/sections/modals/llmConfig/shared";
|
||||
import { fetchBedrockModels } from "@/app/admin/configuration/llm/utils";
|
||||
import { fetchBedrockModels } from "@/lib/llmConfig/svc";
|
||||
import { Card } from "@opal/components";
|
||||
import { Section } from "@/layouts/general-layouts";
|
||||
import { SvgAlertCircle } from "@opal/icons";
|
||||
import { Content } from "@opal/layouts";
|
||||
import { toast } from "@/hooks/useToast";
|
||||
import { refreshLlmProviderCaches } from "@/lib/llmConfig/cache";
|
||||
import useOnMount from "@/hooks/useOnMount";
|
||||
|
||||
const AWS_REGION_OPTIONS = [
|
||||
{ name: "us-east-1", value: "us-east-1" },
|
||||
@@ -123,17 +122,6 @@ function BedrockModalInternals({
|
||||
formikProps.setFieldValue("model_configurations", models);
|
||||
};
|
||||
|
||||
// Auto-fetch models on initial load when editing an existing provider
|
||||
useOnMount(() => {
|
||||
if (existingLlmProvider && !isFetchDisabled) {
|
||||
handleFetchModels().catch((err) => {
|
||||
toast.error(
|
||||
err instanceof Error ? err.message : "Failed to fetch models"
|
||||
);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<InputLayouts.FieldPadder>
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect } from "react";
|
||||
import { markdown } from "@opal/utils";
|
||||
import { useSWRConfig } from "swr";
|
||||
import { useFormikContext } from "formik";
|
||||
@@ -10,7 +9,7 @@ import {
|
||||
LLMProviderName,
|
||||
LLMProviderView,
|
||||
} from "@/interfaces/llm";
|
||||
import { fetchBifrostModels } from "@/app/admin/configuration/llm/utils";
|
||||
import { fetchBifrostModels } from "@/lib/llmConfig/svc";
|
||||
import {
|
||||
useInitialValues,
|
||||
buildValidationSchema,
|
||||
@@ -59,19 +58,6 @@ function BifrostModalInternals({
|
||||
formikProps.setFieldValue("model_configurations", models);
|
||||
};
|
||||
|
||||
// Auto-fetch models on initial load when editing an existing provider
|
||||
useEffect(() => {
|
||||
if (existingLlmProvider && !isFetchDisabled) {
|
||||
handleFetchModels().catch((err) => {
|
||||
console.error("Failed to fetch Bifrost models:", err);
|
||||
toast.error(
|
||||
err instanceof Error ? err.message : "Failed to fetch models"
|
||||
);
|
||||
});
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
<APIBaseField
|
||||
|
||||
@@ -6,18 +6,32 @@
|
||||
*/
|
||||
|
||||
import { render, screen, setupUser, waitFor } from "@tests/setup/test-utils";
|
||||
import { PointerEventsCheckLevel } from "@testing-library/user-event";
|
||||
import CustomModal from "@/sections/modals/llmConfig/CustomModal";
|
||||
import { toast } from "@/hooks/useToast";
|
||||
import { SWR_KEYS } from "@/lib/swr-keys";
|
||||
|
||||
// Mock SWR's mutate function and useSWR
|
||||
const mockMutate = jest.fn();
|
||||
const MOCK_CUSTOM_PROVIDER_OPTIONS = [
|
||||
{ value: "anthropic", label: "Anthropic" },
|
||||
{ value: "cloudflare", label: "Cloudflare" },
|
||||
{ value: "openai", label: "OpenAI" },
|
||||
];
|
||||
jest.mock("swr", () => {
|
||||
const actual = jest.requireActual("swr");
|
||||
return {
|
||||
...actual,
|
||||
useSWRConfig: () => ({ mutate: mockMutate }),
|
||||
__esModule: true,
|
||||
default: () => ({ data: undefined, error: undefined, isLoading: false }),
|
||||
default: (key: string | null) => ({
|
||||
data:
|
||||
key === SWR_KEYS.customProviderNames
|
||||
? MOCK_CUSTOM_PROVIDER_OPTIONS
|
||||
: undefined,
|
||||
error: undefined,
|
||||
isLoading: false,
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
@@ -70,12 +84,15 @@ describe("Custom LLM Provider Configuration Workflow", () => {
|
||||
}
|
||||
) {
|
||||
const nameInput = screen.getByPlaceholderText("Display Name");
|
||||
const providerInput = screen.getByPlaceholderText(
|
||||
"Provider Name as shown on LiteLLM"
|
||||
);
|
||||
|
||||
await user.type(nameInput, options.name);
|
||||
await user.type(providerInput, options.provider);
|
||||
|
||||
// Select provider from the combo box dropdown
|
||||
const providerInput = screen.getByPlaceholderText("Select a provider");
|
||||
await user.click(providerInput);
|
||||
const providerOption = await screen.findByRole("option", {
|
||||
name: new RegExp(options.provider, "i"),
|
||||
});
|
||||
await user.click(providerOption);
|
||||
|
||||
// Fill in model name (first model row)
|
||||
const modelNameInput = screen.getByPlaceholderText("Model name");
|
||||
@@ -83,7 +100,9 @@ describe("Custom LLM Provider Configuration Workflow", () => {
|
||||
}
|
||||
|
||||
test("creates a new custom LLM provider successfully", async () => {
|
||||
const user = setupUser();
|
||||
const user = setupUser({
|
||||
pointerEventsCheck: PointerEventsCheckLevel.Never,
|
||||
});
|
||||
|
||||
// Mock POST /api/admin/llm/test
|
||||
fetchSpy.mockResolvedValueOnce({
|
||||
@@ -159,7 +178,9 @@ describe("Custom LLM Provider Configuration Workflow", () => {
|
||||
});
|
||||
|
||||
test("shows error when test configuration fails", async () => {
|
||||
const user = setupUser();
|
||||
const user = setupUser({
|
||||
pointerEventsCheck: PointerEventsCheckLevel.Never,
|
||||
});
|
||||
|
||||
// Mock POST /api/admin/llm/test (failure)
|
||||
fetchSpy.mockResolvedValueOnce({
|
||||
@@ -204,7 +225,9 @@ describe("Custom LLM Provider Configuration Workflow", () => {
|
||||
});
|
||||
|
||||
test("updates an existing LLM provider", async () => {
|
||||
const user = setupUser();
|
||||
const user = setupUser({
|
||||
pointerEventsCheck: PointerEventsCheckLevel.Never,
|
||||
});
|
||||
|
||||
const existingProvider = {
|
||||
id: 1,
|
||||
@@ -285,7 +308,9 @@ describe("Custom LLM Provider Configuration Workflow", () => {
|
||||
});
|
||||
|
||||
test("preserves additional models when updating a provider", async () => {
|
||||
const user = setupUser();
|
||||
const user = setupUser({
|
||||
pointerEventsCheck: PointerEventsCheckLevel.Never,
|
||||
});
|
||||
|
||||
const existingProvider = {
|
||||
id: 7,
|
||||
@@ -382,7 +407,9 @@ describe("Custom LLM Provider Configuration Workflow", () => {
|
||||
});
|
||||
|
||||
test("sets provider as default when shouldMarkAsDefault is true", async () => {
|
||||
const user = setupUser();
|
||||
const user = setupUser({
|
||||
pointerEventsCheck: PointerEventsCheckLevel.Never,
|
||||
});
|
||||
|
||||
// Mock POST /api/admin/llm/test
|
||||
fetchSpy.mockResolvedValueOnce({
|
||||
@@ -436,7 +463,9 @@ describe("Custom LLM Provider Configuration Workflow", () => {
|
||||
});
|
||||
|
||||
test("shows error when provider creation fails", async () => {
|
||||
const user = setupUser();
|
||||
const user = setupUser({
|
||||
pointerEventsCheck: PointerEventsCheckLevel.Never,
|
||||
});
|
||||
|
||||
// Mock POST /api/admin/llm/test
|
||||
fetchSpy.mockResolvedValueOnce({
|
||||
@@ -472,7 +501,9 @@ describe("Custom LLM Provider Configuration Workflow", () => {
|
||||
});
|
||||
|
||||
test("adds custom configuration key-value pairs", async () => {
|
||||
const user = setupUser();
|
||||
const user = setupUser({
|
||||
pointerEventsCheck: PointerEventsCheckLevel.Never,
|
||||
});
|
||||
|
||||
// Mock POST /api/admin/llm/test
|
||||
fetchSpy.mockResolvedValueOnce({
|
||||
@@ -492,10 +523,13 @@ describe("Custom LLM Provider Configuration Workflow", () => {
|
||||
const nameInput = screen.getByPlaceholderText("Display Name");
|
||||
await user.type(nameInput, "Cloudflare Provider");
|
||||
|
||||
const providerInput = screen.getByPlaceholderText(
|
||||
"Provider Name as shown on LiteLLM"
|
||||
);
|
||||
await user.type(providerInput, "cloudflare");
|
||||
// Select provider from the combo box dropdown
|
||||
const providerInput = screen.getByPlaceholderText("Select a provider");
|
||||
await user.click(providerInput);
|
||||
const providerOption = await screen.findByRole("option", {
|
||||
name: /cloudflare/i,
|
||||
});
|
||||
await user.click(providerOption);
|
||||
|
||||
// Click "Add Line" button for custom config (aria-label from KeyValueInput)
|
||||
const addLineButton = screen.getByRole("button", {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo } from "react";
|
||||
import { useSWRConfig } from "swr";
|
||||
import { useFormikContext } from "formik";
|
||||
import {
|
||||
@@ -18,11 +19,13 @@ import {
|
||||
ModelAccessField,
|
||||
ModalWrapper,
|
||||
} from "@/sections/modals/llmConfig/shared";
|
||||
import { useCustomProviderNames } from "@/hooks/useLLMProviders";
|
||||
import InputTypeInField from "@/refresh-components/form/InputTypeInField";
|
||||
import * as InputLayouts from "@/layouts/input-layouts";
|
||||
import KeyValueInput, {
|
||||
KeyValue,
|
||||
} from "@/refresh-components/inputs/InputKeyValue";
|
||||
import InputComboBox from "@/refresh-components/inputs/InputComboBox";
|
||||
import InputTypeIn from "@/refresh-components/inputs/InputTypeIn";
|
||||
import InputSelect from "@/refresh-components/inputs/InputSelect";
|
||||
import Text from "@/refresh-components/texts/Text";
|
||||
@@ -99,7 +102,6 @@ function ModelConfigurationItem({
|
||||
/>
|
||||
<Button
|
||||
disabled={!canRemove}
|
||||
tooltip={!canRemove ? "At least one model is required" : undefined}
|
||||
prominence="tertiary"
|
||||
icon={SvgMinusCircle}
|
||||
onClick={onRemove}
|
||||
@@ -190,6 +192,35 @@ function CustomConfigKeyValue() {
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Provider Name Select ─────────────────────────────────────────────────────
|
||||
|
||||
function ProviderNameSelect({ disabled }: { disabled?: boolean }) {
|
||||
const { customProviderNames } = useCustomProviderNames();
|
||||
const { values, setFieldValue } = useFormikContext<{ provider: string }>();
|
||||
|
||||
const options = useMemo(
|
||||
() =>
|
||||
(customProviderNames ?? []).map((opt) => ({
|
||||
value: opt.value,
|
||||
label: opt.value,
|
||||
description: opt.label,
|
||||
})),
|
||||
[customProviderNames]
|
||||
);
|
||||
|
||||
return (
|
||||
<InputComboBox
|
||||
value={values.provider}
|
||||
onValueChange={(value) => setFieldValue("provider", value)}
|
||||
options={options}
|
||||
placeholder="Select a provider"
|
||||
disabled={disabled}
|
||||
createPrefix="Use"
|
||||
dropdownMaxHeight="60vh"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Custom Config Processing ─────────────────────────────────────────────────
|
||||
|
||||
function keyValueListToDict(items: KeyValue[]): Record<string, string> {
|
||||
@@ -336,23 +367,17 @@ export default function CustomModal({
|
||||
});
|
||||
}}
|
||||
>
|
||||
{!isOnboarding && (
|
||||
<InputLayouts.FieldPadder>
|
||||
<InputLayouts.Vertical
|
||||
name="provider"
|
||||
title="Provider Name"
|
||||
subDescription={markdown(
|
||||
"Should be one of the providers listed at [LiteLLM](https://docs.litellm.ai/docs/providers)."
|
||||
)}
|
||||
>
|
||||
<InputTypeInField
|
||||
name="provider"
|
||||
placeholder="Provider Name as shown on LiteLLM"
|
||||
variant={existingLlmProvider ? "disabled" : undefined}
|
||||
/>
|
||||
</InputLayouts.Vertical>
|
||||
</InputLayouts.FieldPadder>
|
||||
)}
|
||||
<InputLayouts.FieldPadder>
|
||||
<InputLayouts.Vertical
|
||||
name="provider"
|
||||
title="Provider Name"
|
||||
subDescription={markdown(
|
||||
"Should be one of the providers listed at [LiteLLM](https://docs.litellm.ai/docs/providers)."
|
||||
)}
|
||||
>
|
||||
<ProviderNameSelect disabled={!!existingLlmProvider} />
|
||||
</InputLayouts.Vertical>
|
||||
</InputLayouts.FieldPadder>
|
||||
|
||||
<APIBaseField optional />
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useMemo } from "react";
|
||||
import { useSWRConfig } from "swr";
|
||||
import { useFormikContext } from "formik";
|
||||
import * as InputLayouts from "@/layouts/input-layouts";
|
||||
@@ -24,8 +23,7 @@ import {
|
||||
ModelAccessField,
|
||||
ModalWrapper,
|
||||
} from "@/sections/modals/llmConfig/shared";
|
||||
import { fetchModels } from "@/app/admin/configuration/llm/utils";
|
||||
import debounce from "lodash/debounce";
|
||||
import { fetchModels } from "@/lib/llmConfig/svc";
|
||||
import { toast } from "@/hooks/useToast";
|
||||
import { refreshLlmProviderCaches } from "@/lib/llmConfig/cache";
|
||||
|
||||
@@ -48,54 +46,23 @@ function LMStudioModalInternals({
|
||||
isOnboarding,
|
||||
}: LMStudioModalInternalsProps) {
|
||||
const formikProps = useFormikContext<LMStudioModalValues>();
|
||||
const initialApiKey = existingLlmProvider?.custom_config?.LM_STUDIO_API_KEY;
|
||||
|
||||
const doFetchModels = useCallback(
|
||||
(apiBase: string, apiKey: string | undefined, signal: AbortSignal) => {
|
||||
fetchModels(
|
||||
LLMProviderName.LM_STUDIO,
|
||||
{
|
||||
api_base: apiBase,
|
||||
custom_config: apiKey ? { LM_STUDIO_API_KEY: apiKey } : {},
|
||||
api_key_changed: apiKey !== initialApiKey,
|
||||
name: existingLlmProvider?.name,
|
||||
},
|
||||
signal
|
||||
).then((data) => {
|
||||
if (signal.aborted) return;
|
||||
if (data.error) {
|
||||
toast.error(data.error);
|
||||
formikProps.setFieldValue("model_configurations", []);
|
||||
return;
|
||||
}
|
||||
formikProps.setFieldValue("model_configurations", data.models);
|
||||
});
|
||||
},
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[existingLlmProvider?.name, initialApiKey]
|
||||
);
|
||||
const isFetchDisabled = !formikProps.values.api_base;
|
||||
|
||||
const debouncedFetchModels = useMemo(
|
||||
() => debounce(doFetchModels, 500),
|
||||
[doFetchModels]
|
||||
);
|
||||
|
||||
const apiBase = formikProps.values.api_base;
|
||||
const apiKey = formikProps.values.custom_config?.LM_STUDIO_API_KEY;
|
||||
|
||||
useEffect(() => {
|
||||
if (apiBase) {
|
||||
const controller = new AbortController();
|
||||
debouncedFetchModels(apiBase, apiKey, controller.signal);
|
||||
return () => {
|
||||
debouncedFetchModels.cancel();
|
||||
controller.abort();
|
||||
};
|
||||
} else {
|
||||
formikProps.setFieldValue("model_configurations", []);
|
||||
const handleFetchModels = async () => {
|
||||
const apiKey = formikProps.values.custom_config?.LM_STUDIO_API_KEY;
|
||||
const initialApiKey = existingLlmProvider?.custom_config?.LM_STUDIO_API_KEY;
|
||||
const data = await fetchModels(LLMProviderName.LM_STUDIO, {
|
||||
api_base: formikProps.values.api_base,
|
||||
custom_config: apiKey ? { LM_STUDIO_API_KEY: apiKey } : {},
|
||||
api_key_changed: apiKey !== initialApiKey,
|
||||
name: existingLlmProvider?.name,
|
||||
});
|
||||
if (data.error) {
|
||||
throw new Error(data.error);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [apiBase, apiKey, debouncedFetchModels]);
|
||||
formikProps.setFieldValue("model_configurations", data.models);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -105,6 +72,7 @@ function LMStudioModalInternals({
|
||||
/>
|
||||
|
||||
<APIKeyField
|
||||
name="custom_config.LM_STUDIO_API_KEY"
|
||||
optional
|
||||
subDescription="Optional API key if your LM Studio server requires authentication."
|
||||
/>
|
||||
@@ -117,7 +85,10 @@ function LMStudioModalInternals({
|
||||
)}
|
||||
|
||||
<InputLayouts.FieldSeparator />
|
||||
<ModelSelectionField shouldShowAutoUpdateToggle={false} />
|
||||
<ModelSelectionField
|
||||
shouldShowAutoUpdateToggle={false}
|
||||
onRefetch={isFetchDisabled ? undefined : handleFetchModels}
|
||||
/>
|
||||
|
||||
{!isOnboarding && (
|
||||
<>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user