Skip to content

Commit 18ae6ec

Browse files
committed
add sendasync method to refactor the aiservice telerik/kendo#24269
1 parent c1073ff commit 18ae6ec

File tree

1 file changed

+60
-88
lines changed
  • Telerik.Examples.Mvc/Telerik.Examples.Mvc/Controllers

1 file changed

+60
-88
lines changed

Telerik.Examples.Mvc/Telerik.Examples.Mvc/Controllers/AiService.cs

Lines changed: 60 additions & 88 deletions
Original file line numberDiff line numberDiff line change
@@ -23,20 +23,8 @@ public AiService(IConfiguration config)
2323
_deployment = config["OpenAI:DeploymentName"];
2424
}
2525

26-
public async Task<string> ProcessAsync(string prompt)
26+
private async Task<string> SendAsync(string url, object payload)
2727
{
28-
var url = $"{_endpoint}openai/deployments/{_deployment}/chat/completions?api-version=2024-02-15-preview";
29-
var payload = new
30-
{
31-
messages = new[]
32-
{
33-
new { role = "system", content = "You are a helpful assistant." },
34-
new { role = "user", content = prompt }
35-
},
36-
temperature = 0.3,
37-
max_tokens = 1500
38-
};
39-
4028
_http.DefaultRequestHeaders.Clear();
4129
_http.DefaultRequestHeaders.Add("api-key", _apiKey);
4230

@@ -51,6 +39,30 @@ public async Task<string> ProcessAsync(string prompt)
5139
return json["choices"]?[0]?["message"]?["content"]?.ToString()?.Trim() ?? "";
5240
}
5341

42+
public async Task<string> ProcessAsync(string prompt)
43+
{
44+
try
45+
{
46+
var url = $"{_endpoint}openai/deployments/{_deployment}/chat/completions?api-version=2024-02-15-preview";
47+
var payload = new
48+
{
49+
messages = new[]
50+
{
51+
new { role = "system", content = "You are a helpful assistant." },
52+
new { role = "user", content = prompt }
53+
},
54+
temperature = 0.3,
55+
max_tokens = 1500
56+
};
57+
58+
return await SendAsync(url, payload);
59+
}
60+
catch
61+
{
62+
return "AI configuration missing";
63+
}
64+
}
65+
5466
public async Task<string> AnalyzeGridDataAsync(string instructions, string gridDataJson)
5567
{
5668
var systemPrompt = @"
@@ -78,72 +90,55 @@ You are an AI assistant analyzing Kendo UI Grid data.
7890
try
7991
{
8092
var url = $"{_endpoint}openai/deployments/{_deployment}/chat/completions?api-version=2024-02-15-preview";
81-
8293
var payload = new
8394
{
8495
messages = new[]
8596
{
86-
new { role = "system", content = systemPrompt },
87-
new { role = "user", content = $"Grid Data:\n{gridDataJson}" },
88-
new { role = "user", content = $"Question:\n{instructions}" }
89-
},
97+
new { role = "system", content = systemPrompt },
98+
new { role = "user", content = $"Grid Data:\n{gridDataJson}" },
99+
new { role = "user", content = $"Question:\n{instructions}" }
100+
},
90101
temperature = 0.3,
91102
max_tokens = 1500
92103
};
93104

94-
_http.DefaultRequestHeaders.Clear();
95-
_http.DefaultRequestHeaders.Add("api-key", _apiKey);
96-
97-
var content = new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json");
98-
var response = await _http.PostAsync(url, content);
99-
var text = await response.Content.ReadAsStringAsync();
100-
101-
if (!response.IsSuccessStatusCode)
102-
return $"Azure OpenAI API error: {response.StatusCode}";
103-
104-
var json = JObject.Parse(text);
105-
return json["choices"]?[0]?["message"]?["content"]?.ToString()?.Trim() ?? "";
105+
return await SendAsync(url, payload);
106106
}
107107
catch
108108
{
109109
return "AI configuration missing";
110110
}
111111
}
112+
112113
public async Task<string> EditTextAsync(string text, string instruction)
113114
{
114115
try
115116
{
116117
var url = $"{_endpoint}openai/deployments/{_deployment}/chat/completions?api-version=2024-02-15-preview";
117-
118118
var payload = new
119119
{
120120
messages = new[]
121121
{
122-
new { role = "system", content =
123-
"You are an AI text editor. Modify the text ONLY according to the user's instruction while preserving existing formatting. " +
124-
"If the user requests color, bold, or styles, return the text wrapped in proper HTML inline styles (e.g., <span style='color: green;'>text</span>). " +
125-
"Do not apply additional formatting unless explicitly requested."
126-
},
127-
new { role = "user", content =
128-
$"Modify this text:\n\n{text}\n\nInstruction: {instruction}\n\nReturn the modified text as valid HTML with inline styles only if formatting changes are required."
129-
}
130-
},
122+
new
123+
{
124+
role = "system",
125+
content =
126+
"You are an AI text editor. Modify the text ONLY according to the user's instruction while preserving existing formatting. " +
127+
"If the user requests color, bold, or styles, return the text wrapped in proper HTML inline styles (e.g., <span style='color: green;'>text</span>). " +
128+
"Do not apply additional formatting unless explicitly requested."
129+
},
130+
new
131+
{
132+
role = "user",
133+
content =
134+
$"Modify this text:\n\n{text}\n\nInstruction: {instruction}\n\nReturn the modified text as valid HTML with inline styles only if formatting changes are required."
135+
}
136+
},
131137
temperature = 0.3,
132138
max_tokens = 500
133139
};
134140

135-
_http.DefaultRequestHeaders.Clear();
136-
_http.DefaultRequestHeaders.Add("api-key", _apiKey);
137-
138-
var content = new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json");
139-
var response = await _http.PostAsync(url, content);
140-
var responseText = await response.Content.ReadAsStringAsync();
141-
142-
if (!response.IsSuccessStatusCode)
143-
return $"Azure OpenAI API error: {response.StatusCode} - {responseText}";
144-
145-
var json = JObject.Parse(responseText);
146-
return json["choices"]?[0]?["message"]?["content"]?.ToString()?.Trim() ?? "No AI response.";
141+
return await SendAsync(url, payload);
147142
}
148143
catch
149144
{
@@ -159,30 +154,17 @@ public async Task<string> GenerateChartConfigAsync(string instructions)
159154
{
160155
messages = new[]
161156
{
162-
new { role = "system", content = "Return ONLY valid JSON for a Kendo UI Chart." },
163-
new { role = "user", content = $"Generate a Kendo UI Chart JSON configuration. Instructions: {instructions}" }
164-
},
157+
new { role = "system", content = "Return ONLY valid JSON for a Kendo UI Chart." },
158+
new { role = "user", content = $"Generate a Kendo UI Chart JSON configuration. Instructions: {instructions}" }
159+
},
165160
temperature = 0.2,
166161
max_tokens = 600
167162
};
168163

