Metadata-Version: 2.4
Name: amlllm-openai-server
Version: 0.1.1
Summary: Open AI API compatiable LLM server for Amlogic Device
Author-email: Chen ZHU <chen.zhu@amlogic.com>, Dian YUAN <Dian.Yuan@amlogic.com>
Project-URL: Homepage, https://github.com/Amlogic-NN/amlogic-llm-server
Project-URL: Repository, https://github.com/Amlogic-NN/amlogic-llm-server
Project-URL: Issues, https://github.com/Amlogic-NN/amlogic-llm-server/issues
Classifier: Development Status :: 4 - Beta
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Cython
Classifier: Programming Language :: C
Classifier: Programming Language :: C++
Classifier: Operating System :: POSIX :: Linux
Classifier: Framework :: FastAPI
Classifier: Operating System :: POSIX :: Linux
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: fastapi<1.0,>=0.115
Requires-Dist: PyYAML<7.0,>=6.0
Requires-Dist: uvicorn<1.0,>=0.30
Requires-Dist: json-repair~=0.59.6
Requires-Dist: jinja2<4.0,>=3.1
Requires-Dist: jsonschema~=4.26.0
Requires-Dist: pydantic~=2.13.4
Requires-Dist: httpx<1.0,>=0.27
Requires-Dist: openai>=1.0
Requires-Dist: matplotlib>=3.9
Requires-Dist: numpy>=1.26
Requires-Dist: Pillow>=10.0
Provides-Extra: dev
Requires-Dist: pytest>=9.0.3; extra == "dev"
Requires-Dist: cython>=3.0; extra == "dev"
Provides-Extra: benchmark
Requires-Dist: datasets>=3.0; extra == "benchmark"
Requires-Dist: tqdm>=4.0; extra == "benchmark"
Requires-Dist: numpy>=1.26; extra == "benchmark"
Dynamic: license-file

# AML LLM OpenAI Server

An OpenAI-compatible API server for Amlogic LLM devices, with built-in tool-calling
evaluation and Agent capability benchmarking tools.

- **Server**: OpenAI-compatible `/v1/chat/completions` endpoint (ADLA & llama.cpp backends)
- **Tools Evaluation**: Measure tool-calling accuracy of local vs cloud models
- **Agent Benchmark**: Evaluate LLM agent capabilities on MMLU-Pro, TAU2-Bench, and BFCL

---

### Prerequisites

