|
| 1 | +use std::path::PathBuf; |
| 2 | +use std::sync::Arc; |
| 3 | + |
| 4 | +use anyhow::{Context as _, Result}; |
| 5 | +use forge_domain::{ |
| 6 | + Context, ContextMessage, DataGenerationParameters, ResultStreamExt, Template, ToolDefinition, |
| 7 | +}; |
| 8 | +use futures::StreamExt; |
| 9 | +use futures::stream::{self, BoxStream}; |
| 10 | +use schemars::schema::RootSchema; |
| 11 | +use tracing::{debug, info}; |
| 12 | + |
| 13 | +use crate::{ |
| 14 | + AppConfigService, EnvironmentService, FsReadService, ProviderService, Services, TemplateEngine, |
| 15 | +}; |
| 16 | + |
| 17 | +pub struct DataGenerationApp<A> { |
| 18 | + services: Arc<A>, |
| 19 | +} |
| 20 | + |
| 21 | +type JsonSchema = String; |
| 22 | +type SystemPrompt = String; |
| 23 | +type UserPrompt = String; |
| 24 | +type Input = Vec<serde_json::Value>; |
| 25 | + |
| 26 | +impl<A: Services> DataGenerationApp<A> { |
| 27 | + pub fn new(services: Arc<A>) -> Self { |
| 28 | + Self { services } |
| 29 | + } |
| 30 | + |
| 31 | + /// Helper function to read a file from a path, resolving it relative to cwd |
| 32 | + /// if necessary |
| 33 | + async fn read_file(&self, path: PathBuf) -> Result<String> { |
| 34 | + let resolved_path = if path.is_absolute() { |
| 35 | + path |
| 36 | + } else { |
| 37 | + let cwd = self.services.get_environment().cwd; |
| 38 | + cwd.join(path) |
| 39 | + }; |
| 40 | + |
| 41 | + let content = self |
| 42 | + .services |
| 43 | + .read(resolved_path.display().to_string(), None, None) |
| 44 | + .await? |
| 45 | + .content |
| 46 | + .file_content() |
| 47 | + .to_owned(); |
| 48 | + |
| 49 | + Ok(content) |
| 50 | + } |
| 51 | + |
| 52 | + async fn read_file_opt(&self, path: Option<PathBuf>) -> Result<Option<String>> { |
| 53 | + match path { |
| 54 | + Some(path) => self.read_file(path).await.map(Some), |
| 55 | + None => Ok(None), |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + async fn load_parameters( |
| 60 | + &self, |
| 61 | + params: DataGenerationParameters, |
| 62 | + ) -> Result<(JsonSchema, Option<SystemPrompt>, Option<UserPrompt>, Input)> { |
| 63 | + debug!("Loading data generation parameters"); |
| 64 | + |
| 65 | + // Read all files in parallel |
| 66 | + let (schema, system_prompt, user_prompt, input) = tokio::join!( |
| 67 | + self.read_file(params.schema.clone()), |
| 68 | + self.read_file_opt(params.system_prompt), |
| 69 | + self.read_file_opt(params.user_prompt), |
| 70 | + self.read_file(params.input) |
| 71 | + ); |
| 72 | + |
| 73 | + let input: Vec<serde_json::Value> = input? |
| 74 | + .lines() |
| 75 | + .map(|text| { |
| 76 | + serde_json::from_str(text).with_context(|| "Could not parse the input file") |
| 77 | + }) |
| 78 | + .collect::<Result<Vec<_>>>()?; |
| 79 | + |
| 80 | + debug!("Loaded {} input items", input.len()); |
| 81 | + |
| 82 | + Ok((schema?, system_prompt?, user_prompt?, input)) |
| 83 | + } |
| 84 | + |
| 85 | + pub async fn execute( |
| 86 | + &self, |
| 87 | + params: DataGenerationParameters, |
| 88 | + ) -> Result<BoxStream<'static, Result<serde_json::Value>>> { |
| 89 | + let concurrency = params.concurrency; |
| 90 | + let (schema, system_prompt, user_prompt, input) = self.load_parameters(params).await?; |
| 91 | + |
| 92 | + info!( |
| 93 | + "Starting data generation with {} items (concurrency: {})", |
| 94 | + input.len(), |
| 95 | + concurrency |
| 96 | + ); |
| 97 | + |
| 98 | + let provider = self.services.get_default_provider().await?; |
| 99 | + let model_id = self.services.get_provider_model(Some(&provider.id)).await?; |
| 100 | + debug!("Using provider: {}, model: {}", provider.id, model_id); |
| 101 | + let schema: RootSchema = |
| 102 | + serde_json::from_str(&schema).with_context(|| "Could not parse the JSON schema")?; |
| 103 | + let mut context = |
| 104 | + Context::default().add_tool(ToolDefinition::new("output").input_schema(schema)); |
| 105 | + |
| 106 | + if let Some(content) = system_prompt { |
| 107 | + context = context.add_message(ContextMessage::system(content)) |
| 108 | + } |
| 109 | + |
| 110 | + let services = self.services.clone(); |
| 111 | + |
| 112 | + let json_stream = input.into_iter().map(move |input| { |
| 113 | + let provider = provider.clone(); |
| 114 | + let context = context.clone(); |
| 115 | + let user_prompt = user_prompt.clone(); |
| 116 | + let model_id = model_id.clone(); |
| 117 | + let services = services.clone(); |
| 118 | + |
| 119 | + async move { |
| 120 | + debug!("Processing data generation request"); |
| 121 | + |
| 122 | + let provider = provider.clone(); |
| 123 | + let mut context = context.clone(); |
| 124 | + let content = if let Some(ref content) = user_prompt { |
| 125 | + TemplateEngine::default().render_template(Template::new(content), &input)? |
| 126 | + } else { |
| 127 | + serde_json::to_string(&input)? |
| 128 | + }; |
| 129 | + |
| 130 | + context = |
| 131 | + context.add_message(ContextMessage::user(content, Some(model_id.clone()))); |
| 132 | + |
| 133 | + let stream = services.chat(&model_id, context, provider.clone()).await?; |
| 134 | + let response = stream.into_full(false).await?; |
| 135 | + |
| 136 | + anyhow::Ok((input, response)) |
| 137 | + } |
| 138 | + }); |
| 139 | + |
| 140 | + let json_stream = stream::iter(json_stream) |
| 141 | + .buffer_unordered(concurrency) |
| 142 | + .map(|result| { |
| 143 | + result.and_then(|(input, response)| { |
| 144 | + response |
| 145 | + .tool_calls |
| 146 | + .into_iter() |
| 147 | + .map(|tool| { |
| 148 | + let output = tool.arguments.parse()?; |
| 149 | + let mut value = serde_json::Map::new(); |
| 150 | + value.insert("input".to_string(), input.clone()); |
| 151 | + value.insert("output".to_string(), output); |
| 152 | + Ok(serde_json::Value::from(value)) |
| 153 | + }) |
| 154 | + .collect::<Result<Vec<_>>>() |
| 155 | + }) |
| 156 | + }) |
| 157 | + .flat_map(|data| match data { |
| 158 | + Ok(data) => stream::iter(data).map(Ok).boxed(), |
| 159 | + Err(err) => stream::iter(Err(err)).boxed(), |
| 160 | + }) |
| 161 | + .boxed(); |
| 162 | + |
| 163 | + Ok(json_stream) |
| 164 | + } |
| 165 | +} |
0 commit comments