169-
_http.DefaultRequestHeaders.Clear();
170-
_http.DefaultRequestHeaders.Add("api-key", _apiKey);
164+
var raw = await SendAsync(url, payload);
165+
if (string.IsNullOrWhiteSpace(raw)) return "{}";
171166

172-
var content = new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json");
173-
var response = await _http.PostAsync(url, content);
174-
175-
if (!response.IsSuccessStatusCode)
176-
return "{}";
177-
178-
var raw = await response.Content.ReadAsStringAsync();
179-
dynamic json = JsonConvert.DeserializeObject(raw);
180-
181-
string config = json?.choices?[0]?.message?.content?.ToString() ?? "";
182-
if (string.IsNullOrWhiteSpace(config))
183-
return "{}";
184-
185-
config = config.Trim();
167+
string config = raw.Trim();
186168

187169
int start = config.IndexOf('{');
188170
int end = config.LastIndexOf('}');
@@ -218,7 +200,7 @@ public async Task<string> GenerateSchedulerConfigAsync(string instructions)
218200
219201
The JSON object MUST contain:
220202
{
221-
""date"": ""2025-01-10T00:00:00Z"", // optional
203+
""date"": ""2025-01-10T00:00:00Z"",
222204
""events"": [
223205
{
224206
""id"": 1,
@@ -239,27 +221,17 @@ public async Task<string> GenerateSchedulerConfigAsync(string instructions)
239221
{
240222
messages = new[]
241223
{
242-
new { role = "system", content = systemPrompt },
243-
new { role = "user", content = instructions }
244-
},
224+
new { role = "system", content = systemPrompt },
225+
new { role = "user", content = instructions }
226+
},
245227
temperature = 0.2,
246228
max_tokens = 600
247229
};
248230

249-
_http.DefaultRequestHeaders.Clear();
250-
_http.DefaultRequestHeaders.Add("api-key", _apiKey);
251-
252-
var content = new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json");
253-
var response = await _http.PostAsync(url, content);
254-
255-
var raw = await response.Content.ReadAsStringAsync();
256-
if (!response.IsSuccessStatusCode)
257-
return "{}";
258-
259-
dynamic json = JsonConvert.DeserializeObject(raw);
260-
string config = json?.choices?[0]?.message?.content?.ToString() ?? "{}";
231+
var raw = await SendAsync(url, payload);
232+
if (string.IsNullOrWhiteSpace(raw)) return "{}";
261233

262-
config = config.Trim();
234+
string config = raw.Trim();
263235

264236
int start = config.IndexOf("{");
265237
int end = config.LastIndexOf("}");

0 commit comments

Comments
 (0)