# Run and serve models

FastFlowLM (`flm`) runs models on the NPU from the terminal or as a local server with an OpenAI-compatible API, so existing OpenAI clients, LangChain, and Open WebUI work unchanged. The model tags are on the [Models](<https://rocm.github.io/FastFlow-SDK/reference/models/index.md>) page; `flm list` shows the ones in your installed release.

## Chat in the terminal

```
flm run qwen3:0.6b
```

The first run downloads the model from Hugging Face. Type `/bye` to exit. `flm pull <tag>` downloads without starting a chat.

## Start the server

```
flm serve qwen3:0.6b
```

The server listens on `http://127.0.0.1:52625`, with the OpenAI API under `/v1`. Change the port for one run with `--port <port>`, or for every run with the `FLM_SERVE_PORT` environment variable. Other useful options:

| Option | Effect |
| --- | --- |
| `--ctx-len <tokens>` | Context length, rounded up to a power of two, at least 512 |
| `--pmode <mode>` | NPU power mode: `powersaver`, `balanced`, `performance` (default), or `turbo` |
| `--embed 1` | Also load the default embedding model, EmbeddingGemma; or pass an embedding model's tag |
| `--asr 1` | Also load the default speech-to-text model, Whisper; or pass a speech model's tag |
| `--cors 0` | Disable CORS, which is on by default; do this if the server is reachable beyond localhost |

One model of each kind (LLM, embedding, speech) can be loaded at a time, and they can run together in one server.

## Endpoints

| Endpoint | Use |
| --- | --- |
| `GET /v1/models` | List the models |
| `POST /v1/chat/completions` | Chat, streaming, tool calls, and structured output |
| `POST /v1/completions` | Plain text completion |
| `POST /v1/embeddings` | Embeddings; start the server with `--embed 1` |
| `POST /v1/audio/transcriptions` | Speech to text; start the server with `--asr 1` |

The server does not check API keys, but OpenAI clients require one, so pass any string.

```
curl http://127.0.0.1:52625/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{"model": "qwen3:0.6b", "messages": [{"role": "user", "content": "Hello"}]}'
```

The Python examples below need `python -m pip install openai`. CI runs each one except speech to text against `flm serve` on an NPU. Download them from this site, for example `curl -fsSLO https://rocm.github.io/FastFlow-SDK/examples/serve/chat.py`.

## Chat with streaming

```
#!/usr/bin/env python3
# Copyright Advanced Micro Devices, Inc.
# SPDX-License-Identifier: MIT
"""Chat with a model that FastFlowLM serves on the NPU, streaming the reply.

Start the server in another terminal first:

    flm serve qwen3:0.6b
    python -m pip install openai
    python examples/serve/chat.py
"""

import os

from openai import OpenAI

# flm serve listens on 52625 unless FLM_SERVE_PORT or --port changes it.
BASE_URL = os.environ.get("FLM_BASE_URL", "http://127.0.0.1:52625/v1")
MODEL = os.environ.get("FLM_MODEL", "qwen3:0.6b")

# FastFlowLM does not check the key, but the client requires one.
client = OpenAI(base_url=BASE_URL, api_key="flm")

stream = client.chat.completions.create(
    model=MODEL,
    messages=[{"role": "user", "content": "In one sentence, what is an NPU?"}],
    stream=True,
)
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
print()
```

## Tool calls

The server parses each model's own tool-call markup into OpenAI `tool_calls`. It supports `tool_choice` (`auto`, `required`, `none`, or one function) and `parallel_tool_calls`. Use a model whose capabilities on [Models](<https://rocm.github.io/FastFlow-SDK/reference/models/index.md>) include `tool-calling`, such as `gemma4-it:e2b`.

```
#!/usr/bin/env python3
# Copyright Advanced Micro Devices, Inc.
# SPDX-License-Identifier: MIT
"""Let a model that FastFlowLM serves call a Python function.

Use a model whose Capabilities on the Models page include tool calling:

    flm serve gemma4-it:e2b
    python examples/serve/tool_call.py
"""

import json
import os

from openai import OpenAI

BASE_URL = os.environ.get("FLM_BASE_URL", "http://127.0.0.1:52625/v1")
MODEL = os.environ.get("FLM_MODEL", "gemma4-it:e2b")

client = OpenAI(base_url=BASE_URL, api_key="flm")


def get_weather(city: str) -> dict:
    return {"city": city, "forecast": "sunny", "celsius": 21}


TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get today's weather for a city.",
            "parameters": {
                "type": "object",
                "properties": {"city": {"type": "string"}},
                "required": ["city"],
            },
        },
    }
]

messages = [{"role": "user", "content": "What is the weather in Austin today?"}]
reply = client.chat.completions.create(model=MODEL, messages=messages, tools=TOOLS)
message = reply.choices[0].message
messages.append(message.model_dump(exclude_none=True))
for call in message.tool_calls or []:
    print(f"tool call: {call.function.name}({call.function.arguments})")
    result = get_weather(**json.loads(call.function.arguments))
    messages.append(
        {"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)}
    )

final = client.chat.completions.create(model=MODEL, messages=messages, tools=TOOLS)
print(final.choices[0].message.content)
```

## Thinking and structured output

Reasoning models put their thinking in `reasoning_content`, separate from `content`. Turn thinking on or off per request with the FastFlowLM `think` field, which the OpenAI SDK sends through `extra_body`:

```
client.chat.completions.create(model="qwen3:0.6b", messages=messages, extra_body={"think": False})
```

The setting stays on the loaded model for later requests, so send it on every request if you mix both. `response_format` accepts `json_object` and `json_schema`, and constrains the output to the schema. FastFlowLM documents both in [Reasoning, tool calls and streaming](<https://fastflowlm.com/docs/instructions/server/reasoning_and_tools/>) and [Structured output](<https://fastflowlm.com/docs/instructions/server/structured_output/>).

## Embeddings

```
#!/usr/bin/env python3
# Copyright Advanced Micro Devices, Inc.
# SPDX-License-Identifier: MIT
"""Embed text with EmbeddingGemma, served by FastFlowLM beside an LLM.

flm serve qwen3:0.6b --embed 1
python examples/serve/embeddings.py
"""

import math
import os

from openai import OpenAI

BASE_URL = os.environ.get("FLM_BASE_URL", "http://127.0.0.1:52625/v1")

client = OpenAI(base_url=BASE_URL, api_key="flm")


def embed(text: str) -> list[float]:
    return client.embeddings.create(model="embed-gemma", input=text).data[0].embedding


a = embed("The model runs on the NPU.")
b = embed("The NPU executes the model.")
cosine = sum(x * y for x, y in zip(a, b, strict=True)) / (
    math.hypot(*a) * math.hypot(*b)
)
print(f"{len(a)} dimensions, cosine similarity {cosine:.3f}")
```

## Speech to text

```
#!/usr/bin/env python3
# Copyright Advanced Micro Devices, Inc.
# SPDX-License-Identifier: MIT
"""Transcribe an audio file with Whisper, served by FastFlowLM.

flm serve --asr 1
python examples/serve/transcribe.py recording.mp3
"""

import os
import sys

from openai import OpenAI

BASE_URL = os.environ.get("FLM_BASE_URL", "http://127.0.0.1:52625/v1")

client = OpenAI(base_url=BASE_URL, api_key="flm")

with open(sys.argv[1], "rb") as audio:
    print(client.audio.transcriptions.create(model="whisper-v3", file=audio).text)
```

## Use your own NPU kernels in a model

FastFlowLM loads model extensions: engines built outside `flm` that replace parts of a model with your own NPU programs. [Replace Gemma 4 GEMM and dequant with IRON](<https://rocm.github.io/FastFlow-SDK/examples/iron-gemma4-gemm-dequant/index.md>) walks through one.
