conductor/client/prompt_client.rs
1// Copyright {{.Year}} Conductor OSS
2// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
3
4use crate::error::Result;
5use crate::http::{ApiClient, ApiPath};
6use crate::models::{MetadataTag, PromptTemplate};
7use std::collections::HashMap;
8
9/// Client for managing AI prompt templates.
10#[derive(Clone)]
11pub struct PromptClient {
12 api: ApiClient,
13}
14
15impl PromptClient {
16 /// Create a new prompt client.
17 #[must_use]
18 pub fn new(api: ApiClient) -> Self {
19 Self { api }
20 }
21
22 // ==================== Basic CRUD operations ====================
23
24 /// Creates or updates a prompt template (simplified method)
25 /// This creates a new version or updates the latest version.
26 ///
27 /// # Errors
28 ///
29 /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
30 pub async fn save_prompt(
31 &self,
32 prompt_name: &str,
33 description: &str,
34 prompt_template: &str,
35 ) -> Result<()> {
36 self.save_prompt_with_options(prompt_name, description, prompt_template, None, None, false)
37 .await
38 }
39
40 /// Creates or updates a prompt template with full control over versioning and model associations.
41 ///
42 /// # Arguments
43 /// * `prompt_name` - The name of the prompt template
44 /// * `description` - A description of what the prompt does
45 /// * `prompt_template` - The template content with optional variable placeholders
46 /// * `models` - Optional list of AI model names this prompt is compatible with (e.g., `["openai:gpt-4", "anthropic:sonnet-4.5"]`)
47 /// * `version` - Specific version number to create or update, or None to update the latest version
48 /// * `auto_increment` - If true, automatically creates a new version instead of updating existing
49 ///
50 /// # Errors
51 ///
52 /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
53 pub async fn save_prompt_with_options(
54 &self,
55 prompt_name: &str,
56 description: &str,
57 prompt_template: &str,
58 models: Option<&[String]>,
59 version: Option<i32>,
60 auto_increment: bool,
61 ) -> Result<()> {
62 let path = format!("/prompts/{prompt_name}");
63
64 let mut params: Vec<(&str, String)> = vec![("description", description.to_owned())];
65
66 if let Some(v) = version {
67 params.push(("version", v.to_string()));
68 }
69
70 if auto_increment {
71 params.push(("autoIncrement", "true".to_owned()));
72 }
73
74 if let Some(m) = models {
75 for model in m {
76 params.push(("models", model.clone()));
77 }
78 }
79
80 let params_ref: Vec<(&str, &str)> = params.iter().map(|(k, v)| (*k, v.as_str())).collect();
81 self.api
82 .post_raw_with_params(
83 ApiPath::templated(&path, "/prompts/{promptName}"),
84 prompt_template,
85 ¶ms_ref,
86 )
87 .await
88 }
89
90 /// Updates an existing prompt template at a specific version.
91 ///
92 /// # Arguments
93 /// * `prompt_name` - The name of the prompt template
94 /// * `version` - The version number to update
95 /// * `description` - A description of what the prompt does
96 /// * `prompt_template` - The template content with optional variable placeholders
97 /// * `models` - Optional list of AI model names this prompt is compatible with
98 ///
99 /// # Errors
100 ///
101 /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
102 pub async fn update_prompt(
103 &self,
104 prompt_name: &str,
105 version: i32,
106 description: &str,
107 prompt_template: &str,
108 models: Option<&[String]>,
109 ) -> Result<()> {
110 let path = format!("/prompts/{prompt_name}/{version}");
111
112 let mut params: Vec<(&str, String)> = vec![("description", description.to_owned())];
113
114 if let Some(m) = models {
115 for model in m {
116 params.push(("models", model.clone()));
117 }
118 }
119
120 let params_ref: Vec<(&str, &str)> = params.iter().map(|(k, v)| (*k, v.as_str())).collect();
121 self.api
122 .put_raw_with_params(
123 ApiPath::templated(&path, "/prompts/{promptName}/{version}"),
124 prompt_template,
125 ¶ms_ref,
126 )
127 .await
128 }
129
130 /// Creates multiple prompt templates in a single bulk operation.
131 ///
132 /// # Arguments
133 /// * `prompts` - List of prompt templates to create
134 /// * `new_version` - If true, creates new versions for existing prompts; if false, updates existing versions
135 ///
136 /// # Errors
137 ///
138 /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
139 pub async fn save_prompts(&self, prompts: &[PromptTemplate], new_version: bool) -> Result<()> {
140 let path = format!("/prompts?newVersion={new_version}");
141 let _: serde_json::Value = self
142 .api
143 .post(ApiPath::templated(&path, "/prompts"), prompts)
144 .await?;
145 Ok(())
146 }
147
148 /// Retrieves the latest version of a prompt template by name.
149 ///
150 /// # Errors
151 ///
152 /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
153 pub async fn get_prompt(&self, prompt_name: &str) -> Result<PromptTemplate> {
154 let path = format!("/prompts/{prompt_name}");
155 self.api
156 .get(ApiPath::templated(&path, "/prompts/{promptName}"))
157 .await
158 }
159
160 /// Retrieves a specific version of a prompt template.
161 ///
162 /// # Arguments
163 /// * `prompt_name` - The name of the prompt template
164 /// * `version` - The version number to retrieve
165 ///
166 /// # Errors
167 ///
168 /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
169 pub async fn get_prompt_version(
170 &self,
171 prompt_name: &str,
172 version: i32,
173 ) -> Result<PromptTemplate> {
174 let path = format!("/prompts/{prompt_name}/{version}");
175 self.api
176 .get(ApiPath::templated(&path, "/prompts/{promptName}/{version}"))
177 .await
178 }
179
180 /// Retrieves all versions of a specific prompt template.
181 ///
182 /// # Arguments
183 /// * `prompt_name` - The name of the prompt template
184 ///
185 /// # Returns
186 /// List of all versions of the prompt template, ordered by version number.
187 ///
188 /// # Errors
189 ///
190 /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
191 pub async fn get_all_prompt_versions(&self, prompt_name: &str) -> Result<Vec<PromptTemplate>> {
192 let path = format!("/prompts/{prompt_name}/versions");
193 self.api
194 .get(ApiPath::templated(&path, "/prompts/{promptName}/versions"))
195 .await
196 }
197
198 /// Retrieves all prompt templates (latest versions only).
199 ///
200 /// # Errors
201 ///
202 /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, or an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status.
203 pub async fn get_prompts(&self) -> Result<Vec<PromptTemplate>> {
204 self.api.get("/prompts").await
205 }
206
207 /// Deletes all versions of a prompt template.
208 ///
209 /// # Errors
210 ///
211 /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, or an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status.
212 pub async fn delete_prompt(&self, prompt_name: &str) -> Result<()> {
213 let path = format!("/prompts/{prompt_name}");
214 self.api
215 .delete_no_content(ApiPath::templated(&path, "/prompts/{promptName}"))
216 .await
217 }
218
219 /// Deletes a specific version of a prompt template.
220 ///
221 /// # Arguments
222 /// * `prompt_name` - The name of the prompt template
223 /// * `version` - The version number to delete
224 ///
225 /// # Errors
226 ///
227 /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, or an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status.
228 pub async fn delete_prompt_version(&self, prompt_name: &str, version: i32) -> Result<()> {
229 let path = format!("/prompts/{prompt_name}/{version}");
230 self.api
231 .delete_no_content(ApiPath::templated(&path, "/prompts/{promptName}/{version}"))
232 .await
233 }
234
235 // ==================== Tag management ====================
236
237 /// Retrieves all tags associated with a prompt template.
238 ///
239 /// # Errors
240 ///
241 /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
242 pub async fn get_tags_for_prompt_template(
243 &self,
244 prompt_name: &str,
245 ) -> Result<Vec<MetadataTag>> {
246 let path = format!("/prompts/{prompt_name}/tags");
247 self.api
248 .get(ApiPath::templated(&path, "/prompts/{promptName}/tags"))
249 .await
250 }
251
252 /// Adds or updates tags for a prompt template.
253 ///
254 /// # Errors
255 ///
256 /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, or an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status.
257 pub async fn update_tag_for_prompt_template(
258 &self,
259 prompt_name: &str,
260 tags: &[MetadataTag],
261 ) -> Result<()> {
262 let path = format!("/prompts/{prompt_name}/tags");
263 self.api
264 .put_no_response(
265 ApiPath::templated(&path, "/prompts/{promptName}/tags"),
266 tags,
267 )
268 .await
269 }
270
271 /// Deletes specific tags from a prompt template.
272 ///
273 /// # Errors
274 ///
275 /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
276 pub async fn delete_tag_for_prompt_template(
277 &self,
278 prompt_name: &str,
279 tags: &[MetadataTag],
280 ) -> Result<()> {
281 let path = format!("/prompts/{prompt_name}/tags");
282 self.api
283 .delete_with_body(
284 ApiPath::templated(&path, "/prompts/{promptName}/tags"),
285 tags,
286 )
287 .await
288 }
289
290 // ==================== Testing ====================
291
292 /// Tests a prompt template by substituting variables and processing through the specified AI model.
293 ///
294 /// This allows you to validate prompt templates before saving them or using them in workflows.
295 ///
296 /// # Arguments
297 /// * `prompt_text` - The text of the prompt template with variable placeholders
298 /// * `variables` - A map containing variables to be replaced in the template
299 /// * `ai_integration` - The name of the AI integration provider (e.g., "openai")
300 /// * `text_complete_model` - The AI model to use for completing text (e.g., "gpt-4")
301 /// * `temperature` - The randomness of the output, typically 0.0 to 1.0 (default is 0.1)
302 /// * `top_p` - The nucleus sampling probability mass (default is 0.9)
303 /// * `stop_words` - Optional list of words at which to stop generating further text
304 ///
305 /// # Returns
306 /// The processed prompt text after variable substitution and AI model processing.
307 ///
308 /// # Errors
309 ///
310 /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
311 #[expect(clippy::too_many_arguments)]
312 pub async fn test_prompt(
313 &self,
314 prompt_text: &str,
315 variables: &HashMap<String, serde_json::Value>,
316 ai_integration: &str,
317 text_complete_model: &str,
318 temperature: f32,
319 top_p: f32,
320 stop_words: Option<&[String]>,
321 ) -> Result<String> {
322 let mut body = serde_json::json!({
323 "prompt": prompt_text,
324 "promptVariables": variables,
325 "llmProvider": ai_integration,
326 "model": text_complete_model,
327 "temperature": temperature,
328 "topP": top_p
329 });
330
331 if let Some(sw) = stop_words {
332 body["stopWords"] = serde_json::json!(sw);
333 }
334
335 self.api.post("/prompts/test", &body).await
336 }
337}
338
339#[cfg(test)]
340mod tests {
341 use super::*;
342 use crate::Configuration;
343
344 #[test]
345 fn test_prompt_client_creation() {
346 let config = Configuration::new("http://localhost:8080/api");
347 let api = ApiClient::new(config).unwrap();
348 let _client = PromptClient::new(api);
349 }
350}