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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
**/target
Cargo.lock
.hermes/
6 changes: 6 additions & 0 deletions nah_chat/CHANGELOG
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
CHANGELOG of nah_chat
===
## v0.7.0
* Add OpenAI Responses API support: `responses()`, `responses_stream()`, `create_responses_request()`,
`ResponsesInput`, `ResponseInputItem`, `ResponseOutputItem`, `ResponseObject`, `ResponseUsage`,
`ResponsesStreamEvent`, `ResponsesParamsBuilder`.
* Fix infinite loop in `chat_completion_stream` when the server closes the connection without sending `data: [DONE]`.

## v0.5.0
* Fix `max_tokens` parameter name
* Implement `FromIterator`, `Default` and `Extend` for `ChatMessage`.
Expand Down
4 changes: 2 additions & 2 deletions nah_chat/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
[package]
name = "nah_chat"
version = "0.6.0"
version = "0.7.0"
edition = "2024"
license = "MPL-2.0"
description = "Lightweight LLM chat completion API."
homepage = "https://github.com/linmx0130/nah"
repository = "https://github.com/linmx0130/nah"
keywords = ["llm","chat_completion", "openai"]
keywords = ["llm", "chat_completion", "responses", "openai"]
readme = "README.md"

[dependencies]
Expand Down
15 changes: 14 additions & 1 deletion nah_chat/README.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
# Introduction
This crate exposes an async stream API for the widely-used OpenAI
[chat completion API](https://platform.openai.com/docs/api-reference/chat).
[chat completion API](https://platform.openai.com/docs/api-reference/chat) and the
[Responses API](https://platform.openai.com/docs/api-reference/responses).

Supported features:
* Stream generation
* Tool calls
* Reasoning content (Qwen3, Deepseek R1, etc)
* Responses API (stream + non-stream, tool calls, reasoning)
This crate is built on top of `reqwest` and `serde_json`.

```rust
Expand Down Expand Up @@ -37,6 +39,17 @@ while let Some(delta_result) = stream.next().await {
}
```

## Responses API

The [Responses API](https://platform.openai.com/docs/api-reference/responses) is supported via
`responses()` (non-stream) and `responses_stream()` (SSE event stream). The endpoint is
`{base_url}/responses` — for DeepSeek use `https://api.deepseek.com`, for OpenAI use
`https://api.openai.com/v1` (the base URL must not end with `/`).

The stream yields typed `ResponsesStreamEvent`s and terminates on `response.completed` /
`response.incomplete` / `response.failed` (no `data: [DONE]`). See `examples/responses.rs`
and `examples/responses_tool.rs` for runnable examples.

# Notice
Copyright 2025, [Mengxiao Lin](linmx0130@gmail.com).
This is a part of [nah](https://github.com/linmx0130/nah) project. `nah` means "*N*ot *A*
Expand Down
74 changes: 74 additions & 0 deletions nah_chat/examples/responses.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/*
* 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/.
*/

use futures_util::{StreamExt, pin_mut};
use nah_chat::{ChatClient, 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));
let input =
ResponsesInput::Text("Hi, how are you? Please introduce yourself in one sentence.".to_string());
let mut params = ResponsesParamsBuilder::new();
params
.instructions("You are a helpful assistant.")
.reasoning(serde_json::json!({"effort": "high"}));

println!("== Non-stream ==");
let response = client.responses(&model, &input, &params).await.unwrap();
println!("{}", response.output_text());
if let Some(usage) = &response.usage {
println!(
"usage: input={:?} output={:?} total={:?} (reasoning_tokens={:?})",
usage.input_tokens,
usage.output_tokens,
usage.total_tokens,
usage
.output_tokens_details
.as_ref()
.and_then(|d| d.reasoning_tokens)
);
}

println!("== Stream ==");
let stream = client
.responses_stream(&model, &input, &params)
.await
.unwrap();
pin_mut!(stream);
while let Some(event_result) = stream.next().await {
match event_result.unwrap() {
ResponsesStreamEvent::ReasoningTextDelta { delta, .. } => {
eprint!("{}", delta);
}
ResponsesStreamEvent::OutputTextDelta { delta, .. } => {
print!("{}", delta);
let _ = std::io::stdout().flush();
}
ResponsesStreamEvent::Completed(response) => {
println!(
"\n[completed] status={}, total_tokens={:?}",
response.status,
response.usage.as_ref().and_then(|u| u.total_tokens)
);
}
ResponsesStreamEvent::Incomplete(response) => {
println!("\n[incomplete] status={}", response.status);
}
ResponsesStreamEvent::Failed(response) => {
println!("\n[failed] error={:?}", response.error);
}
_ => {}
}
}
Ok(())
}
75 changes: 75 additions & 0 deletions nah_chat/examples/responses_tool.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/*
* 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/.
*/

use futures_util::{StreamExt, pin_mut};
use nah_chat::{ChatClient, ResponsesInput, ResponsesParamsBuilder, ResponsesStreamEvent};
use serde_json::json;
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));

// The Responses API tool format is FLAT: {"type":"function","name":...,"parameters":...}
let tools = json!([{
"type": "function",
"name": "get_weather",
"description": "Get the weather of a city",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"]
}
}]);

