mirror of
https://github.com/eigent-ai/eigent.git
synced 2026-12-05 21:47:17 +00:00
Some checks failed
Test / Run Python Tests (push) Has been cancelled
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
Test / Run Browser Preview Electron Test (push) Has been cancelled
CodeQL Advanced / Analyze (javascript-typescript) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Pre-commit / pre-commit (push) Has been cancelled
Test / Run Web + Local Brain Smoke (push) Has been cancelled
Test / Run Frontend Guardrails (push) Has been cancelled
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
392 lines
13 KiB
Python
392 lines
13 KiB
Python
# ========= Copyright 2025-2026 @ Eigent.ai All Rights Reserved. =========
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
# you may not use this file except in compliance with the License.
|
|
# You may obtain a copy of the License at
|
|
#
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
#
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
# See the License for the specific language governing permissions and
|
|
# limitations under the License.
|
|
# ========= Copyright 2025-2026 @ Eigent.ai All Rights Reserved. =========
|
|
|
|
import copy
|
|
import json
|
|
|
|
import httpx
|
|
import pytest
|
|
from camel.models import ModelFactory
|
|
from camel.models.openai_compatible_model import OpenAICompatibleModel
|
|
from camel.toolkits import FunctionTool
|
|
from openai import AsyncOpenAI, BadRequestError, OpenAI
|
|
from pydantic import BaseModel
|
|
|
|
from app.model.model_platform import (
|
|
NormalizedModelPlatform,
|
|
NormalizedOptionalModelPlatform,
|
|
canonical_model_platform,
|
|
configure_meta_model_api_backend,
|
|
is_eigent_cloud_model_endpoint,
|
|
is_meta_model_api_endpoint,
|
|
normalize_model_platform,
|
|
normalize_optional_model_platform,
|
|
patch_azure_cloud_config,
|
|
resolve_cloud_model_runtime_platform,
|
|
)
|
|
|
|
|
|
def test_normalize_model_platform_maps_known_aliases():
|
|
assert normalize_model_platform("grok") == "openai-compatible-model"
|
|
assert normalize_model_platform("z.ai") == "zhipuai"
|
|
assert normalize_model_platform("ModelArk") == "openai-compatible-model"
|
|
assert normalize_model_platform("ernie") == "qianfan"
|
|
assert normalize_model_platform("llama.cpp") == "openai-compatible-model"
|
|
assert normalize_model_platform("meta") == "openai-compatible-model"
|
|
assert normalize_model_platform("nebius") == "openai-compatible-model"
|
|
|
|
|
|
def test_normalize_model_platform_keeps_non_alias_unchanged():
|
|
assert normalize_model_platform("openai") == "openai"
|
|
assert normalize_model_platform("mistral") == "mistral"
|
|
|
|
|
|
def test_canonical_model_platform_matches_alias_and_its_target():
|
|
assert canonical_model_platform("grok") == "openai-compatible-model"
|
|
assert canonical_model_platform("openai-compatible-model") == (
|
|
"openai-compatible-model"
|
|
)
|
|
assert canonical_model_platform("z.ai") == "zhipuai"
|
|
assert canonical_model_platform("OpenAI ") == "openai"
|
|
|
|
|
|
def test_meta_model_api_endpoint_matches_exact_official_host():
|
|
assert is_meta_model_api_endpoint("https://api.meta.ai/v1")
|
|
assert is_meta_model_api_endpoint("https://API.META.AI/v1/")
|
|
assert not is_meta_model_api_endpoint("https://api.meta.ai.example/v1")
|
|
assert not is_meta_model_api_endpoint("https://example.com/api.meta.ai")
|
|
assert not is_meta_model_api_endpoint(None)
|
|
|
|
|
|
def test_meta_model_api_backend_omits_strict_without_changing_schema():
|
|
assert hasattr(OpenAICompatibleModel, "_prepare_request_config")
|
|
|
|
tools = [
|
|
{
|
|
"type": "function",
|
|
"function": {
|
|
"name": "planning_exit_plan_mode",
|
|
"strict": True,
|
|
"parameters": {
|
|
"type": "object",
|
|
"properties": {
|
|
"allowed_prompts": {
|
|
"type": "object",
|
|
"additionalProperties": {"type": "string"},
|
|
}
|
|
},
|
|
},
|
|
},
|
|
}
|
|
]
|
|
backend = ModelFactory.create(
|
|
model_platform="openai-compatible-model",
|
|
model_type="muse-spark-1.3",
|
|
api_key="test-key",
|
|
url="https://api.meta.ai/v1",
|
|
model_config_dict={"stream": True},
|
|
)
|
|
|
|
configure_meta_model_api_backend(backend, "https://api.meta.ai/v1")
|
|
request_config = backend._prepare_request_config(tools)
|
|
|
|
function = request_config["tools"][0]["function"]
|
|
assert "strict" not in function
|
|
assert function["parameters"]["properties"]["allowed_prompts"][
|
|
"additionalProperties"
|
|
] == {"type": "string"}
|
|
assert tools[0]["function"]["strict"] is True
|
|
assert request_config["stream"] is True
|
|
|
|
|
|
def test_non_meta_backend_keeps_strict_tool_schema():
|
|
class _Backend:
|
|
def _prepare_request_config(self, tools=None):
|
|
return {"tools": tools}
|
|
|
|
tools = [
|
|
{
|
|
"type": "function",
|
|
"function": {"name": "example", "strict": True},
|
|
}
|
|
]
|
|
backend = _Backend()
|
|
|
|
configure_meta_model_api_backend(backend, "https://api.openai.com/v1")
|
|
|
|
assert backend._prepare_request_config(tools)["tools"] == tools
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"nested_schema",
|
|
[
|
|
{"type": "object"},
|
|
{"type": "object", "additionalProperties": True},
|
|
{"type": "object", "additionalProperties": {"type": "string"}},
|
|
{"type": ["object", "null"], "additionalProperties": True},
|
|
{"type": "array", "items": {"type": "object"}},
|
|
{"anyOf": [{"type": "null"}, {"type": "object"}]},
|
|
{"allOf": [{"type": "object"}]},
|
|
{"oneOf": [{"type": "object"}]},
|
|
{"$ref": "#/$defs/Mapping", "$defs": {"Mapping": {"type": "object"}}},
|
|
],
|
|
)
|
|
def test_meta_only_relaxes_tools_with_open_object_schemas(nested_schema):
|
|
class Backend:
|
|
def _prepare_request_config(self, tools=None):
|
|
return {"tools": tools}
|
|
|
|
closed_schema = {
|
|
"type": "object",
|
|
"additionalProperties": False,
|
|
"properties": {
|
|
"query": {
|
|
"type": "string",
|
|
"enum": ["object", "additionalProperties"],
|
|
}
|
|
},
|
|
"required": ["query"],
|
|
}
|
|
tools = [
|
|
{
|
|
"type": "function",
|
|
"function": {
|
|
"name": "lookup",
|
|
"strict": True,
|
|
"parameters": closed_schema,
|
|
},
|
|
},
|
|
{
|
|
"type": "function",
|
|
"function": {
|
|
"name": "mapping_tool",
|
|
"strict": True,
|
|
"parameters": {
|
|
"type": "object",
|
|
"additionalProperties": False,
|
|
"properties": {"value": nested_schema},
|
|
"required": ["value"],
|
|
},
|
|
},
|
|
},
|
|
]
|
|
original_tools = copy.deepcopy(tools)
|
|
backend = Backend()
|
|
configure_meta_model_api_backend(backend, "https://api.meta.ai/v1")
|
|
configure_meta_model_api_backend(backend, "https://api.meta.ai/v1")
|
|
|
|
prepared = backend._prepare_request_config(tools)["tools"]
|
|
|
|
assert prepared[0] == original_tools[0]
|
|
assert "strict" not in prepared[1]["function"]
|
|
assert (
|
|
prepared[1]["function"]["parameters"]
|
|
== tools[1]["function"]["parameters"]
|
|
)
|
|
assert tools == original_tools
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("asynchronous", [False, True])
|
|
async def test_meta_strict_tools_support_structured_output(asynchronous):
|
|
"""Exercise the SDK parse path used by workers with native output schemas."""
|
|
|
|
class WorkerResult(BaseModel):
|
|
result: str
|
|
|
|
def lookup(query: str) -> str:
|
|
"""Look up a value.
|
|
|
|
Args:
|
|
query: The value to look up.
|
|
"""
|
|
return query
|
|
|
|
tools = [FunctionTool(lookup).get_openai_tool_schema()]
|
|
original_tools = copy.deepcopy(tools)
|
|
requests = []
|
|
|
|
def respond(request: httpx.Request) -> httpx.Response:
|
|
requests.append(request)
|
|
return httpx.Response(
|
|
200,
|
|
json={
|
|
"id": "chatcmpl-test",
|
|
"object": "chat.completion",
|
|
"created": 0,
|
|
"model": "muse-spark-1.3",
|
|
"choices": [
|
|
{
|
|
"index": 0,
|
|
"finish_reason": "stop",
|
|
"message": {
|
|
"role": "assistant",
|
|
"content": '{"result":"done"}',
|
|
},
|
|
}
|
|
],
|
|
},
|
|
)
|
|
|
|
transport = httpx.MockTransport(respond)
|
|
with OpenAI(
|
|
api_key="test-key",
|
|
base_url="https://api.meta.ai/v1",
|
|
http_client=httpx.Client(transport=transport),
|
|
max_retries=0,
|
|
) as client:
|
|
async with AsyncOpenAI(
|
|
api_key="test-key",
|
|
base_url="https://api.meta.ai/v1",
|
|
http_client=httpx.AsyncClient(transport=transport),
|
|
max_retries=0,
|
|
) as async_client:
|
|
backend = ModelFactory.create(
|
|
model_platform="openai-compatible-model",
|
|
model_type="muse-spark-1.3",
|
|
api_key="test-key",
|
|
url="https://api.meta.ai/v1",
|
|
client=client,
|
|
async_client=async_client,
|
|
model_config_dict={"stream": False},
|
|
)
|
|
configure_meta_model_api_backend(backend, "https://api.meta.ai/v1")
|
|
messages = [{"role": "user", "content": "Return the result."}]
|
|
if asynchronous:
|
|
response = await backend._arequest_parse(
|
|
messages, WorkerResult, tools
|
|
)
|
|
else:
|
|
response = backend._request_parse(
|
|
messages, WorkerResult, tools
|
|
)
|
|
|
|
assert response.choices[0].message.parsed == WorkerResult(result="done")
|
|
assert len(requests) == 1
|
|
assert requests[0].url.path == "/v1/chat/completions"
|
|
payload = json.loads(requests[0].content)
|
|
assert payload["tools"][0]["function"]["strict"] is True
|
|
assert payload["response_format"]["type"] == "json_schema"
|
|
assert tools == original_tools
|
|
|
|
|
|
def test_normalize_optional_model_platform_handles_none():
|
|
assert normalize_optional_model_platform(None) is None
|
|
|
|
|
|
def test_normalized_model_platform_type_applies_in_pydantic_model():
|
|
class _Model(BaseModel):
|
|
model_platform: NormalizedModelPlatform
|
|
optional_model_platform: NormalizedOptionalModelPlatform = None
|
|
|
|
item = _Model(
|
|
model_platform="ernie",
|
|
optional_model_platform="ModelArk",
|
|
)
|
|
|
|
assert item.model_platform == "qianfan"
|
|
assert item.optional_model_platform == "openai-compatible-model"
|
|
|
|
|
|
def test_cloud_azure_default_api_version_supports_responses():
|
|
# The cloud proxy bridges chat requests with tools to Azure's Responses
|
|
# API using this version; Azure added Responses in 2025-03-01-preview.
|
|
extra_params = {}
|
|
|
|
patched = patch_azure_cloud_config(extra_params)
|
|
|
|
assert patched["api_version"][:10] >= "2025-03-01"
|
|
assert extra_params == {}
|
|
assert patch_azure_cloud_config({"api_version": "v1"}) == {
|
|
"api_version": "v1"
|
|
}
|
|
|
|
|
|
def test_eigent_cloud_azure_responses_use_openai_compatible_transport():
|
|
assert is_eigent_cloud_model_endpoint("https://proxy.eigent.ai")
|
|
assert (
|
|
resolve_cloud_model_runtime_platform(
|
|
model_platform="azure",
|
|
api_url="https://proxy.eigent.ai",
|
|
api_mode="responses",
|
|
)
|
|
== "openai-compatible-model"
|
|
)
|
|
|
|
|
|
def test_cloud_chat_and_direct_azure_responses_keep_azure_transport():
|
|
assert (
|
|
resolve_cloud_model_runtime_platform(
|
|
model_platform="azure",
|
|
api_url="https://proxy.eigent.ai",
|
|
api_mode="chat_completions",
|
|
)
|
|
== "azure"
|
|
)
|
|
assert (
|
|
resolve_cloud_model_runtime_platform(
|
|
model_platform="azure",
|
|
api_url="https://customer-resource.openai.azure.com",
|
|
api_mode="responses",
|
|
)
|
|
== "azure"
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_cloud_responses_runtime_calls_standard_responses_route():
|
|
runtime_platform = resolve_cloud_model_runtime_platform(
|
|
model_platform="azure",
|
|
api_url="https://proxy.eigent.ai",
|
|
api_mode="responses",
|
|
)
|
|
requested_paths: list[str] = []
|
|
|
|
async def reject_after_recording(request: httpx.Request) -> httpx.Response:
|
|
requested_paths.append(request.url.path)
|
|
return httpx.Response(
|
|
400,
|
|
request=request,
|
|
json={"error": {"message": "test stop", "type": "test_error"}},
|
|
)
|
|
|
|
http_client = httpx.AsyncClient(
|
|
transport=httpx.MockTransport(reject_after_recording)
|
|
)
|
|
responses_client = AsyncOpenAI(
|
|
api_key="test-key",
|
|
base_url="https://proxy.eigent.ai",
|
|
max_retries=0,
|
|
http_client=http_client,
|
|
)
|
|
|
|
backend = ModelFactory.create(
|
|
model_platform=runtime_platform,
|
|
model_type="gpt-5.7-future",
|
|
api_key="test-key",
|
|
url="https://proxy.eigent.ai",
|
|
api_mode="responses",
|
|
async_client=responses_client,
|
|
)
|
|
|
|
assert isinstance(backend, OpenAICompatibleModel)
|
|
assert backend._api_mode == "responses"
|
|
with pytest.raises(BadRequestError, match="test stop"):
|
|
await backend._async_client.responses.create(
|
|
model="gpt-5.7-future",
|
|
input="hello",
|
|
)
|
|
|
|
assert requested_paths == ["/responses"]
|
|
await responses_client.close()
|