File size: 1,731 Bytes
2109241
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/* Minimal persistent C FFI client. SPDX-License-Identifier: AGPL-3.0-only
 * Build: cc -Wall -Wextra -Werror native-api/examples/client.c -ldl -o client
 * Run: ./client /absolute/path/liblispm_llm_native_api.dylib
 * Feed one JSON request per line. The same process retains asynchronous jobs.
 */
#include <dlfcn.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

/* Function pointer signatures exactly match include/lispm_llm.h. */
typedef uint32_t (*version_fn)(void);
typedef char *(*request_fn)(const char *);
typedef void (*free_fn)(char *);

/* Keep the library loaded until process exit so native workers cannot outlive it. */
int main(int argc, char **argv) {
    if (argc != 2) {
        fputs("usage: client /absolute/path/to/native/library\n", stderr);
        return 2;
    }
    void *library = dlopen(argv[1], RTLD_NOW | RTLD_LOCAL);
    if (!library) {
        fprintf(stderr, "dlopen: %s\n", dlerror());
        return 1;
    }
    version_fn version = (version_fn)dlsym(library, "lispm_llm_abi_version");
    request_fn request = (request_fn)dlsym(library, "lispm_llm_request");
    free_fn release = (free_fn)dlsym(library, "lispm_llm_string_free");
    if (!version || !request || !release || version() != 1) {
        fputs("unsupported LispM C ABI\n", stderr);
        return 1;
    }
    char *line = NULL;
    size_t capacity = 0;
    while (getline(&line, &capacity, stdin) >= 0) {
        char *response = request(line);
        if (!response) {
            free(line);
            fputs("native allocation failed\n", stderr);
            return 1;
        }
        puts(response);
        fflush(stdout);
        release(response);
    }
    free(line);
    return ferror(stdin) ? 1 : 0;
}