diff --git a/README.md b/README.md index c505784..d299c29 100644 --- a/README.md +++ b/README.md @@ -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": "", + "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. diff --git a/nah_chat/CHANGELOG b/nah_chat/CHANGELOG index 47a4e4f..2f82e89 100644 --- a/nah_chat/CHANGELOG +++ b/nah_chat/CHANGELOG @@ -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 diff --git a/nah_chat/README.md b/nah_chat/README.md index 4350a46..775c0ff 100644 --- a/nah_chat/README.md +++ b/nah_chat/README.md @@ -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`. @@ -62,6 +64,44 @@ event, yielded after the final delta and right before `[DONE]`. Consumers should all fields are optional (`Option` + `#[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 diff --git a/nah_chat/examples/reasoning_effort.rs b/nah_chat/examples/reasoning_effort.rs new file mode 100644 index 0000000..10e2d05 --- /dev/null +++ b/nah_chat/examples/reasoning_effort.rs @@ -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, ¶ms) + .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, ¶ms) + .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(()) +} diff --git a/nah_chat/examples/responses.rs b/nah_chat/examples/responses.rs index 0045921..b3d328e 100644 --- a/nah_chat/examples/responses.rs +++ b/nah_chat/examples/responses.rs @@ -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, ¶ms).await.unwrap(); diff --git a/nah_chat/src/lib.rs b/nah_chat/src/lib.rs index 085c707..8b9dee7 100644 --- a/nah_chat/src/lib.rs +++ b/nah_chat/src/lib.rs @@ -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) //! @@ -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`. */ diff --git a/nah_chat/src/responses.rs b/nah_chat/src/responses.rs index 969b287..e7dcba9 100644 --- a/nah_chat/src/responses.rs +++ b/nah_chat/src/responses.rs @@ -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); @@ -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()); diff --git a/nah_chat/src/tests.rs b/nah_chat/src/tests.rs index 84ca0ef..b5f7937 100644 --- a/nah_chat/src/tests.rs +++ b/nah_chat/src/tests.rs @@ -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, ¶ms) + .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![ @@ -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, ¶ms) + .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.