samvadsetu 1.0.0

Multi-provider LLM API client for Gemini, ChatGPT, Claude, DeepSeek, Qwen, Ollama, and llama.cpp. Supports tool calling, logprobs, structured output, and batch processing. The name implies a bridge for dialogue: Sanskrit saṃvāda (संवाद) = dialogue, setu (सेतु) = bridge.
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
# samvadsetu | संवाद-सेतु

[![Crates.io](https://img.shields.io/crates/v/samvadsetu.svg)](https://crates.io/crates/samvadsetu)
[![Docs.rs](https://docs.rs/samvadsetu/badge.svg)](https://docs.rs/samvadsetu)
[![CI](https://github.com/sandeep-sandhu/samvadsetu/workflows/CI/badge.svg)](https://github.com/sandeep-sandhu/samvadsetu/actions)

A Rust-native library for sending chat-completion requests to multiple LLM providers through a single, unified API.

**Sanskrit**: saṃvāda (संवाद) = dialogue · setu (सेतु) = bridge.

---

## Supported Providers

| Provider | `llm_service` string | Auth env var | Batch API |
|---|---|---|---|
| OpenAI / ChatGPT | `"chatgpt"` / `"openai"` | `OPENAI_API_KEY` ||
| DeepSeek | `"deepseek"` | `DEEPSEEK_API_KEY` ||
| Alibaba Qwen (DashScope) | `"qwen"` | `DASHSCOPE_API_KEY` ||
| llama.cpp server | `"llamacpp"` | `LLAMACPP_API_KEY` (opt.) ||
| Anthropic Claude | `"claude"` / `"anthropic"` | `ANTHROPIC_API_KEY` ||
| Google Gemini (legacy) | `"gemini"` | `GOOGLE_API_KEY` ||
| Google GenAI | `"google_genai"` | `GOOGLE_API_KEY` ||
| Ollama (local) | `"ollama"` | _(none)_ ||

---

## Installation

```toml
[dependencies]
samvadsetu = "0.2"
```

Optional async support (future):

```toml
samvadsetu = { version = "0.2", features = ["async"] }
```

---

## Quick Start

```rust
use samvadsetu::llm::LLMTextGenBuilder;
use samvadsetu::types::ChatMessage;

fn main() {
    let llm_gen = LLMTextGenBuilder::build("chatgpt", "gpt-4o-mini", 60, None, None)
        .expect("build failed — is OPENAI_API_KEY set?");

    let messages = vec![
        ChatMessage::system("You are a helpful assistant."),
        ChatMessage::user("How is a rainbow formed? Reply in one sentence."),
    ];

    let result = llm_gen.generate_text(&messages, None, None)
        .expect("API call failed");

    println!("{}", result.generated_text);
}
```

Set the API key in your environment before running:

```bash
export OPENAI_API_KEY="sk-..."
```

---

## Core Types

### `ChatMessage` — Building conversations

```rust
use samvadsetu::types::ChatMessage;

// Convenience constructors:
let msg = ChatMessage::system("You are a helpful assistant.");
let msg = ChatMessage::user("What is the capital of France?");
let msg = ChatMessage::assistant("Paris.");

// Returning a tool result to the model:
let msg = ChatMessage::tool_result("call_abc123", "get_weather", "Sunny, 22°C");

// Building an assistant message that made tool calls:
use samvadsetu::types::ToolCall;
use serde_json::json;
let msg = ChatMessage::assistant_with_tool_calls(vec![ToolCall {
    id: "call_abc123".into(),
    name: "get_weather".into(),
    arguments: json!({"city": "Paris"}),
}]);
```

### `LlmApiResult` — What you get back

```rust
use samvadsetu::types::LlmApiResult;

let result: LlmApiResult = /* ... */;

println!("Text:  {}", result.generated_text);
println!("Input tokens:  {}", result.input_tokens_count);
println!("Output tokens: {}", result.output_tokens_count);
println!("Stop reason: {:?}", result.stop_reason);
println!("Model: {}", result.model_used);

// Tool calls the model wants to make:
for tc in &result.tool_calls {
    println!("Call {} → {}({:?})", tc.id, tc.name, tc.arguments);
}

// Chain-of-thought (DeepSeek R1, Ollama `think`, Claude with thinking):
if let Some(cot) = &result.reasoning_content {
    println!("Reasoning: {cot}");
}
```

---

## Feature: Token Log-Probabilities (Hallucination Proxy)

Token log-probabilities are returned by OpenAI-family models (ChatGPT, DeepSeek,
Qwen, llama.cpp) and newer Gemini models.  Claude does **not** support logprobs.

```rust
use samvadsetu::llm::LLMTextGenBuilder;
use samvadsetu::types::ChatMessage;

let llm_gen = LLMTextGenBuilder::build("chatgpt", "gpt-4o-mini", 60, None, None).unwrap();
let messages = vec![ChatMessage::user("Who invented the telephone?")];

let result = llm_gen.generate_text(&messages, None, None).unwrap();

// Aggregate confidence metrics:
if let Some(mean_p) = result.mean_probability() {
    println!("Mean token confidence: {:.1}%", mean_p * 100.0);
}
if let Some(min_p) = result.min_token_probability() {
    println!("Weakest token: {:.1}% (hallucination hotspot)", min_p * 100.0);
}

// Per-token breakdown:
for lp in &result.logprobs {
    println!(
        "  token={:?}  logprob={:.3}  p={:.1}%",
        lp.token, lp.logprob,
        lp.probability() * 100.0
    );
    for alt in &lp.top_alternatives {
        println!("    alt={:?}  logprob={:.3}", alt.token, alt.logprob);
    }
}
```

> **Rule of thumb**: `mean_probability` > 0.9 generally indicates high-confidence
> generation; values < 0.7 warrant extra scrutiny.

---

## Feature: Tool Calling / Function Calling

```rust
use samvadsetu::llm::LLMTextGenBuilder;
use samvadsetu::types::{ChatMessage, ToolDefinition};
use serde_json::json;

let llm_gen = LLMTextGenBuilder::build("chatgpt", "gpt-4o-mini", 60, None, None).unwrap();

let tools = vec![
    ToolDefinition::new(
        "get_weather",
        "Returns current weather for a city.",
        json!({
            "type": "object",
            "properties": {
                "city": {"type": "string", "description": "City name"}
            },
            "required": ["city"]
        }),
    ),
];

let mut messages = vec![ChatMessage::user("What's the weather in Tokyo?")];

// First turn: model requests a tool call
let r1 = llm_gen.generate_text(&messages, Some(&tools), None).unwrap();

for tc in &r1.tool_calls {
    println!("Model wants: {}({:?})", tc.name, tc.arguments);

    // Execute the tool yourself, then add the result to the conversation:
    messages.push(ChatMessage::assistant_with_tool_calls(r1.tool_calls.clone()));
    messages.push(ChatMessage::tool_result(&tc.id, &tc.name, "Sunny, 25°C"));
}

// Second turn: model uses the tool result to answer
let r2 = llm_gen.generate_text(&messages, Some(&tools), None).unwrap();
println!("{}", r2.generated_text);
```

---

## Feature: Structured Output / JSON Mode

```rust
use samvadsetu::types::ResponseFormat;
use serde_json::json;

// JSON Object mode (model must output valid JSON; you define the shape in the prompt)
let result = llm_gen.generate_text(&messages, None, Some(&ResponseFormat::JsonObject)).unwrap();

// JSON Schema mode (model output is constrained to match your schema)
let schema = json!({
    "type": "object",
    "properties": {
        "name":  {"type": "string"},
        "score": {"type": "number"}
    },
    "required": ["name", "score"]
});
let fmt = ResponseFormat::JsonSchema {
    schema,
    name: Some("PersonScore".to_string()),
};
let result = llm_gen.generate_text(&messages, None, Some(&fmt)).unwrap();
let parsed: serde_json::Value = serde_json::from_str(&result.generated_text).unwrap();
```

> JSON Schema mode is fully supported by OpenAI (structured outputs), llama.cpp,
> and Ollama.  DeepSeek and Qwen support JSON object mode.  Gemini supports
> both via `response_mime_type` and `response_schema`.

---

## Feature: Batch Processing

Batch APIs let you submit hundreds or thousands of requests at lower cost and
process the results asynchronously (OpenAI: up to 50 % cost reduction; Anthropic: 50 %).

```rust
use samvadsetu::llm::LLMTextGenBuilder;
use samvadsetu::types::{BatchRequest, BatchStatus, ChatMessage};
use std::time::Duration;

let llm_gen = LLMTextGenBuilder::build("chatgpt", "gpt-4o-mini", 60, None, None).unwrap();

let requests = vec![
    BatchRequest::new("req-1", vec![ChatMessage::user("What is 1 + 1?")]),
    BatchRequest::new("req-2", vec![ChatMessage::user("What is the capital of Spain?")]),
];

// Submit
let mut handle = llm_gen.submit_batch(requests).unwrap();
println!("Batch submitted: {}", handle.batch_id);

// Poll until complete
loop {
    std::thread::sleep(Duration::from_secs(30));
    handle = llm_gen.check_batch_status(&handle).unwrap();
    println!("Status: {:?}", handle.status);
    if handle.status.is_terminal() {
        break;
    }
}

// Retrieve results
if handle.status == BatchStatus::Completed {
    for item in llm_gen.retrieve_batch_results(&handle).unwrap() {
        match item.result {
            Ok(r)  => println!("[{}] {}", item.custom_id, r.generated_text),
            Err(e) => println!("[{}] ERROR: {e}", item.custom_id),
        }
    }
}
```

---

## Configuration via TOML File

```toml
# app_config.toml

[llm_apis.chatgpt]
model_name         = "gpt-4o-mini"
api_url            = "https://api.openai.com/v1/chat/completions"
temperature        = 0.0
max_gen_tokens     = 8192
max_context_len    = 16384
model_api_timeout  = 120
system_prompt      = "You are a helpful assistant."

[llm_apis.claude]
model_name         = "claude-haiku-4-5"
api_url            = "https://api.anthropic.com/v1/messages"
temperature        = 0.0
max_gen_tokens     = 4096
model_api_timeout  = 120

[llm_apis.ollama]
model_name         = "llama3.2"
api_url            = "http://localhost:11434/api/chat"
temperature        = 0.0
max_gen_tokens     = 4096
max_context_len    = 8192
min_gap_btwn_rqsts_secs = 0
```

```rust
use config::{Config, FileFormat};
use samvadsetu::llm::LLMTextGenBuilder;
use samvadsetu::types::ChatMessage;

let app_config = Config::builder()
    .add_source(config::File::new("app_config.toml", FileFormat::Toml))
    .build()
    .expect("Failed to load config");

let llm_gen = LLMTextGenBuilder::build_from_config(&app_config, "chatgpt")
    .expect("Failed to build LLM generator from config");

let messages = vec![ChatMessage::user("Hello!")];
let result = llm_gen.generate_text(&messages, None, None).unwrap();
println!("{}", result.generated_text);
```

---

## Multi-Turn Conversation

The library is stateless — callers own the message history:

```rust
let mut history: Vec<ChatMessage> = vec![
    ChatMessage::system("You are a friendly tutor."),
];

loop {
    let user_input = /* read from stdin */;
    history.push(ChatMessage::user(&user_input));

    let result = llm_gen.generate_text(&history, None, None).unwrap();
    println!("Assistant: {}", result.generated_text);

    history.push(ChatMessage::assistant(&result.generated_text));
}
```

---

## Using Different Providers

```rust
use samvadsetu::llm::LLMTextGenBuilder;
use samvadsetu::types::ChatMessage;

// DeepSeek (OpenAI-compatible)
let llm_gen = LLMTextGenBuilder::build("deepseek", "deepseek-v4-pro", 60, None, None).unwrap();

// Qwen (DashScope, Singapore region by default; override api_url for other regions)
let llm_gen = LLMTextGenBuilder::build("qwen", "qwen-plus", 60, None, None).unwrap();

// Anthropic Claude (no logprobs available)
let llm_gen = LLMTextGenBuilder::build("claude", "claude-haiku-4-5", 60, None, None).unwrap();

// Local llama.cpp server
let mut llm_gen = LLMTextGenBuilder::build("llamacpp", "llama-3.2-3b", 60, None, None).unwrap();
llm_gen.svc_base_url = "http://192.168.1.100:8080/v1/chat/completions".to_string();

// Local Ollama
let mut llm_gen = LLMTextGenBuilder::build("ollama", "gemma3", 60, None, None).unwrap();
llm_gen.svc_base_url = "http://10.13.31.113:11434/api/chat".to_string();
```

---

## Rate Limiting (Multi-threaded)

```rust
use std::sync::{Arc, Mutex};
use samvadsetu::llm::LLMTextGenBuilder;

// Share a mutex across threads; calls will be spaced at least 6 seconds apart.
let rate_limit_mutex = Arc::new(Mutex::new(0isize));

let llm_gen = LLMTextGenBuilder::build(
    "chatgpt",
    "gpt-4o-mini",
    60,
    None,
    Some(Arc::clone(&rate_limit_mutex)),
).unwrap();
```

---

## Error Handling

All errors return `SamvadSetuError`:

```rust
use samvadsetu::error::SamvadSetuError;

match llm_gen.generate_text(&messages, None, None) {
    Ok(result) => println!("{}", result.generated_text),
    Err(SamvadSetuError::RateLimit { retry_after_secs, message }) => {
        if let Some(secs) = retry_after_secs {
            eprintln!("Rate limited. Retry after {secs}s: {message}");
        }
    }
    Err(SamvadSetuError::Auth(msg)) => {
        eprintln!("Authentication failed — check your API key: {msg}");
    }
    Err(SamvadSetuError::Provider { error_type, message, code, .. }) => {
        eprintln!("Provider error [{error_type}] {code:?}: {message}");
    }
    Err(SamvadSetuError::Timeout) => {
        eprintln!("Request timed out — increase network_timeout_secs");
    }
    Err(SamvadSetuError::UnsupportedFeature { provider, feature }) => {
        eprintln!("{provider} does not support {feature}");
    }
    Err(e) => eprintln!("Error: {e}"),
}
```

---

## Provider Capability Matrix

| Feature | ChatGPT | DeepSeek | Qwen | Claude | Gemini | Ollama | llama.cpp |
|---|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
| Chat completions ||||||||
| Tool calling ||||||||
| Token logprobs ||||||||
| JSON object mode ||||||||
| JSON schema ||||||||
| Batch API ||||||||
| Chain-of-thought ||||||||

> Claude does not return logprobs via its API — `result.logprobs` will be empty
> and `result.mean_probability()` will return `None`.

---

## License

Licensed under either of:

- Apache License, Version 2.0 ([LICENSE-APACHE]LICENSE-APACHE)
- MIT License ([LICENSE-MIT]LICENSE-MIT)

at your option.

## Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

See [CONTRIBUTING.md](CONTRIBUTING.md).