Skip to content

Commit 7e4ea5b

Browse files
authored
examples : add server example with REST API (#1443)
* Added httplib support * Added readme for server example * fixed some bugs * Fix the build error on Macbook * changed json11 to nlohmann-json * removed some whitespaces * remove trailing whitespace * added support custom prompts and more functions * some corrections and added as cmake option
1 parent 7780e4f commit 7e4ea5b

File tree

7 files changed

+34434
-0
lines changed

7 files changed

+34434
-0
lines changed

CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ option(LLAMA_CLBLAST "llama: use CLBlast"
7272

7373
option(LLAMA_BUILD_TESTS "llama: build tests" ${LLAMA_STANDALONE})
7474
option(LLAMA_BUILD_EXAMPLES "llama: build examples" ${LLAMA_STANDALONE})
75+
option(LLAMA_BUILD_SERVER "llama: build server example" OFF)
7576

7677
#
7778
# Build info header

examples/CMakeLists.txt

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,4 +37,7 @@ else()
3737
add_subdirectory(save-load-state)
3838
add_subdirectory(benchmark)
3939
add_subdirectory(baby-llama)
40+
if(LLAMA_BUILD_SERVER)
41+
add_subdirectory(server)
42+
endif()
4043
endif()

examples/server/CMakeLists.txt

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
set(TARGET server)
2+
include_directories(${CMAKE_CURRENT_SOURCE_DIR})
3+
add_executable(${TARGET} server.cpp json.hpp httplib.h)
4+
target_link_libraries(${TARGET} PRIVATE common llama ${CMAKE_THREAD_LIBS_INIT})
5+
target_compile_features(${TARGET} PRIVATE cxx_std_11)
6+
if(TARGET BUILD_INFO)
7+
add_dependencies(${TARGET} BUILD_INFO)
8+
endif()

examples/server/README.md

Lines changed: 311 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,311 @@
1+
# llama.cpp/example/server
2+
3+
This example allow you to have a llama.cpp http server to interact from a web page or consume the API.
4+
5+
## Table of Contents
6+
7+
1. [Quick Start](#quick-start)
8+
2. [Node JS Test](#node-js-test)
9+
3. [API Endpoints](#api-endpoints)
10+
4. [More examples](#more-examples)
11+
5. [Common Options](#common-options)
12+
6. [Performance Tuning and Memory Options](#performance-tuning-and-memory-options)
13+
14+
## Quick Start
15+
16+
To get started right away, run the following command, making sure to use the correct path for the model you have:
17+
18+
#### Unix-based systems (Linux, macOS, etc.):
19+
20+
```bash
21+
./server -m models/7B/ggml-model.bin --ctx_size 2048
22+
```
23+
24+
#### Windows:
25+
26+
```powershell
27+
server.exe -m models\7B\ggml-model.bin --ctx_size 2048
28+
```
29+
30+
That will start a server that by default listens on `127.0.0.1:8080`. You can consume the endpoints with Postman or NodeJS with axios library.
31+
32+
## Node JS Test
33+
34+
You need to have [Node.js](https://nodejs.org/en) installed.
35+
36+
```bash
37+
mkdir llama-client
38+
cd llama-client
39+
npm init
40+
npm install axios
41+
```
42+
43+
Create a index.js file and put inside this:
44+
45+
```javascript
46+
const axios = require("axios");
47+
48+
const prompt = `Building a website can be done in 10 simple steps:`;
49+
50+
async function Test() {
51+
let result = await axios.post("http://127.0.0.1:8080/completion", {
52+
prompt,
53+
batch_size: 128,
54+
n_predict: 512,
55+
});
56+
57+
// the response is received until completion finish
58+
console.log(result.data.content);
59+
}
60+
61+
Test();
62+
```
63+
64+
And run it:
65+
66+
```bash
67+
node .
68+
```
69+
70+
## API Endpoints
71+
72+
You can interact with this API Endpoints. This implementations just support chat style interaction.
73+
74+
- **POST** `hostname:port/completion`: Setting up the Llama Context to begin the completions tasks.
75+
76+
*Options:*
77+
78+
`batch_size`: Set the batch size for prompt processing (default: 512).
79+
80+
`temperature`: Adjust the randomness of the generated text (default: 0.8).
81+
82+
`top_k`: Limit the next token selection to the K most probable tokens (default: 40).
83+
84+
`top_p`: Limit the next token selection to a subset of tokens with a cumulative probability above a threshold P (default: 0.9).
85+
86+
`n_predict`: Set the number of tokens to predict when generating text (default: 128, -1 = infinity).
87+
88+
`threads`: Set the number of threads to use during computation.
89+
90+
`n_keep`: Specify the number of tokens from the initial prompt to retain when the model resets its internal context. By default, this value is set to 0 (meaning no tokens are kept). Use `-1` to retain all tokens from the initial prompt.
91+
92+
`as_loop`: It allows receiving each predicted token in real-time instead of waiting for the completion to finish. To enable this, set to `true`.
93+
94+
`interactive`: It allows interacting with the completion, and the completion stops as soon as it encounters a `stop word`. To enable this, set to `true`.
95+
96+
`prompt`: Provide a prompt. Internally, the prompt is compared, and it detects if a part has already been evaluated, and the remaining part will be evaluate.
97+
98+
`stop`: Specify the words or characters that indicate a stop. These words will not be included in the completion, so make sure to add them to the prompt for the next iteration.
99+
100+
`exclude`: Specify the words or characters you do not want to appear in the completion. These words will not be included in the completion, so make sure to add them to the prompt for the next iteration.
101+
102+
- **POST** `hostname:port/embedding`: Generate embedding of a given text
103+
104+
*Options:*
105+
106+
`content`: Set the text to get generate the embedding.
107+
108+
`threads`: Set the number of threads to use during computation.
109+
110+
To use this endpoint, you need to start the server with the `--embedding` option added.
111+
112+
- **POST** `hostname:port/tokenize`: Tokenize a given text
113+
114+
*Options:*
115+
116+
`content`: Set the text to tokenize.
117+
118+
- **GET** `hostname:port/next-token`: Receive the next token predicted, execute this request in a loop. Make sure set `as_loop` as `true` in the completion request.
119+
120+
*Options:*
121+
122+
`stop`: Set `hostname:port/next-token?stop=true` to stop the token generation.
123+
124+
## More examples
125+
126+
### Interactive mode
127+
128+
This mode allows interacting in a chat-like manner. It is recommended for models designed as assistants such as `Vicuna`, `WizardLM`, `Koala`, among others. Make sure to add the correct stop word for the corresponding model.
129+
130+
The prompt should be generated by you, according to the model's guidelines. You should keep adding the model's completions to the context as well.
131+
132+
This example works well for `Vicuna - version 1`.
133+
134+
```javascript
135+
const axios = require("axios");
136+
137+
let prompt = `A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions.
138+
### Human: Hello, Assistant.
139+
### Assistant: Hello. How may I help you today?
140+
### Human: Please tell me the largest city in Europe.
141+
### Assistant: Sure. The largest city in Europe is Moscow, the capital of Russia.`;
142+
143+
async function ChatCompletion(answer) {
144+
// the user's next question to the prompt
145+
prompt += `\n### Human: ${answer}\n`
146+
147+
result = await axios.post("http://127.0.0.1:8080/completion", {
148+
prompt,
149+
batch_size: 128,
150+
temperature: 0.2,
151+
top_k: 40,
152+
top_p: 0.9,
153+
n_keep: -1,
154+
n_predict: 2048,
155+
stop: ["\n### Human:"], // when detect this, stop completion
156+
exclude: ["### Assistant:"], // no show in the completion
157+
threads: 8,
158+
as_loop: true, // use this to request the completion token by token
159+
interactive: true, // enable the detection of a stop word
160+
});
161+
162+
// create a loop to receive every token predicted
163+
// note: this operation is blocking, avoid use this in a ui thread
164+
165+
let message = "";
166+
while (true) {
167+
// you can stop the inference adding '?stop=true' like this http://127.0.0.1:8080/next-token?stop=true
168+
result = await axios.get("http://127.0.0.1:8080/next-token");
169+
process.stdout.write(result.data.content);
170+
message += result.data.content;
171+
172+
// to avoid an infinite loop
173+
if (result.data.stop) {
174+
console.log("Completed");
175+
// make sure to add the completion to the prompt.
176+
prompt += `### Assistant: ${message}`;
177+
break;
178+
}
179+
}
180+
}
181+
182+
// This function should be called every time a question to the model is needed.
183+
async function Test() {
184+
// the server can't inference in paralell
185+
await ChatCompletion("Write a long story about a time magician in a fantasy world");
186+
await ChatCompletion("Summary the story");
187+
}
188+
189+
Test();
190+
```
191+
192+
### Alpaca example
193+
194+
**Temporaly note:** no tested, if you have the model, please test it and report me some issue
195+
196+
```javascript
197+
const axios = require("axios");
198+
199+
let prompt = `Below is an instruction that describes a task. Write a response that appropriately completes the request.
200+
`;
201+
202+
async function DoInstruction(instruction) {
203+
prompt += `\n\n### Instruction:\n\n${instruction}\n\n### Response:\n\n`;
204+
result = await axios.post("http://127.0.0.1:8080/completion", {
205+
prompt,
206+
batch_size: 128,
207+
temperature: 0.2,
208+
top_k: 40,
209+
top_p: 0.9,
210+
n_keep: -1,
211+
n_predict: 2048,
212+
stop: ["### Instruction:\n\n"], // when detect this, stop completion
213+
exclude: [], // no show in the completion
214+
threads: 8,
215+
as_loop: true, // use this to request the completion token by token
216+
interactive: true, // enable the detection of a stop word
217+
});
218+
219+
// create a loop to receive every token predicted
220+
// note: this operation is blocking, avoid use this in a ui thread
221+
222+
let message = "";
223+
while (true) {
224+
result = await axios.get("http://127.0.0.1:8080/next-token");
225+
process.stdout.write(result.data.content);
226+
message += result.data.content;
227+
228+
// to avoid an infinite loop
229+
if (result.data.stop) {
230+
console.log("Completed");
231+
// make sure to add the completion and the user's next question to the prompt.
232+
prompt += message;
233+
break;
234+
}
235+
}
236+
}
237+
238+
// This function should be called every time a instruction to the model is needed.
239+
DoInstruction("Destroy the world"); // as joke
240+
```
241+
242+
### Embeddings
243+
244+
First, run the server with `--embedding` option:
245+
246+
```bash
247+
server -m models/7B/ggml-model.bin --ctx_size 2048 --embedding
248+
```
249+
250+
Run this code in NodeJS:
251+
252+
```javascript
253+
const axios = require('axios');
254+
255+
async function Test() {
256+
let result = await axios.post("http://127.0.0.1:8080/embedding", {
257+
content: `Hello`,
258+
threads: 5
259+
});
260+
// print the embedding array
261+
console.log(result.data.embedding);
262+
}
263+
264+
Test();
265+
```
266+
267+
### Tokenize
268+
269+
Run this code in NodeJS:
270+
271+
```javascript
272+
const axios = require('axios');
273+
274+
async function Test() {
275+
let result = await axios.post("http://127.0.0.1:8080/tokenize", {
276+
content: `Hello`
277+
});
278+
// print the embedding array
279+
console.log(result.data.tokens);
280+
}
281+
282+
Test();
283+
```
284+
285+
## Common Options
286+
287+
- `-m FNAME, --model FNAME`: Specify the path to the LLaMA model file (e.g., `models/7B/ggml-model.bin`).
288+
- `-c N, --ctx_size N`: Set the size of the prompt context. The default is 512, but LLaMA models were built with a context of 2048, which will provide better results for longer input/inference.
289+
- `--embedding`: Enable the embedding mode. **Completion function doesn't work in this mode**.
290+
- `--host`: Set the hostname or ip address to listen. Default `127.0.0.1`;
291+
- `--port`: Set the port to listen. Default: `8080`.
292+
293+
### RNG Seed
294+
295+
- `-s SEED, --seed SEED`: Set the random number generator (RNG) seed (default: -1, < 0 = random seed).
296+
297+
The RNG seed is used to initialize the random number generator that influences the text generation process. By setting a specific seed value, you can obtain consistent and reproducible results across multiple runs with the same input and settings. This can be helpful for testing, debugging, or comparing the effects of different options on the generated text to see when they diverge. If the seed is set to a value less than 0, a random seed will be used, which will result in different outputs on each run.
298+
299+
## Performance Tuning and Memory Options
300+
301+
### No Memory Mapping
302+
303+
- `--no-mmap`: Do not memory-map the model. By default, models are mapped into memory, which allows the system to load only the necessary parts of the model as needed. However, if the model is larger than your total amount of RAM or if your system is low on available memory, using mmap might increase the risk of pageouts, negatively impacting performance.
304+
305+
### Memory Float 32
306+
307+
- `--memory_f32`: Use 32-bit floats instead of 16-bit floats for memory key+value, allowing higher quality inference at the cost of higher memory usage.
308+
309+
## Limitations:
310+
311+
- The actual implementation of llama.cpp need a `llama-state` for handle multiple contexts and clients, but this could require more powerful hardware.

0 commit comments

Comments
 (0)