llm-link 0.3.3

A universal LLM proxy supporting 9 providers (OpenAI, Anthropic, Zhipu, Aliyun, Volcengine, Tencent, Longcat, Moonshot, Ollama) with dynamic model discovery API, hot-reload configuration, and optional API key startup
Documentation
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
# LLM Link

[![Crates.io](https://img.shields.io/crates/v/llm-link.svg)](https://crates.io/crates/llm-link)
[![Documentation](https://docs.rs/llm-link/badge.svg)](https://docs.rs/llm-link)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Downloads](https://img.shields.io/crates/d/llm-link.svg)](https://crates.io/crates/llm-link)

πŸš€ **A user-friendly LLM proxy service with built-in support for popular AI coding tools**

LLM Link provides zero-configuration access to LLM providers through multiple API formats, with optimized built-in support for Codex CLI, Zed, and Claude Code.

## ✨ Key Features

- **🎯 Application-Oriented**: Built-in configurations for popular AI coding tools
- **⚑ Zero Configuration**: One-command startup for common use cases
- **πŸ”„ Multi-Protocol**: Simultaneous OpenAI, Ollama, and Anthropic API support
- **πŸ”€ 9 LLM Providers**: OpenAI, Anthropic, Zhipu, Aliyun, Volcengine, Tencent, Longcat, Moonshot, Ollama
- **πŸ“‘ Dynamic Model Discovery**: REST API to query all supported providers and models
- **πŸ”₯ Hot-Reload Configuration**: Update API keys and switch providers without restart
- **πŸ› οΈ CLI-First**: Simple command-line interface with helpful guidance
- **πŸ”§ Smart Adaptation**: Automatic client detection and optimization
- **πŸš€ Production Ready**: Built with Rust for performance and reliability

## 🎯 Supported Applications

| Application | Protocol | Port | Authentication | Status |
|-------------|----------|------|----------------|---------|
| **Codex CLI** | OpenAI API | 8088 | Bearer Token | βœ… Ready |
| **Zed** | Ollama API | 11434 | None | βœ… Ready |
| **Claude Code** | Anthropic API | 8089 | API Key | βœ… Ready |

## πŸš€ Quick Start

### Installation

#### Option 1: Install from crates.io (Recommended)

```bash
cargo install llm-link
```

#### Option 2: Build from source

```bash
git clone https://github.com/lipish/llm-link.git
cd llm-link
cargo build --release
```

### 🎯 Application Mode (Recommended)

**Step 1: Set up environment variables**
```bash
# Required for all applications (choose your provider)
export ZHIPU_API_KEY="your-zhipu-api-key"
# OR
export OPENAI_API_KEY="sk-xxx"
# OR
export ANTHROPIC_API_KEY="sk-ant-xxx"

# Required for Codex CLI (choose one method)
export LLM_LINK_API_KEY="your-auth-token"
# OR use CLI parameter: --api-key "your-auth-token"
```

**Step 2: Start for your application**
```bash
# For Codex CLI
./target/release/llm-link --app codex-cli --api-key "your-auth-token"

# For Zed
./target/release/llm-link --app zed

# For Claude Code
export ANTHROPIC_API_KEY="your-anthropic-key"
./target/release/llm-link --app claude-code
```

### πŸ“‹ Get Help and Information

```bash
# List all supported applications
./target/release/llm-link --list-apps

# Get detailed setup guide for specific application
./target/release/llm-link --app-info codex-cli
./target/release/llm-link --app-info zed
./target/release/llm-link --app-info claude-code

# Show all CLI options
./target/release/llm-link --help
```

### πŸ”§ Protocol Mode (Advanced)

For custom protocol combinations:

```bash
# Support multiple protocols simultaneously
./target/release/llm-link --protocols ollama,openai --api-key "your-key"
```

### πŸ”„ Provider Override

Switch between different LLM providers without changing configuration:

```bash
# Use OpenAI GPT-4 instead of default
export OPENAI_API_KEY="sk-xxx"
./target/release/llm-link --app codex-cli \
  --provider openai \
  --model gpt-4

# Use Anthropic Claude
export ANTHROPIC_API_KEY="sk-ant-xxx"
./target/release/llm-link --app codex-cli \
  --provider anthropic \
  --model claude-3-5-sonnet-20241022

# Use Ollama local models
./target/release/llm-link --app codex-cli \
  --provider ollama \
  --model llama2

# Use Zhipu GLM models
export ZHIPU_API_KEY="your-key"
./target/release/llm-link --app codex-cli \
  --provider zhipu \
  --model glm-4-flash

# Use Aliyun Qwen models
export ALIYUN_API_KEY="your-key"
./target/release/llm-link --app codex-cli \
  --provider aliyun \
  --model qwen-max
```

**Supported Providers:**
- `openai` - OpenAI GPT models (default: `gpt-4`)
- `anthropic` - Anthropic Claude models (default: `claude-3-5-sonnet-20241022`)
- `zhipu` - Zhipu GLM models (default: `glm-4-flash`)
- `aliyun` - Aliyun Qwen models (default: `qwen-max`)
- `volcengine` - Volcengine Doubao models (default: `doubao-pro-32k`)
- `tencent` - Tencent Hunyuan models (default: `hunyuan-lite`)
- `longcat` - LongCat models (default: `LongCat-Flash-Chat`)
- `moonshot` - Moonshot Kimi models (default: `kimi-k2-turbo-preview`)
- `ollama` - Ollama local models (default: `llama2`)

**πŸ’‘ Discover All Models:**
```bash
# Query all supported providers and their models via API
curl http://localhost:11434/api/info | jq '.supported_providers'
```

See [API Documentation](docs/API_PROVIDERS_MODELS.md) for details.

## βš™οΈ Environment Variables

### Required Variables

```bash
# LLM Provider API Keys (choose based on your provider)
export ZHIPU_API_KEY="your-zhipu-api-key"           # For Zhipu GLM models
export OPENAI_API_KEY="sk-xxx"                      # For OpenAI GPT models
export ANTHROPIC_API_KEY="sk-ant-xxx"               # For Anthropic Claude models
export ALIYUN_API_KEY="your-aliyun-key"             # For Aliyun Qwen models

# LLM Link Authentication (required for Codex CLI)
export LLM_LINK_API_KEY="your-auth-token"           # Bearer token for API access
```

### Optional Variables

```bash
# Ollama Configuration
export OLLAMA_BASE_URL="http://localhost:11434"     # Ollama server URL

# Logging
export LLM_LINK_LOG_LEVEL="info"                    # Log level: debug, info, warn, error
export RUST_LOG="debug"                             # Rust logging (for development)
```

### Using .env File

Create a `.env` file in the project root:

```bash
# .env
ZHIPU_API_KEY=your-zhipu-api-key
LLM_LINK_API_KEY=your-auth-token
OPENAI_API_KEY=sk-xxx
ANTHROPIC_API_KEY=sk-ant-xxx
ALIYUN_API_KEY=your-aliyun-key
```

**Note**: The `.env` file is ignored by git for security. Never commit API keys to version control.

## πŸ“‘ API Endpoints

LLM Link provides REST APIs for service management and model discovery:

### Get Provider and Model Information

```bash
# Get all supported providers and their models
curl http://localhost:11434/api/info

# Example response:
{
  "service": "llm-link",
  "version": "0.3.2",
  "current_provider": "zhipu",
  "current_model": "glm-4-flash",
  "supported_providers": [
    {
      "name": "zhipu",
      "models": [
        {
          "id": "glm-4.6",
          "name": "GLM-4.6",
          "description": "Latest flagship model with 200K context"
        },
        ...
      ]
    },
    ...
  ]
}
```

### Query Specific Provider Models

```bash
# Get Zhipu models
curl -s http://localhost:11434/api/info | jq '.supported_providers[] | select(.name == "zhipu")'

# List all provider names
curl -s http://localhost:11434/api/info | jq -r '.supported_providers[].name'

# Count models per provider
curl -s http://localhost:11434/api/info | jq -r '.supported_providers[] | "\(.name): \(.models | length) models"'
```

### Hot-Reload Configuration

```bash
# Update API key without restart
curl -X POST http://localhost:11434/api/config/update-key \
  -H "Content-Type: application/json" \
  -d '{"provider": "zhipu", "api_key": "new-api-key"}'

# Switch provider
curl -X POST http://localhost:11434/api/config/switch-provider \
  -H "Content-Type: application/json" \
  -d '{"provider": "openai", "model": "gpt-4"}'
```

πŸ“š **Full API Documentation**: See [API_PROVIDERS_MODELS.md](docs/API_PROVIDERS_MODELS.md)

## 🎯 Application Setup Guides

### Codex CLI Integration

1. **Start LLM Link**:
   ```bash
   # Default: Zhipu GLM-4-Flash
   export ZHIPU_API_KEY="your-zhipu-api-key"
   ./target/release/llm-link --app codex-cli --api-key "your-auth-token"

   # Or use OpenAI GPT-4
   export OPENAI_API_KEY="sk-xxx"
   ./target/release/llm-link --app codex-cli --api-key "your-auth-token" \
     --provider openai --model gpt-4

   # Or use Anthropic Claude
   export ANTHROPIC_API_KEY="sk-ant-xxx"
   ./target/release/llm-link --app codex-cli --api-key "your-auth-token" \
     --provider anthropic
   ```

2. **Configure Codex CLI** (`~/.codex/config.toml`):
   ```toml
   [model_providers.llm_link]
   name = "LLM Link"
   base_url = "http://localhost:8088/v1"
   env_key = "LLM_LINK_API_KEY"

   [profiles.default]
   model = "glm-4-flash"  # Or gpt-4, claude-3-5-sonnet-20241022, etc.
   model_provider = "llm_link"
   ```

3. **Use Codex CLI**:
   ```bash
   export LLM_LINK_API_KEY="your-auth-token"
   codex --profile default "Write a Python function"
   ```

πŸ’‘ **Tip**: You can switch providers without changing Codex configuration - just restart llm-link with different `--provider` and `--model` flags!

### Zed Integration

1. **Start LLM Link**:
   ```bash
   export ZHIPU_API_KEY="your-zhipu-api-key"
   ./target/release/llm-link --app zed
   ```

2. **Configure Zed** (`~/.config/zed/settings.json`):
   ```json
   {
     "language_models": {
       "llm-link": {
         "api_url": "http://localhost:11434"
       }
     }
   }
   ```

3. **Use in Zed**: Open Zed and use the AI assistant features

### Claude Code Integration

1. **Start LLM Link**:
   ```bash
   export ANTHROPIC_API_KEY="your-anthropic-key"
   ./target/release/llm-link --app claude-code
   ```

2. **Configure Claude Code**:

   Create or edit the Claude Code settings file at `~/.claude/settings.json`:

   ```json
   {
     "env": {
       "ANTHROPIC_AUTH_TOKEN": "your-auth-token",
       "ANTHROPIC_BASE_URL": "http://localhost:8089",
       "API_TIMEOUT_MS": "300000"
     }
   }
   ```

   **Configuration Options:**
   - `ANTHROPIC_AUTH_TOKEN`: Your authentication token (can be any value when using LLM Link)
   - `ANTHROPIC_BASE_URL`: Point to LLM Link's Claude Code endpoint (`http://localhost:8089`)
   - `API_TIMEOUT_MS`: Request timeout in milliseconds (optional, default: 300000)

3. **Using Different LLM Providers with Claude Code**:

   You can use any supported LLM provider with Claude Code by configuring LLM Link:

   ```bash
   # Use OpenAI GPT-4 with Claude Code
   export OPENAI_API_KEY="sk-xxx"
   ./target/release/llm-link --app claude-code \
     --provider openai \
     --model gpt-4

   # Use Zhipu GLM models with Claude Code
   export ZHIPU_API_KEY="your-zhipu-key"
   ./target/release/llm-link --app claude-code \
     --provider zhipu \
     --model glm-4-flash

   # Use Aliyun Qwen models with Claude Code
   export ALIYUN_API_KEY="your-aliyun-key"
   ./target/release/llm-link --app claude-code \
     --provider aliyun \
     --model qwen-max

   # Use local Ollama models with Claude Code
   ./target/release/llm-link --app claude-code \
     --provider ollama \
     --model llama2
   ```

   **Note**: The Claude Code settings file (`~/.claude/settings.json`) remains the same regardless of which LLM provider you use. LLM Link handles the provider switching transparently.

## πŸ”§ Advanced Usage

### Runtime Configuration Updates

LLM Link provides APIs for runtime configuration management, enabling desktop applications and process managers to update provider settings without manual restarts.

#### Configuration Management APIs

```bash
# Get current configuration
GET http://localhost:11434/api/config/current

# Get health status and instance ID (for restart verification)
GET http://localhost:11434/api/health

# Validate API key before applying
POST http://localhost:11434/api/config/validate
{
  "provider": "zhipu",
  "api_key": "your-api-key"
}

# Prepare configuration for restart
POST http://localhost:11434/api/config/update
{
  "provider": "zhipu",
  "api_key": "your-api-key",
  "model": "glm-4-flash"
}
```

#### Integration Flow

When integrating LLM Link into desktop applications or process managers:

1. **Validate Configuration**: Call `/api/config/validate` to verify the API key
2. **Prepare Update**: Call `/api/config/update` to get restart parameters and current `instance_id`
3. **Restart Process**: Kill current process and start with new environment variables
4. **Verify Success**: Poll `/api/health` until `instance_id` changes and configuration matches

**Example Response**:
```json
{
  "status": "success",
  "current_instance_id": 1729900000,
  "env_vars": {
    "ZHIPU_API_KEY": "your-api-key"
  },
  "cli_args": {
    "provider": "zhipu",
    "model": "glm-4-flash"
  }
}
```

**Restart Verification**:
```bash
# After restart, verify new instance
GET /api/health
{
  "status": "ok",
  "instance_id": 1729900050,  // Changed - restart successful
  "provider": "zhipu",         // Config applied
  "model": "glm-4-flash"
}
```

**Complete Documentation**:
- πŸ“– [Configuration Update API]./docs/CONFIG_UPDATE_API.md - Full API reference and examples
- πŸ“– [Restart Verification Guide]./docs/RESTART_VERIFICATION.md - TypeScript/Python integration examples

### Multiple Applications Simultaneously

You can run multiple LLM Link instances for different applications:

```bash
# Terminal 1: Codex CLI (port 8088)
./target/release/llm-link --app codex-cli --api-key "token1"

# Terminal 2: Zed (port 11434)
./target/release/llm-link --app zed

# Terminal 3: Claude Code (port 8089)
./target/release/llm-link --app claude-code
```

### API Endpoints by Application

| Application | Base URL | Key Endpoints |
|-------------|----------|---------------|
| **Codex CLI** | `http://localhost:8088` | `/v1/chat/completions`, `/v1/models` |
| **Zed** | `http://localhost:11434` | `/api/chat`, `/api/tags` |
| **Claude Code** | `http://localhost:8089` | `/anthropic/v1/messages`, `/anthropic/v1/models` |

## πŸ”₯ Hot-Reload Configuration

**New in v0.3.0**: Update API keys and switch providers without restarting the service!

Perfect for desktop applications like **z-agent** where users need to change settings through a UI.

### πŸš€ Quick Examples

```bash
# Check current configuration
curl http://localhost:11434/api/config/current

# Update API key for OpenAI (no restart needed!)
curl -X POST http://localhost:11434/api/config/update-key \
  -H "Content-Type: application/json" \
  -d '{"provider": "openai", "api_key": "sk-..."}'

# Switch to Anthropic instantly
curl -X POST http://localhost:11434/api/config/switch-provider \
  -H "Content-Type: application/json" \
  -d '{"provider": "anthropic", "model": "claude-3-5-sonnet-20241022", "api_key": "sk-ant-..."}'

# Validate API key before using
curl -X POST http://localhost:11434/api/config/validate-key \
  -H "Content-Type: application/json" \
  -d '{"provider": "ollama", "api_key": ""}'
```

### πŸ”§ Hot-Reload API Endpoints

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/api/config/current` | GET | Get current provider, model, and hot-reload status |
| `/api/config/update-key` | POST | Update API key for specific provider |
| `/api/config/switch-provider` | POST | Switch to different LLM provider |
| `/api/config/validate-key` | POST | Validate API key and get model list |

### ✨ Features

- **πŸ”„ Zero Downtime**: Configuration changes without service restart
- **πŸ”’ Secure**: API keys are safely masked in logs
- **βœ… Validation**: Test API keys before applying changes
- **🧡 Thread Safe**: Concurrent requests handled safely
- **πŸ“‹ Model Discovery**: Get available models during validation

### πŸ“š Integration Examples

**JavaScript/TypeScript:**
```javascript
const client = new LlmLinkClient('http://localhost:11434');

// Check if hot-reload is supported
const config = await client.getCurrentConfig();
if (config.supports_hot_reload) {
  // Update API key
  await client.updateApiKey('openai', 'sk-...');

  // Switch provider
  await client.switchProvider('anthropic', 'claude-3-5-sonnet-20241022', 'sk-ant-...');
}
```

**Python:**
```python
client = LlmLinkClient('http://localhost:11434')

# Validate and update
validation = client.validate_api_key('openai', 'sk-...')
if validation['status'] == 'valid':
    client.update_api_key('openai', 'sk-...')
```

πŸ“– **Complete Documentation**: [Hot-Reload API Guide](./HOT_RELOAD_API.md)

## πŸ› οΈ CLI Reference

### Application Commands

```bash
# List all supported applications
./target/release/llm-link --list-apps

# Get application setup guide
./target/release/llm-link --app-info <app-name>

# Start in application mode
./target/release/llm-link --app <app-name> [options]
```

### CLI Options

```bash
./target/release/llm-link [OPTIONS]

Options:
  -a, --app <APP>              Application mode (codex-cli, zed, claude-code)
      --list-apps              List all supported applications
      --app-info <APP>         Show application information and setup guide
      --protocols <PROTOCOLS>  Protocol mode (ollama,openai,anthropic)
      --api-key <API_KEY>      API key for authentication (overrides env var)
      --provider <PROVIDER>    Override LLM provider (openai, anthropic, zhipu, aliyun, ollama)
      --model <MODEL>          Override LLM model name
      --llm-api-key <KEY>      LLM provider API key (overrides provider-specific env vars)
      --host <HOST>            Host to bind to
  -p, --port <PORT>            Port to bind to
      --log-level <LEVEL>      Log level [default: info]
  -h, --help                   Print help
```

## πŸ§ͺ Testing Your Setup

### Quick API Tests

```bash
# Test Codex CLI setup
curl -H "Authorization: Bearer your-token" \
     http://localhost:8088/v1/models

# Test Zed setup
curl http://localhost:11434/api/tags

# Test Claude Code setup
curl http://localhost:8089/health

# Test Claude Code API endpoint
curl -X POST http://localhost:8089/v1/messages \
  -H "Content-Type: application/json" \
  -H "x-api-key: your-auth-token" \
  -d '{
    "model": "claude-3-5-sonnet-20241022",
    "max_tokens": 100,
    "messages": [
      {"role": "user", "content": "Hello, world!"}
    ]
  }'
```

### Health Check

```bash
# Check service status
curl http://localhost:8088/health  # Codex CLI
curl http://localhost:11434/health # Zed
curl http://localhost:8089/health  # Claude Code
```

## πŸ” Troubleshooting

### Common Issues

1. **Missing Environment Variables**
   ```bash
   # Check what's required for your app
   ./target/release/llm-link --app-info codex-cli
   ```

2. **Port Already in Use**
   ```bash
   # Find what's using the port
   lsof -i :8088
   # Kill the process
   kill -9 <PID>
   ```

3. **Authentication Errors**
   ```bash
   # Verify your API keys are set correctly
   echo $ZHIPU_API_KEY
   echo $LLM_LINK_API_KEY
   echo $ANTHROPIC_API_KEY
   ```

4. **Claude Code Configuration Issues**
   ```bash
   # Check Claude Code settings file
   cat ~/.claude/settings.json

   # Verify the settings format is correct
   # Should contain: ANTHROPIC_AUTH_TOKEN, ANTHROPIC_BASE_URL

   # Test if LLM Link is accessible from Claude Code
   curl -H "x-api-key: your-auth-token" http://localhost:8089/health
   ```

5. **Provider Switching Issues**
   ```bash
   # When switching providers, make sure to:
   # 1. Stop the current LLM Link instance
   # 2. Set the correct API key for the new provider
   # 3. Start LLM Link with the new provider

   # Example: Switch from Anthropic to OpenAI
   # Stop current instance (Ctrl+C)
   export OPENAI_API_KEY="sk-xxx"
   ./target/release/llm-link --app claude-code --provider openai --model gpt-4
   ```

## πŸ—οΈ Architecture

### System Overview

```
External Clients (Codex CLI, Zed, Claude Code)
    ↓
API Layer (HTTP API endpoints)
  β€’ HTTP Request Parsing
  β€’ Format Conversion (OpenAI ↔ Ollama ↔ LLM)
  β€’ Authentication & Authorization
    ↓
Adapter Layer (Client-specific adaptations)
  β€’ Standard: No special handling
  β€’ Zed: Add images field
  β€’ OpenAI: finish_reason correction
    ↓
Service Layer (Business logic)
  β€’ Model Selection & Validation
  β€’ Default Model Fallback
    ↓
LLM Layer (LLM communication)
  β€’ LLM Connector Wrapper
  β€’ Stream Management
  β€’ Error Handling
    ↓
LLM Providers (OpenAI, Anthropic, Zhipu, Aliyun, Ollama)
```

### Core Modules

#### 1. API Layer (`src/api/`)

Handles different protocol HTTP requests and responses.

**Modules:**
- `openai.rs` - OpenAI API compatible interface
- `ollama.rs` - Ollama API compatible interface
- `anthropic.rs` - Anthropic API compatible interface (placeholder)
- `convert.rs` - Format conversion utilities
- `mod.rs` - Module exports and common handlers

**Responsibilities:**
- HTTP request parsing
- Format conversion (OpenAI ↔ Ollama ↔ LLM)
- Client type detection
- Authentication and authorization
- Response formatting

#### 2. Adapter Layer (`src/adapters.rs`)

Handles client-specific response adaptations.

**Adapter Types:**
- `Standard` - Standard Ollama client
  - Preferred format: NDJSON
  - Special handling: None
- `Zed` - Zed editor
  - Preferred format: NDJSON
  - Special handling: Add `images` field
- `OpenAI` - OpenAI API client (including Codex CLI)
  - Preferred format: SSE
  - Special handling: finish_reason correction

**Responsibilities:**
- Client type detection (via HTTP headers, User-Agent, configuration)
- Determine preferred streaming format (SSE/NDJSON/JSON)
- Apply client-specific response adaptations

#### 3. Service Layer (`src/service.rs`)

Business logic layer between API and LLM layers.

**Responsibilities:**
- Business logic processing
- Model selection and validation
- Default model fallback
- Delegating to LLM layer methods

#### 4. LLM Layer (`src/llm/`)

LLM communication layer, encapsulates interaction with LLM providers.

**Modules:**
- `mod.rs` - Client struct and constructor
- `types.rs` - Type definitions (Model, Response, Usage)
- `chat.rs` - Non-streaming chat
- `stream.rs` - Streaming chat
- `models.rs` - Model management

**Responsibilities:**
- Encapsulate llm-connector library
- Unified request/response interface
- Stream response management
- Error handling

#### 5. Configuration (`src/settings.rs`)

Application configuration management.

**Configuration Structure:**
```rust
Settings {
    server: ServerSettings,
    llm_backend: LlmBackendSettings,
    apis: ApiSettings,
    client_adapters: ClientAdapterSettings
}
```

#### 6. Application Support (`src/apps/`)

Built-in application configuration generators.

**Supported Applications:**
- Codex CLI - OpenAI API mode
- Zed - Ollama API mode
- Claude Code - Anthropic API mode

**Features:**
- Zero-configuration startup
- Application-specific optimizations
- Automatic protocol selection

### Request Flow

```
1. External Client Request
   ↓
2. API Layer (openai/ollama endpoints)
   β”œβ”€ HTTP Request Parsing
   β”œβ”€ Format Conversion (API β†’ LLM)
   └─ Client Detection
   ↓
3. Service Layer
   β”œβ”€ Business Logic
   └─ Model Selection
   ↓
4. LLM Layer
   β”œβ”€ LLM Connector Wrapper
   └─ Request Formatting
   ↓
5. LLM Provider
```

### Response Flow

```
1. LLM Provider Response
   ↓
2. LLM Layer
   β”œβ”€ Stream Processing
   └─ Error Handling
   ↓
3. Service Layer
   └─ Business Logic
   ↓
4. Adapter Layer
   └─ Client-specific Adaptations
      β€’ Zed: Add images field
      β€’ OpenAI: finish_reason correction
      β€’ Standard: No special handling
   ↓
5. API Layer
   β”œβ”€ Format Conversion (LLM β†’ API)
   └─ HTTP Response Formatting
   ↓
6. External Client
```

### Design Principles

#### 1. Client Auto-Detection

**Detection Priority:**
1. Force adapter setting (`force_adapter`)
2. Explicit client identifier (`x-client` header)
3. User-Agent auto-detection
4. Default adapter setting

**Supported Client Types:**
- `Standard` - Standard Ollama client
- `Zed` - Zed editor
- `OpenAI` - OpenAI API client (including Codex CLI)

**Detection Example:**
```rust
// 1. Configuration force
force_adapter: "zed"

// 2. Header specification
x-client: zed

// 3. User-Agent detection
User-Agent: Zed/1.0.0  β†’ Zed
User-Agent: OpenAI/1.0 β†’ OpenAI
```

#### 2. Application-First Design

Built-in configurations for popular applications, zero manual configuration needed.

**Benefits:**
- One-command startup
- Automatic protocol selection
- Optimized for each application
- Helpful error messages

#### 3. Asynchronous Processing

Uses Tokio async runtime for high concurrency support.

### Performance Considerations

- **Streaming Response**: Real-time data transmission
- **Zero-Copy**: Minimize data copying
- **Async Processing**: High concurrency support

## πŸš€ Development

### Building from Source

```bash
# Clone the repository
git clone https://github.com/lipish/llm-link.git
cd llm-link

# Build for development
cargo build

# Build for production
cargo build --release

# Run tests
cargo test
```

### Project Structure

```
llm-link/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ main.rs              # Application entry point
β”‚   β”œβ”€β”€ settings.rs          # Configuration definitions
β”‚   β”œβ”€β”€ service.rs           # Business logic layer
β”‚   β”œβ”€β”€ adapters.rs          # Client adapters
β”‚   β”œβ”€β”€ api/                 # HTTP API layer
β”‚   β”‚   β”œβ”€β”€ mod.rs          # AppState, common endpoints
β”‚   β”‚   β”œβ”€β”€ convert.rs      # Format conversion utilities
β”‚   β”‚   β”œβ”€β”€ ollama.rs       # Ollama API endpoints
β”‚   β”‚   β”œβ”€β”€ openai.rs       # OpenAI API endpoints
β”‚   β”‚   └── anthropic.rs    # Anthropic API endpoints
β”‚   β”œβ”€β”€ llm/                 # LLM communication layer
β”‚   β”‚   β”œβ”€β”€ mod.rs          # Client struct
β”‚   β”‚   β”œβ”€β”€ types.rs        # Type definitions
β”‚   β”‚   β”œβ”€β”€ chat.rs         # Non-streaming chat
β”‚   β”‚   β”œβ”€β”€ stream.rs       # Streaming chat
β”‚   β”‚   └── models.rs       # Model management
β”‚   β”œβ”€β”€ apps/                # Application config generators
β”‚   └── models/              # Model configurations
β”œβ”€β”€ docs/                    # Documentation
β”œβ”€β”€ tests/                   # Test scripts
β”œβ”€β”€ Cargo.toml              # Rust dependencies
β”œβ”€β”€ README.md               # This file
└── CHANGELOG.md            # Version history
```

### Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests if applicable
5. Submit a pull request

## πŸ“š Documentation

- [Quick Start Guide]docs/QUICK_START.md - Fast reference for common use cases (δΈ­ζ–‡)
- [Changelog]CHANGELOG.md - Version history and updates

## πŸ“„ License

MIT License

## 🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## ⭐ Support

If you find LLM Link helpful, please consider giving it a star on GitHub!

---

**Made with ❀️ for the AI coding**