Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,25 @@ For Qwen3 models where you have controls on whether to enable thinkings, using f
}
```

Reasoning effort can be set through `extraParams` as well, without any code change; it is sent as
the top-level `reasoning_effort` field of the chat completion API:
```json
{
"model": {
"baseUrl": "https://api.deepseek.com",
"model": "deepseek-v4-flash",
"authToken": "<AUTH_TOKEN_HERE>",
"extraParams": {
"reasoning_effort": "high"
}
},
"mcpServers": {...}
}
```
Note that `nah` also sends `temperature`, `frequency_penalty` and `top_p`; providers with a
thinking mode may ignore or clamp some of them (DeepSeek ignores `temperature` and
`frequency_penalty` in thinking mode and raises `top_p` to at least 0.95).

After launching `nah`, it will active all MCP servers declared in the config file and provide a shell-like user interface. Here are some useful commands supported by `nah`.
* `chat`: Chat with a LLM with all tools installed.
* `use`: Select a MCP server to interactive with.
Expand Down
8 changes: 8 additions & 0 deletions nah_chat/CHANGELOG
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
CHANGELOG of nah_chat
===
## Unreleased
* `ChatCompletionParamsBuilder::reasoning_effort()` sets the top-level `reasoning_effort`
parameter of the chat completion API.
* `ResponsesParamsBuilder::reasoning_effort()` sets `reasoning.effort` of the Responses API,
merging into an existing `reasoning` object (other keys, e.g. `summary`, are preserved).
* Additive only — `insert()` / `reasoning(Value)` behaviour is unchanged; no new public types and
no version bump.

## v0.8.0
* Add token usage support to the chat completion stream. `chat_completion_stream` now yields
`ChatCompletionStreamEvent` (`Delta` / `Usage`) instead of `ChatResponseChunkDelta` — **breaking
Expand Down
40 changes: 40 additions & 0 deletions nah_chat/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ Supported features:
* Stream generation
* Tool calls
* Reasoning content (Qwen3, Deepseek R1, etc)
* Reasoning effort control (`reasoning_effort` in the chat completion API, `reasoning.effort` in
the Responses API)
* Token usage in the chat completion stream (via `stream_options.include_usage`)
* Responses API (stream + non-stream, tool calls, reasoning)
This crate is built on top of `reqwest` and `serde_json`.
Expand Down Expand Up @@ -62,6 +64,44 @@ event, yielded after the final delta and right before `[DONE]`. Consumers should
all fields are optional (`Option<u64>` + `#[serde(default)]`), so partial provider responses
deserialize; DeepSeek-specific extras are ignored.

### Reasoning effort

The two APIs spell the reasoning effort hint differently:

| API | Request field | Typical values |
|---|---|---|
| Chat completion | `reasoning_effort` (top level) | `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max` |
| Responses | `reasoning.effort` (nested in `reasoning`) | same |

```rust
use nah_chat::{ChatCompletionParamsBuilder, ResponsesParamsBuilder};

let mut params = ChatCompletionParamsBuilder::new();
params.max_tokens(4096).reasoning_effort("high");

let mut params = ResponsesParamsBuilder::new();
params.reasoning_effort("high");
```

The string is sent verbatim, so provider-specific values keep working; which values a model accepts
is model-dependent, and an unsupported value is rejected by the server (HTTP 400).
`reasoning_effort` merges into an existing `reasoning` object, so it can be combined with the raw
setter: `params.reasoning(serde_json::json!({"summary": "auto"})).reasoning_effort("high")`.

**DeepSeek thinking mode**: the effort is `low` / `high` / `max` (other values are mapped by the
server, e.g. `medium` -> `high`); thinking itself is toggled by a separate field — `thinking:
{"type": "enabled" | "disabled"}` in the chat completion API, or `reasoning.effort: "none"` in the
Responses API. Pass the toggle through the escape hatch:

```rust
let mut params = ChatCompletionParamsBuilder::new();
params.reasoning_effort("max");
params.insert("thinking", serde_json::json!({"type": "enabled"}));
```

In DeepSeek thinking mode `temperature`, `frequency_penalty` and `presence_penalty` have no effect
and `top_p` is clamped to >= 0.95.

## Responses API