This project is using `uv` please use following command or follow the [official document](https://docs.astral.sh/uv/getting-started/installation/) to install uv

```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
```

### Install the wheel

```bash
uv venv --python 3.11
uv pip install amlllm-openai-server -i <index url>
```

### Bootstrap

#### Use a bootstrap tool

_You need Internet connection to use bootstrap scripts to download the models or you can manually put files in folder_

1. List the available model

```bash
uv run -m amlllm_openai_server.bootstrap list
```

You will see the available models as following table

| \# | Name | Type | Thinking | Multimodal | Context | Tools |
|----|------|------|----------|------------|---------|-------|
| 0 | Qwen3-1.7B | Qwen3 | Yes | No | 8192 | Yes |
| 1 | Qwen3-4B-Instruct-2507 | Qwen3 | No | No | 8192 | Yes |
| 2 | Qwen3-4B | Qwen3 | Yes | No | 4096 | Yes |

2. Download the model

Replace the model name as your expectation. Here use `Qwen3-4B-Instruct-2507` for example.

```bash
uv run -m amlllm_openai_server.bootstrap download Qwen3-4B-Instruct-2507
```

---

## Server Configuration

### `config/server.yaml`

```yaml
server:
  host: "0.0.0.0"
  port: 8000
  api_key: ""          # optional, set for authentication
  log_level: "info"
  title: "AMLLLM OneAPI Proxy"
  version: "0.2.0"

models:
  root_dir: "../models"
  enabled:
    - default           # model directories under root_dir

# Optional: upstream proxy to a cloud API
# upstream:
#   base_url: "https://api.openai.com"
#   api_key: "sk-..."
#   model: "gpt-4o"
#   force_upstream: false
#   skill_injection: false
```

### `models/default/model.json`

Example for Qwen3 Seriers:

```json
{
  "id": "amlogic-default",
  "weights": "Qwen3-1.7B-Q4AM_PB32.adla",
  "model_type": "qwen",
  "sampling_mode": "top_p",
  "top_k": 40,
  "top_p": 0.85,
  "temperature": 0.7,
  "repeat_penalty": 1.15,
  "presence_penalty": 10,
  "system_prompt": "You are a helpful assistant.",
  "prompt_prefix": "",
  "prompt_postfix": "",
  "retain_history": true,
  "loglevel": "ERROR",
  "metadata": {
    "family": "default",
    "device": "amlogic"
  },
  "token_pair": { "151657": 151658 },
  "chat_format": "{%- if tools %}\n    {{- '<|im_start|>system\\n' }}\n    {%- if messages[0].role == 'system' %}\n        {{- messages[0].content + '\\n\\n' }}\n    {%- endif %}\n    {{- \"# Tools\\n\\nYou may call one or more functions to assist with the user query.\\n\\nYou are provided with function signatures within <tools></tools> XML tags:\\n<tools>\" }}\n    {%- for tool in tools %}\n        {{- \"\\n\" }}\n        {{- tool | tojson }}\n    {%- endfor %}\n    {{- \"\\n</tools>\\n\\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\\n<tool_call>\\n{\\\"name\\\": <function-name>, \\\"arguments\\\": <args-json-object>}\\n</tool_call><|im_end|>\\n\" }}\n{%- else %}\n    {%- if messages[0].role == 'system' %}\n        {{- '<|im_start|>system\\n' + messages[0].content + '<|im_end|>\\n' }}\n    {%- endif %}\n{%- endif %}\n{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}\n{%- for message in messages[::-1] %}\n    {%- set index = (messages|length - 1) - loop.index0 %}\n    {%- if ns.multi_step_tool and message.role == \"user\" and message.content is string and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}\n        {%- set ns.multi_step_tool = false %}\n        {%- set ns.last_query_index = index %}\n    {%- endif %}\n{%- endfor %}\n{%- for message in messages %}\n    {%- if message.content is string %}\n        {%- set content = message.content %}\n    {%- else %}\n        {%- set content = '' %}\n    {%- endif %}\n    {%- if (message.role == \"user\") or (message.role == \"system\" and not loop.first) %}\n        {{- '<|im_start|>' + message.role + '\\n' + content + '<|im_end|>' + '\\n' }}\n    {%- elif message.role == \"assistant\" %}\n        {%- set reasoning_content = '' %}\n        {%- if message.reasoning_content is string %}\n            {%- set reasoning_content = message.reasoning_content %}\n        {%- else %}\n            {%- if '</think>' in content %}\n                {%- set reasoning_content = content.split('</think>')[0].rstrip('\\n').split('<think>')[-1].lstrip('\\n') %}\n                {%- set content = content.split('</think>')[-1].lstrip('\\n') %}\n            {%- endif %}\n        {%- endif %}\n        {%- if loop.index0 > ns.last_query_index %}\n            {%- if loop.last or (not loop.last and reasoning_content) %}\n                {{- '<|im_start|>' + message.role + '\\n<think>\\n' + reasoning_content.strip('\\n') + '\\n</think>\\n\\n' + content.lstrip('\\n') }}\n            {%- else %}\n                {{- '<|im_start|>' + message.role + '\\n' + content }}\n            {%- endif %}\n        {%- else %}\n            {{- '<|im_start|>' + message.role + '\\n' + content }}\n        {%- endif %}\n        {%- if message.tool_calls %}\n            {%- for tool_call in message.tool_calls %}\n                {%- if (loop.first and content) or (not loop.first) %}\n                    {{- '\\n' }}\n                {%- endif %}\n                {%- if tool_call.function %}\n                    {%- set tool_call = tool_call.function %}\n                {%- endif %}\n                {{- '<tool_call>\\n{\"name\": \"' }}\n                {{- tool_call.name }}\n                {{- '\", \"arguments\": ' }}\n                {%- if tool_call.arguments is string %}\n                    {{- tool_call.arguments }}\n                {%- else %}\n                    {{- tool_call.arguments | tojson }}\n                {%- endif %}\n                {{- '}\\n</tool_call>' }}\n            {%- endfor %}\n        {%- endif %}\n        {{- '<|im_end|>\\n' }}\n    {%- elif message.role == \"tool\" %}\n        {%- if loop.first or (messages[loop.index0 - 1].role != \"tool\") %}\n            {{- '<|im_start|>user' }}\n        {%- endif %}\n        {{- '\\n<tool_response>\\n' }}\n        {{- content }}\n        {{- '\\n</tool_response>' }}\n        {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n            {{- '<|im_end|>\\n' }}\n        {%- endif %}\n    {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n    {{- '<|im_start|>assistant\\n' }}\n    {%- if enable_thinking is defined and enable_thinking is false %}\n        {{- '<think>\\n\\n</think>\\n\\n' }}\n    {%- endif %}\n{%- endif %}"
}
```

### Model Configuration Parameters

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `id` | `string` | Yes | — | Unique model identifier, used as `model` in OpenAI API requests |
| `weights` | `string` | Yes | — | Path to the model weights file (`.adla` for ADLA, `.gguf` for llama.cpp) |
| `model_type` | `string` | Yes | — | Model architecture type: `"qwen"`, `"llama"`, `"gemma"`, etc. Determines chat template and tokenization |
| `sampling_mode` | `string` | No | `"top_p"` | Sampling strategy: `"top_p"`, `"top_k"`, or `"greedy"` |
| `top_k` | `int` | No | `40` | Top-K sampling: keep only the K most likely tokens |
| `top_p` | `float` | No | `0.85` | Nucleus sampling: keep tokens with cumulative probability ≥ p |
| `temperature` | `float` | No | `0.7` | Controls randomness; higher = more creative, lower = more deterministic |
| `repeat_penalty` | `float` | No | `1.15` | Penalizes repeated tokens; > 1.0 discourages repetition |
| `presence_penalty` | `float` | No | `0` | ADLA-specific presence penalty for token repetition |
| `system_prompt` | `string` | No | `""` | Default system prompt prepended to every conversation |
| `prompt_prefix` | `string` | No | `""` | Custom text prepended before the prompt |
| `prompt_postfix` | `string` | No | `""` | Custom text appended after the prompt |
| `retain_history` | `bool` | No | `true` | Whether to keep conversation history across turns |
| `loglevel` | `string` | No | `"ERROR"` | ADLA runtime log level: `"DEBUG"`, `"INFO"`, `"WARNING"`, `"ERROR"` |
| `metadata` | `dict` | No | `{}` | Arbitrary key-value metadata exposed in `/v1/models` response |
| `token_pair` | `dict` | No | `{}` | Special token ID mapping, e.g. `{"151657": 151658}` maps `<tool_call>` → `</tool_call>`, the token MUST appear in pair, as  151657 ->xxx -> 151658, otherwise, the generation will be stopped. |
| `chat_format` | `string`  | No | `""` | Jinja2 chat template for formatting messages (see [Jinja2 Templates](#jinja2-chat-templates))  or Path to `tokenizer_config.json`|
| `chat_template_kwargs` | `dict` | No | `{}` | Extra parameters passed to chat templates | 

### Jinja2 Chat Templates

The `chat_format` field uses Jinja2 syntax or tokenizer config to define how messages are formatted into the model's native prompt structure. 

1. Prepare the model `tokenizer_config.json`
2. For Qwen series, it is possible to put the Jinja template string directly
3. For other series, put the path to `tokenizer_config.json` 

Backend values:
- `"adla"` — Amlogic ADLA runtime (AARCH64 only)


---

## Running the Server

```bash
# Default: reads config/server.yaml
uv run python -m amlllm_openai_server

# Custom config path
uv run python -m amlllm_openai_server --config /path/to/server.yaml

# Override host/port/log-level
uv run python -m amlllm_openai_server --host 0.0.0.0 --port 8000 --log-level debug
```

Test the endpoint:

```bash
curl http://localhost:8000/v1/models
curl http://localhost:8000/healthz
```

### If you want to install PicoClaw

```bash
dpkg -i picoclaw_modified_aarch64.deb
```

### Run demo with PicoClaw

1. Start the AMLLLM server (see above)
2. Start PicoClaw:
   ```bash
   picoclaw-launcher &
   ```
3. Configure PicoClaw model:
   - **Provider**: openai
   - **Model identifier**: `amlogic-default`
   - **API Base URL**: `http://localhost:8000/v1`

**Tips**: The agent work folder is under `$HOME/.picoclaw/workspace`. If you are using
local models with context limitations, it's better to remove `AGENTS.md` and `SOUL.md`.

