deepseek/agent/
builder.rs1use std::sync::Arc;
6
7use futures::StreamExt;
8
9use crate::client::HttpClient;
10use crate::error::{DeepSeekError, Result};
11
12use super::loop_runner::run;
13use super::messages::{ResultSubtype, SdkMessage};
14use super::options::RunOptions;
15use super::tool::Tool;
16
17pub struct AgentBuilder<H: HttpClient> {
19 http: H,
20 api_key: String,
21 model: String,
22 preamble: String,
23 tools: Vec<Box<dyn Tool>>,
24 base_url: String,
25 worker_id: String,
26 options: RunOptions,
27}
28
29impl<H: HttpClient> AgentBuilder<H> {
30 pub fn new(http: H, api_key: impl Into<String>, model: impl Into<String>) -> Self {
31 let model = model.into();
32 let mut options = RunOptions::new(model.clone());
33 options.base_url = "https://api.deepseek.com/v1".into();
34 Self {
35 http,
36 api_key: api_key.into(),
37 model,
38 preamble: String::new(),
39 tools: Vec::new(),
40 base_url: "https://api.deepseek.com".into(),
41 worker_id: String::new(),
42 options,
43 }
44 }
45
46 pub fn preamble(mut self, p: &str) -> Self {
47 self.preamble = p.into();
48 self
49 }
50
51 pub fn tool(mut self, t: impl Tool + 'static) -> Self {
52 self.tools.push(Box::new(t));
53 self
54 }
55
56 pub fn base_url(mut self, url: &str) -> Self {
60 let trimmed = url.trim_end_matches('/').to_string();
61 self.base_url = trimmed.clone();
62 self.options.base_url = if trimmed.ends_with("/v1") {
64 trimmed
65 } else {
66 format!("{trimmed}/v1")
67 };
68 self
69 }
70
71 pub fn worker_id(mut self, id: impl Into<String>) -> Self {
72 self.worker_id = id.into();
73 self
74 }
75
76 pub fn options(mut self, opts: RunOptions) -> Self {
80 self.options = opts;
81 self
82 }
83
84 pub fn build(self) -> DeepSeekAgent<H> {
85 let mut options = self.options;
86 options.model = self.model.clone();
87 options.system_prompt = self.preamble;
88 DeepSeekAgent {
89 http: self.http,
90 api_key: self.api_key,
91 tools: Arc::new(self.tools),
92 options,
93 worker_id: self.worker_id,
94 }
95 }
96}
97
98pub struct DeepSeekAgent<H: HttpClient> {
102 http: H,
103 api_key: String,
104 tools: Arc<Vec<Box<dyn Tool>>>,
105 options: RunOptions,
106 #[allow(dead_code)]
107 worker_id: String,
108}
109
110impl<H: HttpClient + Clone + Send + Sync + 'static> DeepSeekAgent<H> {
111 pub fn run(
113 &self,
114 user_prompt: String,
115 ) -> impl futures::Stream<Item = SdkMessage> + use<H> {
116 run(
117 self.http.clone(),
118 self.api_key.clone(),
119 Arc::clone(&self.tools),
120 user_prompt,
121 self.options.clone_for_run(),
122 )
123 }
124
125 pub async fn prompt(&self, user_prompt: String) -> Result<String> {
128 let mut stream = Box::pin(self.run(user_prompt));
129 let mut last_text: Option<String> = None;
130 while let Some(msg) = stream.next().await {
131 match msg {
132 SdkMessage::Result {
133 subtype: ResultSubtype::Success,
134 result: Some(text),
135 ..
136 } => return Ok(text),
137 SdkMessage::Result { subtype, .. } => {
138 return Err(DeepSeekError::Other(format!(
139 "agent stopped with subtype {subtype:?}"
140 )));
141 }
142 SdkMessage::Assistant { content, .. } => {
143 if let Some(t) = content.iter().find_map(|b| match b {
144 super::messages::ContentBlock::Text { text } => Some(text.clone()),
145 _ => None,
146 }) {
147 last_text = Some(t);
148 }
149 }
150 _ => {}
151 }
152 }
153 last_text.ok_or_else(|| {
154 DeepSeekError::Other("agent stream ended without a Result message".into())
155 })
156 }
157}
158
159impl RunOptions {
160 fn clone_for_run(&self) -> RunOptions {
163 RunOptions {
164 model: self.model.clone(),
165 system_prompt: self.system_prompt.clone(),
166 allowed_tools: self.allowed_tools.clone(),
167 disallowed_tools: self.disallowed_tools.clone(),
168 max_turns: self.max_turns,
169 max_budget_usd: self.max_budget_usd,
170 effort: self.effort.clone(),
171 permission_mode: self.permission_mode,
172 pre_tool_hook: self.pre_tool_hook.clone(),
173 session_id: self.session_id.clone(),
174 base_url: self.base_url.clone(),
175 }
176 }
177}