1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
use std::time::Duration;
use crate::{
convert_recipe_with_config, convert_recipe_with_provider, fetch_recipe_with_timeout,
ImportError, Recipe,
};
/// Represents the input source for a recipe
#[derive(Debug, Clone)]
pub enum InputSource {
/// Fetch recipe from a URL
Url(String),
/// Use plain text content
Text(String),
}
/// Represents the desired output format
#[derive(Debug, Clone, Copy, Default)]
pub enum OutputMode {
/// Convert to Cooklang format (default)
#[default]
Cooklang,
/// Return Recipe struct without conversion
Recipe,
}
/// Result of a recipe import operation
#[derive(Debug, Clone)]
pub enum ImportResult {
/// Cooklang-formatted recipe
Cooklang(String),
/// Recipe struct (markdown format)
Recipe(Recipe),
}
/// Optional LLM provider configuration
#[derive(Debug, Clone)]
pub enum LlmProvider {
OpenAI,
Anthropic,
Google,
AzureOpenAI,
Ollama,
}
impl LlmProvider {
/// Convert to provider name string used by the factory
fn as_str(&self) -> &str {
match self {
LlmProvider::OpenAI => "openai",
LlmProvider::Anthropic => "anthropic",
LlmProvider::Google => "google",
LlmProvider::AzureOpenAI => "azure_openai",
LlmProvider::Ollama => "ollama",
}
}
}
/// Builder for configuring and executing recipe imports
#[derive(Debug, Default)]
pub struct RecipeImporterBuilder {
source: Option<InputSource>,
mode: OutputMode,
provider: Option<LlmProvider>,
timeout: Option<Duration>,
api_key: Option<String>,
model: Option<String>,
}
impl RecipeImporterBuilder {
/// Set the input source to a URL
///
/// # Example
/// ```
/// use cooklang_import::RecipeImporter;
///
/// let builder = RecipeImporter::builder()
/// .url("https://example.com/recipe");
/// ```
pub fn url(mut self, url: impl Into<String>) -> Self {
self.source = Some(InputSource::Url(url.into()));
self
}
/// Set the input source to plain text
///
/// Use this when you have a recipe in plain text format that needs to be parsed.
/// The LLM will extract ingredients and instructions from the text.
///
/// # Example
/// ```
/// use cooklang_import::RecipeImporter;
///
/// let recipe_text = "Take 2 eggs and 1 cup of flour. Mix them together and bake at 350F for 30 minutes.";
/// let builder = RecipeImporter::builder()
/// .text(recipe_text);
/// ```
pub fn text(mut self, text: impl Into<String>) -> Self {
self.source = Some(InputSource::Text(text.into()));
self
}
/// Set output mode to extract only (no conversion)
///
/// This returns a Recipe struct without converting to Cooklang format.
///
/// # Example
/// ```
/// use cooklang_import::RecipeImporter;
///
/// let builder = RecipeImporter::builder()
/// .url("https://example.com/recipe")
/// .extract_only();
/// ```
pub fn extract_only(mut self) -> Self {
self.mode = OutputMode::Recipe;
self
}
/// Set a custom LLM provider for conversion
///
/// # Example
/// ```
/// use cooklang_import::{RecipeImporter, LlmProvider};
///
/// let builder = RecipeImporter::builder()
/// .url("https://example.com/recipe")
/// .provider(LlmProvider::Anthropic);
/// ```
pub fn provider(mut self, provider: LlmProvider) -> Self {
self.provider = Some(provider);
self
}
/// Set a timeout for HTTP requests
///
/// # Example
/// ```
/// use cooklang_import::RecipeImporter;
/// use std::time::Duration;
///
/// let builder = RecipeImporter::builder()
/// .url("https://example.com/recipe")
/// .timeout(Duration::from_secs(30));
/// ```
pub fn timeout(mut self, duration: Duration) -> Self {
self.timeout = Some(duration);
self
}
/// Set the API key for the LLM provider
///
/// This allows passing the API key directly instead of relying on
/// environment variables or config files.
///
/// # Example
/// ```
/// use cooklang_import::{RecipeImporter, LlmProvider};
///
/// let builder = RecipeImporter::builder()
/// .url("https://example.com/recipe")
/// .provider(LlmProvider::Anthropic)
/// .api_key("your-api-key");
/// ```
pub fn api_key(mut self, key: impl Into<String>) -> Self {
self.api_key = Some(key.into());
self
}
/// Set the model name for the LLM provider
///
/// # Example
/// ```
/// use cooklang_import::{RecipeImporter, LlmProvider};
///
/// let builder = RecipeImporter::builder()
/// .url("https://example.com/recipe")
/// .provider(LlmProvider::Anthropic)
/// .model("claude-3-5-sonnet-20241022");
/// ```
pub fn model(mut self, model: impl Into<String>) -> Self {
self.model = Some(model.into());
self
}
/// Build and execute the recipe import operation
///
/// # Returns
/// An `ImportResult` containing either a Cooklang string or Recipe struct
///
/// # Errors
/// Returns `ImportError` if:
/// - No input source was specified
/// - URL fetch fails
/// - Recipe extraction fails
/// - Conversion fails
/// - Invalid combination of options (e.g., markdown + extract_only)
///
/// # Example
/// ```no_run
/// # use cooklang_import::RecipeImporter;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let result = RecipeImporter::builder()
/// .url("https://example.com/recipe")
/// .build()
/// .await?;
/// # Ok(())
/// # }
/// ```
pub async fn build(self) -> Result<ImportResult, ImportError> {
// Validate that source is set
let source = self.source.ok_or_else(|| {
ImportError::BuilderError(
"No input source specified. Use .url() or .markdown()".to_string(),
)
})?;
// Convert provider enum to string name if provided
let provider_name = self.provider.as_ref().map(|p| p.as_str());
match (source, self.mode) {
// Use Case 1: URL → Cooklang
(InputSource::Url(url), OutputMode::Cooklang) => {
let recipe = fetch_recipe_with_timeout(&url, self.timeout).await?;
let cooklang = if self.api_key.is_some() || self.model.is_some() {
convert_recipe_with_config(&recipe, provider_name, self.api_key, self.model)
.await?
} else {
convert_recipe_with_provider(&recipe, provider_name).await?
};
Ok(ImportResult::Cooklang(cooklang))
}
// Use Case 2: URL → Recipe (extract only)
(InputSource::Url(url), OutputMode::Recipe) => {
let recipe = fetch_recipe_with_timeout(&url, self.timeout).await?;
Ok(ImportResult::Recipe(recipe))
}
// Use Case 3: Text → Cooklang
(InputSource::Text(text), OutputMode::Cooklang) => {
// Validate input
if text.trim().is_empty() {
return Err(ImportError::InvalidMarkdown(
"Recipe text cannot be empty".to_string(),
));
}
// Create Recipe struct
let recipe = Recipe {
content: text,
..Default::default()
};
let cooklang = if self.api_key.is_some() || self.model.is_some() {
convert_recipe_with_config(&recipe, provider_name, self.api_key, self.model)
.await?
} else {
convert_recipe_with_provider(&recipe, provider_name).await?
};
Ok(ImportResult::Cooklang(cooklang))
}
// Invalid: Text → Recipe (no-op)
(InputSource::Text { .. }, OutputMode::Recipe) => Err(ImportError::BuilderError(
"Cannot use extract_only() with text input. Text needs to be parsed first."
.to_string(),
)),
}
}
}
/// Main entry point for the builder API
pub struct RecipeImporter;
impl RecipeImporter {
/// Creates a new builder for importing recipes
///
/// # Example
/// ```
/// use cooklang_import::RecipeImporter;
///
/// let builder = RecipeImporter::builder();
/// ```
pub fn builder() -> RecipeImporterBuilder {
RecipeImporterBuilder::default()
}
}