let mut params = ResponsesParamsBuilder::new();
params
.instructions("You are a helpful assistant.")
.tools(tools)
.tool_choice(json!("auto"));

let input = ResponsesInput::Text("What is the weather in San Francisco?".to_string());
let stream = client
.responses_stream(&model, &input, &params)
.await
.unwrap();
pin_mut!(stream);
while let Some(event_result) = stream.next().await {
match event_result.unwrap() {
ResponsesStreamEvent::FunctionCallArgumentsDelta { delta, .. } => {
eprint!("{}", delta);
let _ = std::io::stdout().flush();
}
ResponsesStreamEvent::OutputTextDelta { delta, .. } => {
print!("{}", delta);
let _ = std::io::stdout().flush();
}
ResponsesStreamEvent::Completed(response) => {
println!("\n[completed] status={}", response.status);
for call in response.function_calls() {
println!(
"[function_call] name={} arguments={}",
call.name.as_deref().unwrap_or(""),
call.arguments.as_deref().unwrap_or("")
);
}
}
ResponsesStreamEvent::Incomplete(response) => {
println!("\n[incomplete] status={}", response.status)
}
ResponsesStreamEvent::Failed(response) => {
println!("\n[failed] error={:?}", response.error)
}
_ => {}
}
}
Ok(())
}
8 changes: 6 additions & 2 deletions nah_chat/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@
//!
//! # Introduction
//! This crate exposes an async stream API for the widely-used OpenAI
//! [chat completion API](https://platform.openai.com/docs/api-reference/chat).
//! [chat completion API](https://platform.openai.com/docs/api-reference/chat) and the
//! [Responses API](https://platform.openai.com/docs/api-reference/responses).
//!
//! Supported features:
//! * Stream generation
//! * Tool calls
//! * Reasoning content (Qwen3, Deepseek R1, etc)
//! * Responses API (stream + non-stream, tool calls, reasoning)
//!
//! This crate is built on top of `tokio`, `reqwest` and `serde_json`.
//!
Expand Down Expand Up @@ -59,8 +61,10 @@
//!
mod error;
mod message;
mod responses;
pub use error::{Error, ErrorKind, Result};
pub use message::*;
pub use responses::*;

use async_stream::stream;
use futures_core::stream::Stream;
Expand Down Expand Up @@ -327,7 +331,7 @@ impl ChatClient {
let mut reach_done = false;
while !reach_done {
let Some(chunk_data) = res.chunk().await? else {
continue;
break;
};
let chunk_data_str = match String::from_utf8(chunk_data.to_vec()) {
Ok(v) => v,
Expand Down
Loading
Loading