Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions docs/modules/llm.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,35 @@ response = llm.generate(
)
```

### RuncrateLLM

RuncrateLLM is an adapter for [Runcrate](https://runcrate.ai/), which serves open-weight models such as DeepSeek, Qwen, Kimi, GLM and gpt-oss through an OpenAI-compatible API.

The `RuncrateLLM` model class reuses the OpenAI chat-completions logic in EvoAgentX (streaming, async and tool calls) and points it at `https://api.runcrate.ai/v1`. If `runcrate_key` is not set, the `RUNCRATE_API_KEY` environment variable is used. See the [Runcrate docs](https://runcrate.ai/docs) for the list of available models.

**Basic Usage:**

```python
from evoagentx.models import RuncrateConfig, RuncrateLLM

# Configure the model
config = RuncrateConfig(
model="deepseek-ai/DeepSeek-V4-Flash",
runcrate_key="your-runcrate-api-key",
temperature=0.7,
max_tokens=1000
)

# Initialize the model
llm = RuncrateLLM(config=config)

# Generate text
response = llm.generate(
prompt="Write a poem about artificial intelligence.",
system_message="You are a creative poet."
)
```

### OpenRouterLLM

OpenRouterLLM is an adapter for the [OpenRouter platform](https://openrouter.ai/), which provides access to a wide range of language models from various providers through a unified API. It supports models from providers like Anthropic, Google, Meta, Mistral AI, and more, all accessible through a single interface.
Expand Down
29 changes: 29 additions & 0 deletions docs/zh/modules/llm.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,35 @@ response = llm.generate(
)
```

### RuncrateLLM

RuncrateLLM 是 [Runcrate](https://runcrate.ai/) 的适配器,Runcrate 通过 OpenAI 兼容的 API 提供 DeepSeek、Qwen、Kimi、GLM 和 gpt-oss 等开源权重模型。

`RuncrateLLM` 模型类复用 EvoAgentX 中的 OpenAI 聊天补全逻辑(流式、异步和工具调用),并将请求发送到 `https://api.runcrate.ai/v1`。如果未设置 `runcrate_key`,则会使用环境变量 `RUNCRATE_API_KEY`。可用模型列表请参阅 [Runcrate 文档](https://runcrate.ai/docs)。

**基本用法:**

```python
from evoagentx.models import RuncrateConfig, RuncrateLLM

# Configure the model
config = RuncrateConfig(
model="deepseek-ai/DeepSeek-V4-Flash",
runcrate_key="your-runcrate-api-key",
temperature=0.7,
max_tokens=1000
)

# Initialize the model
llm = RuncrateLLM(config=config)

# Generate text
response = llm.generate(
prompt="Write a poem about artificial intelligence.",
system_message="You are a creative poet."
)
```

### OpenRouterLLM

OpenRouterLLM 是 [OpenRouter 平台](https://openrouter.ai/) 的适配器,该平台通过统一的 API 提供对各种提供商的语言模型的访问。它支持来自 Anthropic、Google、Meta、Mistral AI 等提供商的模型,所有这些都可以通过单一接口访问。
Expand Down
1 change: 1 addition & 0 deletions evoagentx/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@
from .openrouter_model import *
from .aliyun_model import *
from .novita_model import *
from .runcrate_model import *
32 changes: 32 additions & 0 deletions evoagentx/models/model_configs.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,38 @@ def __str__(self):
return self.model


class RuncrateConfig(LLMConfig):

# LLM keys
llm_type: str = "RuncrateLLM"
runcrate_key: Optional[str] = Field(default=None, description="the API key used to authenticate Runcrate requests. Falls back to the RUNCRATE_API_KEY environment variable.")

# generation parameters
temperature: Optional[float] = Field(default=None, description="the temperature used to scaling logits")
max_tokens : Optional[int] = Field(default=None, description="maximum number of generated tokens")
max_completion_tokens: Optional[int] = Field(default=None, description="An upper bound for the number of tokens that can be generated for a completion, including visible output tokens and reasoning tokens.")
top_p: Optional[float] = Field(default=None, description="Only sample from tokens with cumulative probability greater than top_p when generating text.")
n: Optional[int] = Field(default=None, description="How many chat completion choices to generate for each input message.")
stream: Optional[bool] = Field(default=None, description=" If set to true, it sends partial message deltas. Tokens will be sent as they become available, with the stream terminated by a [DONE] message.")
stream_options: Optional[dict] = Field(default=None, description="Options for streaming response. Only set this when you set stream: true")
timeout: Optional[Union[float, int]] = Field(default=None, description="Timeout in seconds for completion requests (Defaults to 600 seconds)")

# tools
tools: Optional[List] = Field(default=None, description="A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of functions the model may generate JSON inputs for.")
tool_choice: Optional[Union[str, dict]] = Field(default=None, description="Controls which (if any) function is called by the model. none means the model will not call a function and instead generates a message. auto means the model can pick between generating a message or calling a function. required forces the model to call a tool. Specifying a particular function via {\"type\": \"function\", \"function\": {\"name\": \"my_function\"}} forces the model to call that function.")
parallel_tool_calls: Optional[bool] = Field(default=None, description="Whether to enable parallel function calling during tool use.")

# token probabilities
logprobs: Optional[bool] = Field(default=None, description="Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned in the content of message.")
top_logprobs: Optional[int] = Field(default=None, description="An integer between 0 and 5 specifying the number of most likely tokens to return at each token position, each with an associated log probability. logprobs must be set to true if this parameter is used.")

# output format
response_format: Optional[Union[BaseModel, dict]] = Field(default=None, description=" An object specifying the format that the model must output.")

def __str__(self):
return self.model


# def get_default_device():
# return "cuda" if torch.cuda.is_available() else "cpu"

Expand Down
69 changes: 69 additions & 0 deletions evoagentx/models/runcrate_model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import os
from typing import Optional, Union

from openai import AsyncOpenAI, OpenAI
from openai.types.chat import ChatCompletion, ChatCompletionChunk

from .openai_model import OpenAILLM
from .model_configs import RuncrateConfig
from ..core.logging import logger
from ..core.registry import register_model
from .model_utils import Cost, cost_manager

# Runcrate exposes an OpenAI-compatible API at this base URL.
RUNCRATE_BASE_URL = "https://api.runcrate.ai/v1"


@register_model(config_cls=RuncrateConfig, alias=["runcrate"])
class RuncrateLLM(OpenAILLM):
"""Runcrate LLM client.

Runcrate serves open-weight models through the OpenAI chat-completions
protocol, so this reuses all of ``OpenAILLM``'s generation/streaming/tool-call
logic and only overrides client construction and cost handling.

If ``runcrate_key`` is not set in the config, the ``RUNCRATE_API_KEY``
environment variable is used.

LiteLLM has no pricing data for Runcrate-hosted models, so the dollar cost
cannot be computed or approximated. Token counts are still tracked; the
per-model cost is recorded as 0. A warning is emitted once at init time.
"""

def init_model(self):
self._client = None
self._async_client = None
# parameters in RuncrateConfig that are not Runcrate models' input parameters
self._default_ignore_fields = ["llm_type", "runcrate_key", "output_response"]
logger.warning(
"[RuncrateLLM] LiteLLM has no pricing data for Runcrate models, so dollar "
"cost cannot be computed. Token usage will be tracked, but cost will "
"be recorded as 0."
)

@staticmethod
def _api_key(config: RuncrateConfig) -> Optional[str]:
return config.runcrate_key or os.getenv("RUNCRATE_API_KEY")

def _init_client(self, config: RuncrateConfig):
return OpenAI(api_key=self._api_key(config), base_url=RUNCRATE_BASE_URL)

def _init_async_client(self, config: RuncrateConfig):
return AsyncOpenAI(api_key=self._api_key(config), base_url=RUNCRATE_BASE_URL)

def _update_cost(self, response: Union[ChatCompletion, ChatCompletionChunk]):
# Override OpenAILLM's LiteLLM-based cost computation: only record token
# counts and leave cost at 0 (see class docstring).
usage = getattr(response, "usage", None)
if usage is None:
logger.warning(
f"[RuncrateLLM] usage is None in response (id={getattr(response, 'id', '?')}); "
"tokens will not be recorded."
)
return
cost = Cost(
input_tokens=usage.prompt_tokens,
output_tokens=usage.completion_tokens,
cost=0.0,
)
cost_manager.update_cost(cost=cost, model=self.config.model)
107 changes: 107 additions & 0 deletions tests/src/models/test_runcrate_model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import pytest

from evoagentx.core.registry import MODEL_REGISTRY
from evoagentx.models import LLMOutputParser
from evoagentx.models.model_configs import RuncrateConfig
from evoagentx.models.model_utils import cost_manager
from evoagentx.models.runcrate_model import RUNCRATE_BASE_URL, RuncrateLLM

from tests.src.models.mock_response import (
mock_openai_stream_completions_create,
mock_openai_tool_call_create,
mock_async_openai_create,
)

RUNCRATE_MODEL = "deepseek-ai/DeepSeek-V4-Flash"
SYNC_PATCH = "openai.resources.chat.completions.Completions.create"
ASYNC_PATCH = "openai.resources.chat.completions.AsyncCompletions.create"

GET_WEATHER_TOOL = {
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a given city.",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}


@pytest.fixture(autouse=True)
def reset_cost_manager():
cost_manager.input_tokens.clear()
cost_manager.output_tokens.clear()
cost_manager.total_tokens.clear()
cost_manager.cost_per_model.clear()
yield


def _make_llm(**kwargs) -> RuncrateLLM:
kwargs.setdefault("runcrate_key", "mock_runcrate_key")
config = RuncrateConfig(model=RUNCRATE_MODEL, output_response=False, **kwargs)
return RuncrateLLM(config=config)


def _assert_tokens_recorded(model: str = RUNCRATE_MODEL):
assert cost_manager.total_tokens[model] > 0, "No tokens recorded"
assert cost_manager.cost_per_model[model] == 0.0


def test_registry_alias():
assert MODEL_REGISTRY.get_model("RuncrateLLM") is RuncrateLLM
assert MODEL_REGISTRY.get_model("runcrate") is RuncrateLLM


def test_client_uses_runcrate_base_url():
client = _make_llm().ensure_client()
assert str(client.base_url).rstrip("/") == RUNCRATE_BASE_URL
assert client.api_key == "mock_runcrate_key"


def test_runcrate_key_not_sent_as_completion_param():
params = _make_llm(temperature=0.2).get_completion_params(messages=[])
assert "runcrate_key" not in params
assert params["temperature"] == 0.2


def test_api_key_falls_back_to_env(monkeypatch):
monkeypatch.setenv("RUNCRATE_API_KEY", "env_runcrate_key")
llm = _make_llm(runcrate_key=None)
assert llm.ensure_client().api_key == "env_runcrate_key"
assert llm.ensure_async_client().api_key == "env_runcrate_key"


def test_sync_non_stream(mocker):
mocker.patch(SYNC_PATCH, mock_openai_stream_completions_create)
out = _make_llm(stream=False).generate(prompt="What is the capital of China?")
assert isinstance(out, LLMOutputParser)
assert out.content == "Beijing"
_assert_tokens_recorded()


def test_sync_stream(mocker):
mocker.patch(SYNC_PATCH, mock_openai_stream_completions_create)
out = _make_llm(stream=True).generate(prompt="What is the capital of China?")
assert isinstance(out, LLMOutputParser)
assert out.content == "Paris"
_assert_tokens_recorded()


def test_sync_tool_call(mocker):
mocker.patch(SYNC_PATCH, mock_openai_tool_call_create)
llm = _make_llm(stream=False, tools=[GET_WEATHER_TOOL], tool_choice="auto")
out = llm.generate(prompt="What is the weather in Tokyo?")
assert "<tool_call>" in out.content
assert "get_weather" in out.content
_assert_tokens_recorded()


async def test_async_stream(mocker):
mocker.patch(ASYNC_PATCH, mock_async_openai_create)
out = await _make_llm(stream=True).async_generate(prompt="What is the capital of China?")
assert isinstance(out, LLMOutputParser)
assert out.content == "Paris"
_assert_tokens_recorded()