The [Responses API](https://platform.openai.com/docs/api-reference/responses) is supported via
Expand Down
96 changes: 96 additions & 0 deletions nah_chat/examples/reasoning_effort.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/

//! Reasoning effort demo for both the chat completion API (`reasoning_effort`)
//! and the Responses API (`reasoning.effort`). DeepSeek's thinking mode is on by
//! default, so both calls should print a chain of thought.
//!
//! Run with:
//! DEEPSEEK_API_KEY=... cargo run -p nah_chat --example reasoning_effort

use futures_util::{StreamExt, pin_mut};
use nah_chat::{
ChatClient, ChatCompletionParamsBuilder, ChatCompletionStreamEvent, ChatMessage, ResponsesInput,
ResponsesParamsBuilder, ResponsesStreamEvent,
};
use std::io::Write;

#[tokio::main(flavor = "current_thread")]
async fn main() -> std::io::Result<()> {
let auth_token = std::env::var("DEEPSEEK_API_KEY").unwrap();
let base_url =
std::env::var("BASE_URL").unwrap_or_else(|_| "https://api.deepseek.com".to_string());
let model = std::env::var("MODEL").unwrap_or_else(|_| "deepseek-v4-flash".to_string());
let client = ChatClient::init(base_url, Some(auth_token));

println!("== Chat completion API: reasoning_effort ==");
let messages = vec![ChatMessage::user_text_message(
"9.11 and 9.8, which is greater? Answer with the number only.",
)];
let mut params = ChatCompletionParamsBuilder::new();
params.reasoning_effort("high").include_usage();
let stream = client
.chat_completion_stream(&model, &messages, &params)
.await
.unwrap();
pin_mut!(stream);
let mut message = ChatMessage::new();
while let Some(event) = stream.next().await {
match event.unwrap() {
ChatCompletionStreamEvent::Delta(delta) => message.apply_model_response_chunk(delta),
ChatCompletionStreamEvent::Usage(usage) => println!(
"\n[usage] prompt={:?} completion={:?} reasoning_tokens={:?}",
usage.prompt_tokens,
usage.completion_tokens,
usage
.completion_tokens_details
.as_ref()
.and_then(|d| d.reasoning_tokens)
),
}
}
match &message.reasoning_content {
Some(reasoning) => println!("[reasoning] {} chars of chain of thought", reasoning.len()),
None => println!("[reasoning] none returned"),
}
println!("[answer] {}", message.content);

println!("== Responses API: reasoning.effort ==");
let input = ResponsesInput::Text("9.11 and 9.8, which is greater?".to_string());
let mut params = ResponsesParamsBuilder::new();
params
.instructions("You are a helpful assistant.")
.reasoning_effort("high");
let stream = client
.responses_stream(&model, &input, &params)
.await
.unwrap();
pin_mut!(stream);
while let Some(event) = stream.next().await {
match event.unwrap() {
ResponsesStreamEvent::ReasoningTextDelta { delta, .. } => eprint!("{}", delta),
ResponsesStreamEvent::OutputTextDelta { delta, .. } => {
print!("{}", delta);
let _ = std::io::stdout().flush();
}
ResponsesStreamEvent::Completed(response) => println!(
"\n[completed] status={}, reasoning_tokens={:?}",
response.status,
response
.usage
.as_ref()
.and_then(|u| u.output_tokens_details.as_ref())
.and_then(|d| d.reasoning_tokens)
),
ResponsesStreamEvent::Incomplete(response) => {
println!("\n[incomplete] status={}", response.status)
}
ResponsesStreamEvent::Failed(response) => println!("\n[failed] error={:?}", response.error),
_ => {}
}
}
Ok(())
}
2 changes: 1 addition & 1 deletion nah_chat/examples/responses.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ async fn main() -> std::io::Result<()> {
let mut params = ResponsesParamsBuilder::new();
params
.instructions("You are a helpful assistant.")
.reasoning(serde_json::json!({"effort": "high"}));
.reasoning_effort("high");

println!("== Non-stream ==");
let response = client.responses(&model, &input, &params).await.unwrap();
Expand Down
23 changes: 23 additions & 0 deletions nah_chat/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
//! * Stream generation
//! * Tool calls
//! * Reasoning content (Qwen3, Deepseek R1, etc)
//! * Reasoning effort control (`reasoning_effort` in the chat completion API,
//! `reasoning.effort` in the Responses API)
//! * Token usage in the chat completion stream (via `stream_options.include_usage`)
//! * Responses API (stream + non-stream, tool calls, reasoning)
//!
Expand Down Expand Up @@ -146,6 +148,27 @@ impl ChatCompletionParamsBuilder {
self
}

/**
* Set the `reasoning_effort` parameter of the chat completion API.
*
* The value is sent verbatim and validated by the server: OpenAI reasoning
* models take `none` / `minimal` / `low` / `medium` / `high` / `xhigh` /
* `max`, DeepSeek takes `low` / `high` / `max`. Which values are accepted is
* model-dependent.
*
* This is the chat completion spelling (a top-level field); the Responses API
* nests the same setting as `reasoning.effort` (see
* [ResponsesParamsBuilder::reasoning_effort]). Providers that additionally
* need a thinking mode toggle (DeepSeek `thinking`, Qwen3 `enable_thinking`)
* can be configured with [ChatCompletionParamsBuilder::insert].
*/
pub fn reasoning_effort(&mut self, effort: &str) -> &mut Self {
self
.data
.insert("reasoning_effort".to_owned(), json!(effort));
self
}

/**
* Set a parameter with key of `name` and value of `value`.
*/
Expand Down
44 changes: 44 additions & 0 deletions nah_chat/src/responses.rs
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,28 @@ impl ResponsesParamsBuilder {
self
}

/**
* Set the `reasoning.effort` parameter — the Responses API spelling of the
* chat completion `reasoning_effort` parameter.
*
* The value is sent verbatim and validated by the server (DeepSeek takes
* `low` / `high` / `max`, and uses `"none"` to disable thinking mode). Only
* `effort` is written: other keys of an existing `reasoning` object
* (e.g. `summary`, `mode`) are preserved, so this can be combined with
* [ResponsesParamsBuilder::reasoning].
*/
pub fn reasoning_effort(&mut self, effort: &str) -> &mut Self {
let mut reasoning = match self.data.remove("reasoning") {
Some(Value::Object(object)) => object,
_ => serde_json::Map::new(),
};
reasoning.insert("effort".to_owned(), json!(effort));
self
.data
.insert("reasoning".to_owned(), Value::Object(reasoning));
self
}

/** Set the `text` parameter, e.g. `json!({"format": {"type": "json_object"}})`. */
pub fn text(&mut self, text: Value) -> &mut Self {
self.data.insert("text".to_owned(), text);
Expand Down Expand Up @@ -1096,6 +1118,28 @@ data: {\"sequence_number\":1,\"foo\":\"bar\"}
assert_eq!(data.len(), 7);
}

#[test]
fn test_responses_reasoning_effort_merges_into_existing_object() {
// effort after a raw reasoning object: the other keys survive
let mut params = ResponsesParamsBuilder::new();
params
.reasoning(serde_json::json!({"summary": "detailed"}))
.reasoning_effort("max");
let data = params.build();
assert_eq!(data["reasoning"]["effort"], "max");
assert_eq!(data["reasoning"]["summary"], "detailed");

// reasoning(Value) stays a whole-object setter (documented, unchanged) and
// therefore replaces a previously set effort.
let mut params = ResponsesParamsBuilder::new();
params
.reasoning_effort("low")
.reasoning(serde_json::json!({"summary": "auto"}));
let data = params.build();
assert_eq!(data["reasoning"]["summary"], "auto");
assert!(data["reasoning"].get("effort").is_none());
}

#[test]
fn test_serialize_input_text() {
let input = ResponsesInput::Text("Hi".to_string());
Expand Down
58 changes: 58 additions & 0 deletions nah_chat/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,43 @@ fn test_chat_completion_params_builder() {
assert_eq!(params.len(), 5);
}

#[test]
fn test_chat_completion_params_builder_reasoning_effort() {
let mut params = ChatCompletionParamsBuilder::new();
params.reasoning_effort("high");
assert_eq!(params.build()["reasoning_effort"], "high");

// The value is passed through verbatim (provider-specific / future values).
let mut params = ChatCompletionParamsBuilder::new();
params.reasoning_effort("max");
assert_eq!(params.build()["reasoning_effort"], "max");

// Absent by default: the field must never be sent unless asked for.
assert!(
!ChatCompletionParamsBuilder::new()
.build()
.contains_key("reasoning_effort")
);
}

#[test]
fn test_chat_completion_request_body_reasoning_effort() {
let client = ChatClient::init("https://api.deepseek.com".to_string(), None);
let messages = vec![ChatMessage::user_text_message("Hi")];
let mut params = ChatCompletionParamsBuilder::new();
params.reasoning_effort("high");
let req = client
.create_chat_completion_request("deepseek-chat", &messages, true, &params)
.build()
.unwrap();
let body: serde_json::Value =
serde_json::from_slice(req.body().unwrap().as_bytes().unwrap()).unwrap();
assert_eq!(body["reasoning_effort"], "high");
// The chat completions API is FLAT: no nested `reasoning` object (that is the
// Responses API spelling and would be ignored here).
assert!(body.get("reasoning").is_none());
}

#[test]
fn test_collect_chat_response_chunk_delta() {
let delta = vec![
Expand Down Expand Up @@ -206,6 +243,27 @@ fn test_responses_request_body() {
assert_eq!(body["reasoning"]["effort"], "high");
}

#[test]
fn test_responses_request_body_reasoning_effort() {
use crate::responses::{ResponsesInput, ResponsesParamsBuilder};
let client = ChatClient::init("https://api.deepseek.com".to_string(), None);
let mut params = ResponsesParamsBuilder::new();
params
.instructions("You are helpful.")
.reasoning_effort("high");
let input = ResponsesInput::Text("Hi".to_string());
let req = client
.create_responses_request("deepseek-v4-flash", &input, false, &params)
.build()
.unwrap();
let body: serde_json::Value =
serde_json::from_slice(req.body().unwrap().as_bytes().unwrap()).unwrap();
assert_eq!(body["reasoning"]["effort"], "high");
// The Responses API nests the effort under `reasoning`; the flat field is the
// chat completion spelling and would be ignored here.
assert!(body.get("reasoning_effort").is_none());
}

#[test]
fn test_chat_stream_chunk_split_reassembly() {
// SSE events split across network chunks must not be lost.
Expand Down
Loading