From 22f1ab44f9560023c59763e60d2c6c21f4433e48 Mon Sep 17 00:00:00 2001 From: Taha Date: Tue, 15 Oct 2024 23:38:49 -0400 Subject: [PATCH] Basic set of streams that can talks ot the LLM and get DSL back from few-shot prompt --- .../DataStream/Misc/DSLStream.cs | 31 +++ .../Join/NonIncremental/NonIncJoinStream.cs | 4 +- .../DataStreamCore/DataStreamCore.csproj | 2 + .../MarketData/SettlementPriceStream.cs | 15 +- .../SharedStreams/NL/FewShotPrompts.json | 181 ++++++++++++++++++ .../SharedStreams/NL/NLStream.cs | 35 ++++ .../SharedStreams/NL/NLToDSLStream.cs | 43 +++++ .../NL/NLToFewShotPromptStream.cs | 176 +++++++++++++++++ .../SharedStreams/NL/OpenAIPromptStream.cs | 112 +++++++++++ .../SharedStreams/SharedStreams.csproj | 1 + 10 files changed, 594 insertions(+), 6 deletions(-) create mode 100644 src/DataStreamSuite/DataStream/Misc/DSLStream.cs create mode 100644 src/DataStreamSuite/SharedStreams/NL/FewShotPrompts.json create mode 100644 src/DataStreamSuite/SharedStreams/NL/NLStream.cs create mode 100644 src/DataStreamSuite/SharedStreams/NL/NLToDSLStream.cs create mode 100644 src/DataStreamSuite/SharedStreams/NL/NLToFewShotPromptStream.cs create mode 100644 src/DataStreamSuite/SharedStreams/NL/OpenAIPromptStream.cs diff --git a/src/DataStreamSuite/DataStream/Misc/DSLStream.cs b/src/DataStreamSuite/DataStream/Misc/DSLStream.cs new file mode 100644 index 000000000..5824a60e1 --- /dev/null +++ b/src/DataStreamSuite/DataStream/Misc/DSLStream.cs @@ -0,0 +1,31 @@ +namespace bts.SilverPine { + using System; + using BCG; + using System.Collections.Generic; + using Bts.DataStreamExpressions; + + // All this does is take in a dsl expression, parse it and fire the data that come out of running it. + // So for example, if an expresison is passed + [DataStreamUserRespresentation("dsl")] + public class DSLStream : ViewStream { + private readonly string _dsl; + public DSLStream(string dsl) { + Log.Gen.info($"DSLStream.cons dsl: {dsl}"); + _dsl = dsl; + ViewStream rs = build_stream(dsl); + mySetRealSource(rs); + } + + static ViewStream? build_stream(string stream_expression) { + try { + var exp = DataStreamExpressionsInterpreter.Evaluate(stream_expression); + var rv = exp.getView(new Dictionary(0)); + return rv; + + } catch (Exception ex) { + bts.Log.assert(false, $"Could not build stream: {stream_expression} ex: {ex}"); + return null; + } + } + } +} \ No newline at end of file diff --git a/src/DataStreamSuite/DataStream/Primitives/Join/NonIncremental/NonIncJoinStream.cs b/src/DataStreamSuite/DataStream/Primitives/Join/NonIncremental/NonIncJoinStream.cs index 5c6be1a14..07b9f6528 100644 --- a/src/DataStreamSuite/DataStream/Primitives/Join/NonIncremental/NonIncJoinStream.cs +++ b/src/DataStreamSuite/DataStream/Primitives/Join/NonIncremental/NonIncJoinStream.cs @@ -129,7 +129,9 @@ namespace BCG { string log_msg = $"Join and map time for {_book_keeping_data.Count} " + $"tables {timer.Elapsed} ratio {_n_expensive_fires}/{_n_total_fires}"; } - myFireEvent(new DataPacket(dp_output_rows, dp_output_rows, myLastValue == null ? new BlueTable(_output_schema) : (myLastValue as DataPacket).newRows)); + var dp_out = BlueDataUtility.build_dp_inc(dp_output_rows, myLastValue as DataPacket); + myFireEvent(dp_out); + //myFireEvent(new DataPacket(dp_output_rows, dp_output_rows, myLastValue == null ? new BlueTable(_output_schema) : (myLastValue as DataPacket).newRows)); } } diff --git a/src/DataStreamSuite/DataStreamCore/DataStreamCore.csproj b/src/DataStreamSuite/DataStreamCore/DataStreamCore.csproj index 88cc3561c..ee49dfc6f 100644 --- a/src/DataStreamSuite/DataStreamCore/DataStreamCore.csproj +++ b/src/DataStreamSuite/DataStreamCore/DataStreamCore.csproj @@ -9,6 +9,8 @@ + + diff --git a/src/DataStreamSuite/SharedStreams/Business/MarketData/SettlementPriceStream.cs b/src/DataStreamSuite/SharedStreams/Business/MarketData/SettlementPriceStream.cs index 6e231e758..35c00fe6c 100644 --- a/src/DataStreamSuite/SharedStreams/Business/MarketData/SettlementPriceStream.cs +++ b/src/DataStreamSuite/SharedStreams/Business/MarketData/SettlementPriceStream.cs @@ -13,12 +13,15 @@ namespace bts.SilverPine { public SettlementPriceStream(string future_name, string date_txt) : this(future_name, date_txt, String.Empty) { } - // public SettlementPriceStream(string future_name, string begin_dt, string end_dt) - // : this(future_name, DateTime.Parse(begin_dt).Date, DateTime.Parse(end_dt).Date) { } + public SettlementPriceStream(string future_name, string begin_dt, string end_dt) + : this(future_name, DateTime.Parse(begin_dt).Date, DateTime.Parse(end_dt).Date) { } - public SettlementPriceStream(string symbol_or_contract, string begin_dt_txt, string end_dt_txt) { - DateTime begin_dt = DateTime.Parse(begin_dt_txt); - DateTime end_dt = String.IsNullOrEmpty(end_dt_txt) ? DateTime.MinValue : DateTime.Parse(end_dt_txt); + public SettlementPriceStream(string symbol_or_contract, DateTime begin_dt) + : this(symbol_or_contract, begin_dt, DateTime.MinValue) { } + + public SettlementPriceStream(string symbol_or_contract, DateTime begin_dt, DateTime end_dt) { + // DateTime begin_dt = DateTime.Parse(begin_dt_txt); + // DateTime end_dt = String.IsNullOrEmpty(end_dt_txt) ? DateTime.MinValue : DateTime.Parse(end_dt_txt); Tuple ccat_sym_contr = ContractUtils.get_symbol_category(symbol_or_contract); ContractUtils.ContractCategory contr_cat = ccat_sym_contr.Item1; string symbol = ccat_sym_contr.Item2; @@ -41,6 +44,8 @@ namespace bts.SilverPine { DateTime dt = r.get_datetime("ts_event"); return dt <= begin_dt && dt >= end_dt; }); + rs = new MathStream(rs, "settlement = close * 1.0"); + rs = new NewProjectStream(rs, "ts_event settlement"); mySetRealSource(rs); } diff --git a/src/DataStreamSuite/SharedStreams/NL/FewShotPrompts.json b/src/DataStreamSuite/SharedStreams/NL/FewShotPrompts.json new file mode 100644 index 000000000..1c7cc8558 --- /dev/null +++ b/src/DataStreamSuite/SharedStreams/NL/FewShotPrompts.json @@ -0,0 +1,181 @@ +{ + "prompts": [ + { + "category": "Settlement", + "description": "This is a few shot learning example for an NL to DSL. The DSL function in question is Settlement (symbol_or_contract, datetime1). The first argument is a future (like CL, for crude oil) or a specific future contract like crude oil Dec 24 future (CLZ4). The second argument is the date at which the settlement is to be fetched. There is an overloaded function, Settlement (symbol_or_contract, begin_dt, end_dt) which gets the settlements for all dates from begin_dt to end_dt. This will also have datetimes expressed as Today, Yesterday, Last Friday, First Friday of the month, Last Thursday of August etc. You will need to know what Today is, since there will be referecnes to last week, yesterday etc. These examples are assuming Today is 10/11/2024, however you should use the Today's real date", + "prompt": "What was the settlement for CL on June 8th?", + "examples": [ + { + "natural_language": "Find Settlement price of the SP500 future on 04/22/2023.", + "dsl": "Settlement(\"ES\", 4/22/2023)" + }, + { + "natural_language": "Find Settlement price of the Silver Dec 24 Future on 04/22/2023.", + "dsl": "Settlement(\"SIZ4\", 4/22/2023)" + }, + { + "natural_language": "Find Yesterday's Settlement of the Crude Oil Future.", + "dsl": "Settlement(\"CL\", 10/10/2024)" + }, + { + "natural_language": "Find today's settlement of the 10 year treasury future.", + "dsl": "Settlement(\"ZN\", 10/11/2024)" + }, + { + "natural_language": "Find the Settlement of Natural Gas Dec 24 future on the first Friday of Sept.", + "dsl": "Settlement(\"NGZ4\", 9/6/2024)" + }, + { + "natural_language": "Find the Settlement of WTI Jan 25 future in the first Week of Sept.", + "dsl": "Settlement(\"CLF5\", 9/2/2024, 9/6/2024)" + }, + { + "natural_language": "Find the Settlement price for the Sp 500 Dec 24 Mar 25 spread for the first two weeks of September.", + "dsl": "Settlement(\"ESZ4-ESH5\", 9/14/2024, 9/1/2024)" + }, + { + "natural_language": "Find the Settlement of Natural Gas future on the first Friday of Sept.", + "dsl": "Settlement(\"NG\", 9/6/2024)" + } + ] + }, + { + "category": "VWAP", + "description": "This is a few shot learning example for an NL to DSL. The DSL function in question is VWAP (symbol_or_contract, datetime1, datetime2). The first argument is a future (like CL, for crude oil, or ES for SP 500) or a specific future contract like crude oil Dec 24 future (CLZ4) or SP 500 Dec 2024 (ESZ4). The second argument is where the VWAP has to be calculated (also the beginning of the time window), and the third argument is datetime specifying the end of the time window. So, for example, a 20-day VWAP on 9/30/2023, the first argument will be 9/30/2023, and the third argument will be 9/10/2023 (20 days prior). This will also have datetimes expressed as Today, Yesterday, Last Friday, Last Sunday, etc. For the purpose of this few-shot prompts, let's assume today is 10/11/2024.", + "prompt": "What was the VWAP for ZN over the past 30 days?", + "examples": [ + { + "natural_language": "Find the 20 day VWAP of the SP future on 04/22/2023.", + "dsl": "VWAP(\"ES\", \"4/22/2023\", \"4/02/2023\")" + }, + { + "natural_language": "Find Yesterday's 10 day VWAP of the Crude Oil Future.", + "dsl": "VWAP(\"CL\", \"10/10/2024\", \"10/1/2024\")" + }, + { + "natural_language": "Find today's 30-day VWAP of the 10 year treasury future.", + "dsl": "VWAP(\"ZN\", \"10/11/2024\", \"9/11/2024\")" + }, + { + "natural_language": "Find the 10 hour VWAP of the Natural Gas future from yesterday at 5:00 PM.", + "dsl": "VWAP(\"NG\", \"9/27/2024 17:00:00\", \"9/27/2024 7:00:00\")" + } + ] + }, + { + "category": "Price Diff", + "description": "This is a few shot learning example for an NL to DSL. The DSL function in question is OHLCVPriceDiff (symbol_or_contract, datetime1, datetime2). The first argument is a future (like CL, for crude oil) or a specific future contract like crude oil Dec 24 future (CLZ4). The second and third arguments are dates, that the function finds the difference of prices at. Assume today is 10/15/2024", + "prompt": "What is the difference in ZN price from July 10th to July 14th?", + "examples": [ + { + "natural_language": "What is the difference in ZN price from July 10th to July 14th?", + "dsl": "OHLCVPriceDiff(\"ZN\", \"7/14/2024\", \"7/10/2024\")" + }, + { + "natural_language": "What is the price difference in SP Future price from Sept 10th and Sept 5th?", + "dsl": "OHLCVPriceDiff(\"ES\", \"9/10/2024\", \"9/5/2024\")" + }, + { + "natural_language": "What is the price difference in Natural Gas Dec Future price from Aug 30th and Aug 20th?", + "dsl": "OHLCVPriceDiff(\"NGZ4\", \"8/30/2024\", \"8/20/2024\")" + } + ] + }, + { + "category": "Abs Volume", + "description": "this is a few shot learning example for an NL to DSL. The DSL function in question is AbsVolume(symbol, ContractType, datetime1, datetime2), which computes the highest volume in the date range, specified by datetime1, and datetime2. The first argument is a future symbol (like CL for crude oil, ES for SP 500 etc). If no symbol is specified, use \"*\". The second argument is the ContractType, which is \"Future\" for futures and \"FutureSpread\" for future spreads. the 3rd argument is the begin date and the 4th argument is the end date, between which the max volume is computed. If no future is specified use \"*\" from the first arugment. For this prompt, assume today is 10/11/2024 ", + "prompt": "Which SP Future traded the most between 7/14/2024 and 7/10/2024", + "examples": [ + { + "natural_language": "Which SP Future traded the most between 7/14/2024 and 7/10/2024", + "dsl": "AbsVolume(\"ES\", \"Future\", \"7/14/2024\", \"7/10/2024\")" + }, + { + "natural_language": "Which Gold Spread traded the most between Today and Sept 20th", + "dsl": "AbsVolume(\"GC\", \"FutureSpread\", \"10/1/2024\", \"9/20/2024\")" + }, + { + "natural_language": "Which 10 year Spread traded the highest volume last week?", + "dsl": "AbsVolume(\"ZN\", \"FutureSpread\", \"9/27/2024\", \"9/23/2024\")" + }, + { + "natural_language": "Which Corn Spread traded the most today?", + "dsl": "AbsVolume(\"ZC\", \"FutureSpread\", \"10/1/2024\", \"10/1/2024\")" + }, + { + "natural_language": "Which Future traded the most today?", + "dsl": "AbsVolume(\"*\", \"Future\", \"9/30/2024\", \"9/30/2024\")" + } + ] + }, + { + "category": "Roll", + "description": "This is a few shot learning example for an NL to DSL. The DSL function in question is FuturesRoll(symbol) which computes the rollover date for a future, ie when the highest volume swtches from one expiration to the next one. ", + "prompt": "When does the roll typically occur In CL?", + "examples": [ + { + "natural_language": "When does the roll typically occur In CL?", + "dsl": "FuturesRoll(\"CL\")" + }, + { + "natural_language": "When does the roll typically occur for 10 year treasury?", + "dsl": "FuturesRoll(\"ZN\")" + }, + { + "natural_language": "When does the roll usually occur for Gold Future", + "dsl": "FuturesRoll(\"GC\")" + }, + { + "natural_language": "Which Corn Spread traded the most today?", + "dsl": "AbsVolume(\"ZC\", \"FutureSpread\", \"10/1/2024\", \"10/1/2024\")" + }, + { + "natural_language": "At what date does the future rollover happens for SP500?", + "dsl": "FuturesRoll(\"SI\")" + }, + { + "natural_language": "When does the future rollover happens for the Corn Future?", + "dsl": "FuturesRoll(\"ZC\")" + } + ] + }, + { + "category": "Daily Move", + "description": "This is a few shot learning example for an NL to DSL. For the purpose of this few shot prompts, lets assume today is 10/3/2024 ", + "prompt": "How often did crude settle + or - 10% over the previous day?", + "examples": [ + { + "natural_language": "List all the days when the SP 500 closed + or -5% from the previous day's close", + "dsl": "ColDiff(filteredOHLCV(\"ES\"),\"ts_event\", -1, \"close\", \"close\", \"close_diff\", 5)" + }, + { + "natural_language": "List all the days when the Crude Oil closed + or -2.5% from the previous day's close", + "dsl": "Average(filteredOHLCV(\"CL\", \"10/02/2023\", \"10/01/2023\"), \"volume\")" + }, + { + "natural_language": "Show me all the days when the Ten year Treaury Future opened + or -1% from the previous day's open", + "dsl": "Average(filteredOHLCV(\"SI\", \"10/03/2023\", \"9/13/2023\"), \"volume\")" + }, + { + "natural_language": "List all the trading days when the Silver Future opened + or -1% from the previous day's close", + "dsl": "Average(filteredOHLCV(\"ES\", \"10/03/2023\", \"9/13/2023\"), \"volume\")" + } + ] + }, + { + "category": "Average Volume", + "description": "This is a few shot learning example for an NL to DSL. For the purpose of this few shot prompts, lets assume today is 10/3/2024 ", + "prompt": "When does the most open interest typically shift from one contract to another in e-minis?", + "examples": [ + { + "natural_language": "When does the most open interest typically shift from one contract to another in e-minis? ", + "dsl": "FuturesRoll(\"ES\")" + }, + { + "natural_language": "Usually when does the open interest move from one contract to another in WTI?", + "dsl": "FuturesRoll(\"CL\")" + } + ] + } + ] +} \ No newline at end of file diff --git a/src/DataStreamSuite/SharedStreams/NL/NLStream.cs b/src/DataStreamSuite/SharedStreams/NL/NLStream.cs new file mode 100644 index 000000000..977641f01 --- /dev/null +++ b/src/DataStreamSuite/SharedStreams/NL/NLStream.cs @@ -0,0 +1,35 @@ +namespace sbts.SilverPine { + using BCG; + + using bts; + using bts.SilverPine; + + [DataStreamUserRespresentation("nl")] + public class NLStream : ViewStream { + private readonly string _nl_prompt; + private ViewStream _nl_to_dsl_stream, _dsl_stream; + public NLStream(string nl_prompt) { + _nl_prompt = nl_prompt; + } + + protected override void myOnFirstSubscriber() { + _nl_to_dsl_stream = new NLToDSLStream(_nl_prompt); + _nl_to_dsl_stream.onChange += _handle_dsl_callback; + } + + private void _handle_dsl_callback(object dp_obj) { + DataPacket dp = dp_obj as DataPacket; + var r = dp.newRows.to_list().ElementAt(0); + string dsl = r.get("response"); + Log.Gen.info($"NLStream._handle_dsl_callback dsl: {dsl}"); + _dsl_stream = new DSLStream(dsl); + _dsl_stream.onChange += _handle_data_cb; + } + + private void _handle_data_cb(object dp_obj) { + var dp = dp_obj as DataPacket; + DataPacket dp_out = BlueDataUtility.build_dp_inc(dp.newRows, myLastValue as DataPacket); + myFireEvent(dp_out); + } + } +} \ No newline at end of file diff --git a/src/DataStreamSuite/SharedStreams/NL/NLToDSLStream.cs b/src/DataStreamSuite/SharedStreams/NL/NLToDSLStream.cs new file mode 100644 index 000000000..b056334ee --- /dev/null +++ b/src/DataStreamSuite/SharedStreams/NL/NLToDSLStream.cs @@ -0,0 +1,43 @@ +namespace bts.SilverPine { + using BCG; + + // This subscribes to 1. NLToFewShotStream, gets the 2. total fewshot prompt, constructs and 3. OpenAIPromptReponseStream, + // passing in 2. to 3. As it gets the calbacks from 3. it fires them + [DataStreamUserRespresentation("nl_to_dsl")] + public class NLToDSLStream : ViewStream { + private readonly string _nl_prompt; + private ViewStream _nl_to_fw_prompt_stream; + ViewStream _openai_prompt_str = null; + public NLToDSLStream(string nl_prompt) { + _nl_prompt = nl_prompt; + _nl_to_fw_prompt_stream = new NLToFewShotPromptStream(nl_prompt); + } + + protected override void myOnFirstSubscriber() { + _nl_to_fw_prompt_stream.onChange += _on_fs_prompt; + } + + private void _on_fs_prompt(object dp_obj) { + DataPacket dp = dp_obj as DataPacket; + IBlueRow r = dp.newRows.to_list().ElementAt(0); + string few_shot_prompt = r.get("few_shot_prompt"); + Log.Gen.info($"NLToDSLStream._on_fs_prompt nl_prompt: {_nl_prompt} few_shot_prompt: {few_shot_prompt}"); + _openai_prompt_str = new OpenAIPromptStream(few_shot_prompt); + _openai_prompt_str.onChange += _on_openai_prompt; + } + + private void _on_openai_prompt(object dp_obj) { + DataPacket dp = dp_obj as DataPacket; + var dp_out = BlueDataUtility.build_dp(dp.newRows, myLastValue as DataPacket); + myFireEvent(dp_out); + } + + protected override void myOnLastSubscriber() { + + } + + + + + } +} \ No newline at end of file diff --git a/src/DataStreamSuite/SharedStreams/NL/NLToFewShotPromptStream.cs b/src/DataStreamSuite/SharedStreams/NL/NLToFewShotPromptStream.cs new file mode 100644 index 000000000..5c1ef23bb --- /dev/null +++ b/src/DataStreamSuite/SharedStreams/NL/NLToFewShotPromptStream.cs @@ -0,0 +1,176 @@ +namespace bts.SilverPine { + using BCG; + + using SimMetrics.Net.Metric; + + using System.Text.Json; + + + [DataStreamUserRespresentation("nl_to_fewshot_prompt")] + // given an nl prompt, retreives the correct fewshot prompt and converts it into a form + // that be sent to openAI as a prompt + public class NLToFewShotPromptStream : ViewStream { + + // Represents a pair of a natural language query and its dsl + public class FewShotExample { + public string natural_language { get; set; } + public string dsl { get; set; } + } + + // Class to represent each prompt category + public class FewShotPrompt { + public string category { get; set; } + // this is the explaination of the DSL + public string description { get; set; } + // th actual prompt given by the user/CME + public string prompt { get; set; } + public List examples { get; set; } + + public override string ToString() { + string rv = $"System: {description}\n"; + int ex_no = 0; + foreach (FewShotExample ex in examples) { + rv += $"{++ex_no}. Natural Language: \"{ex.natural_language}\"" + "\n"; + rv += $" DSL: {ex.dsl}\n"; + + } + return rv; + } + } + + // this is how it should be prepended to the actual prompt: + // System: This is a few-shot learning example for converting natural language prompts to a DSL function for settlement data retrieval. The DSL function can take either a single date or a date range. Assume today's date is 10/11/2024. The function is structured as follows: + // - Settlement(symbol_or_contract, datetime1): Retrieves the settlement for the specified date. + // - Settlement(symbol_or_contract, begin_dt, end_dt): Retrieves the settlements for all dates in the specified range. + + // Examples: + // 1. Natural Language: "Find the Settlement price of the SP future on 04/22/2023." + // DSL: Settlement(SP, 4/22/2023) + + // 2. Natural Language: "Find Yesterday's Settlement of the Crude Oil Future." + // DSL: Settlement(CL, 10/10/2024) + + // 3. Natural Language: "Find today's settlement of the 10-year treasury future." + // DSL: Settlement(ZN, 10/10/2024) + + // 4. Natural Language: "Find the Settlement of Natural Gas future on the first Friday of Sept." + // DSL: Settlement(NG, 9/6/2024) + + // 5. Natural Language: "Find the Settlement of Natural Gas Dec 24 future in the first Week of October." + // DSL: Settlement(NGZ4, 10/1/2024, 10/1/2024) + + // 6. Natural Language: "Find the settlement prices for the Wheat and Corn spread for the first two weeks of November." + // DSL: Settlement(ZWZ4-ZCZ4, 11/1/2024, 11/14/2024) + + // [Your Real Prompt Goes Here] + + + // Root class to map the JSON structure + public class Root { + public List prompts { get; set; } + } + + public static Root read_json_file() { + // TODO + string json_file_path = @"C:\Users\m_tah\development\spark\src\DataStreamSuite\SharedStreams\NL\FewShotPrompts.json"; + string json_string = File.ReadAllText(json_file_path); + var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; + Root root = JsonSerializer.Deserialize(json_string, options); + return root; + } + + private readonly string _nl_prompt; + // this is the first stream that sends all FewShotPrompt.prompt and asks the LLM + // to find the FewShotPrompt.prompt that matches the nl_prompt the closest. That + // gives us our FewShotPrompt + private ViewStream _nl_to_fewshot_index_stream; + public NLToFewShotPromptStream(string nl) { + _nl_prompt = nl; + } + + private static string _build_fewshot_prompt(FewShotPrompt fw_prompt, string nl_prompt) { + string rv = "You are a helpful assistant that converts natural language into DSL. "; + rv += $"{fw_prompt}\n\n"; + rv += "Now, convert the following prompt into DSL: \n"; + rv += $"Natural Language: {nl_prompt}\n"; + return rv; + } + + protected override void myOnFirstSubscriber() { + Root root = read_json_file(); + //FewShotPrompt p = find_matching_prompt(root, _nl_prompt); + //string final_prompt = _build_final_prompt(p, _nl_prompt); + string meta_prompt = build_meta_prompt(root, _nl_prompt); + _nl_to_fewshot_index_stream = new OpenAIPromptStream(meta_prompt); + _nl_to_fewshot_index_stream.onChange += _on_fewshot_index; + //Log.Gen.info($"NLToDSLStream.myOnFirstSubscriber meta_prompt: {meta_prompt}"); + + // this needs to be sent to the LLM to get the few-shot item. Once the few-shot item is received, then + // we can prepend the fewshot to the prompt and send it + //Log.Gen.info($"NLToDSLStream.myOnFirstSubscriber total_prompt: {final_prompt}"); + //_fire_event(final_prompt); + } + + private void _on_fewshot_index(object dp_obj) { + DataPacket dp = dp_obj as DataPacket; + IBlueRow r = dp.newRows.to_ienum().ElementAt(0); + string response = r.get("response"); + Log.Gen.info($"NLToDSLStream._on_fewshot_index prompt: {r.get("prompt")}"); + Log.Gen.info($"NLToDSLStream._on_fewshot_index response: {response}"); + string[] toks = response.Split('.'); + int index = Int32.Parse(toks[0]); + var root = read_json_file(); + FewShotPrompt fs_prompt = root.prompts[index]; + string final_prompt = _build_fewshot_prompt(fs_prompt, _nl_prompt); + _fire_event(final_prompt); + } + + private void _fire_event(string final_prompt) { + IBlueTableSchema schema = BlueDataUtility.form_schema("NLToFewShotPromptStream", + Tuple.Create("id", TypeCode.Int32), + Tuple.Create("prompt", TypeCode.String), + Tuple.Create("few_shot_prompt", TypeCode.String)); + IBlueRow nr = new BlueRow(schema, 0, _nl_prompt, final_prompt); + BlueTable nt = new BlueTable(schema); + nt.addRow(nr); + var dp_out = BlueDataUtility.build_dp(nt, myLastValue as DataPacket); + myFireEvent(dp_out); + } + + // since find_matching_prompt using string matching loses semantics and often results + // the incorrect few-shot entry (ex for, "Find the VWAP of the Sp 500 Dec 24 future during the first Week of October 24?"). + // so we assemble all the prompts from the few-shot (field "prompt") entry and ask an LLM to tell us which is the closest to the prompt. + // based on that we select the few-shot entry. This is what this function does + public static string build_meta_prompt(Root root, string nl_prompt) { + string meta_promp = "Take a look at the following prompt examples:\n"; + int rv = 0; + foreach (FewShotPrompt fs_entry in root.prompts) { + meta_promp += $"{rv++}. {fs_entry.prompt}\n"; + } + meta_promp += "Based on the above prompts, tell me which prompt (give me answer as the index only, and nothing else) does the following prompt most closely matches to: \n"; + meta_promp += nl_prompt; + return meta_promp; + } + + public static FewShotPrompt find_matching_prompt(Root root, string nl_prompt) { + var levenshtein = new SimMetrics.Net.Metric.Levenstein(); + FewShotPrompt rv = root.prompts.ElementAt(0); + Func get_total_sim = (fsp) => { + double similiarity = levenshtein.GetSimilarity(fsp.prompt, nl_prompt); + foreach (FewShotExample fs_ex in fsp.examples) { + similiarity += levenshtein.GetSimilarity(fs_ex.natural_language, nl_prompt); + } + return similiarity; + }; + double highest_simmiliarity = 0.0; + foreach (FewShotPrompt p in root.prompts) { + double similiarity = get_total_sim(p); //levenshtein.GetSimilarity(p.prompt, nl_prompt); + if (similiarity > highest_simmiliarity) { + highest_simmiliarity = similiarity; + rv = p; + } + } + return rv; + } + } +} \ No newline at end of file diff --git a/src/DataStreamSuite/SharedStreams/NL/OpenAIPromptStream.cs b/src/DataStreamSuite/SharedStreams/NL/OpenAIPromptStream.cs new file mode 100644 index 000000000..84b148d7f --- /dev/null +++ b/src/DataStreamSuite/SharedStreams/NL/OpenAIPromptStream.cs @@ -0,0 +1,112 @@ +namespace bts.SilverPine { + using System; + using System.IO; + using System.Net.Http; + using System.Text; + using System.Text.Json; + using System.Threading.Tasks; + // using OpenAI.GPT3; + // using OpenAI.GPT3.ObjectModels.RequestModels; + // using OpenAI.GPT3.Managers; + using BCG; + using BCG.Utilities.General; + + + // given a prompt, this stream connects to openAI and gets the response back + // it then fires a callback with the schema id, prompt, response + public class OpenAIPromptStream : ViewStream, IWorker { + #region OpenAI communication + static string api_key = //File.ReadAllText("OpenAIGPT4.key"); + "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"; + + // Uses HttpClient to send the prompt to OpenAI gpt4, and queues the response in the response_queue + public static async Task get_GPT4_http_responseAsync(string prompt, SyncQueue response_queue) { + Log.Gen.info($"OpenAIPromptStream.GetGPT4ResponseAsync prompt: {prompt}"); + // Read the API key from the file + + + // OpenAI API URL for the completion request + string apiUrl = "https://api.openai.com/v1/chat/completions"; + + // Create the request payload + var requestBody = new { + model = "gpt-3.5-turbo", + messages = new[] + { + new { role = "user", content = prompt } + }, + max_tokens = 500 // Adjust based on your response length needs + }; + + // Serialize the payload to JSON + string jsonRequestBody = JsonSerializer.Serialize(requestBody); + + using (HttpClient client = new HttpClient()) { + // Add the OpenAI API key to the Authorization header + client.DefaultRequestHeaders.Add("Authorization", $"Bearer {api_key}"); + + // Prepare the request content + HttpContent content = new StringContent(jsonRequestBody, Encoding.UTF8, "application/json"); + + // Send the POST request to OpenAI API + HttpResponseMessage response = await client.PostAsync(apiUrl, content); + + // Ensure the response is successful + response.EnsureSuccessStatusCode(); + + // Read the response content as a string + string response_content = await response.Content.ReadAsStringAsync(); + Log.Gen.info($"OpenAIPromptStream.GetGPT4ResponseAsync prompt: {prompt} response: {response_content}"); + + // Parse the response content + var json_doc = JsonDocument.Parse(response_content); + string gpt_response = json_doc.RootElement + .GetProperty("choices")[0] + .GetProperty("message") + .GetProperty("content") + .GetString(); + + //return gpt_response; + response_queue.enqueue(gpt_response); + Log.Gen.info($"OpenAIPromptStream.GetGPT4ResponseAsync gpt_response: {gpt_response}"); + + } + } + #endregion + + private readonly string _prompt; + private readonly ViewStreamDatabase _vsd; + private SyncQueue _queue = new SyncQueue(); + public OpenAIPromptStream(string prompt) + : this(ViewStreamDatabase.instance, prompt) { + } + + public OpenAIPromptStream(ViewStreamDatabase vsd, string prompt) { + _prompt = prompt; + _vsd = vsd; + } + + protected override void myOnFirstSubscriber() { + Task.Factory.StartNew(() => get_GPT4_http_responseAsync(_prompt, _queue)); + _vsd.addWorker(this); + } + + protected override void myOnLastSubscriber() { + } + + public void doWork() { + var response = _queue.dequeue(0); + if (response == null) + return; + IBlueTableSchema schema = BlueDataUtility.form_schema("OpenAIRespone", + Tuple.Create("id", TypeCode.Int32), + Tuple.Create("prompt", TypeCode.String), + Tuple.Create("response", TypeCode.String)); + IBlueRow nr = new BlueRow(schema, 0, _prompt, response); + BlueTable nt = new BlueTable(schema); + nt.addRow(nr); + var dp_out = BlueDataUtility.build_dp(nt, myLastValue as DataPacket); + myFireEvent(dp_out); + } + } +} diff --git a/src/DataStreamSuite/SharedStreams/SharedStreams.csproj b/src/DataStreamSuite/SharedStreams/SharedStreams.csproj index 1eaca56a1..233b5b976 100644 --- a/src/DataStreamSuite/SharedStreams/SharedStreams.csproj +++ b/src/DataStreamSuite/SharedStreams/SharedStreams.csproj @@ -17,6 +17,7 @@ +