بهترین روشها برای ادغام هوش مصنوعی در برنامههای .NET
نویسنده: وحید نصیری
تاریخ: ۱۴۰۴/۰۲/۰۸ ۰۷:۲۰
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
services.AddStackExchangeRedisCache(options =>
{
options.Configuration = Configuration.GetConnectionString("Redis");
options.InstanceName = "AIResponses_";
});
public async Task<string> GetAIResponseAsync(string prompt)
{
var cacheKey = $"AI_{prompt.GetHashCode()}";
var cachedResponse = await _distributedCache.GetStringAsync(cacheKey);
if (string.IsNullOrEmpty(cachedResponse))
{
cachedResponse = await CallOpenAIAsync(prompt);
await _distributedCache.SetStringAsync(cacheKey, cachedResponse, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(30)
});
}
return cachedResponse;
}var retryPolicy = Policy
.Handle<HttpRequestException>()
.WaitAndRetryAsync(5, attempt => TimeSpan.FromSeconds(Math.Pow(2, attempt)));
string response = await retryPolicy.ExecuteAsync(() => CallOpenAIAsync(prompt));try
{
var response = await CallOpenAIAsync(prompt);
}
catch (OpenAIException ex) when (ex.StatusCode == 429)
{
Log.Warning("Rate limit exceeded: {Message}", ex.Message);
}
catch (Exception ex)
{
Log.Error("Unexpected error occurred: {Message}", ex.Message);
}public string SanitizeInput(string input)
{
return Regex.Replace(input, @"[<>\\/]", "");
}
var safePrompt = SanitizeInput(prompt);string GeneratePrompt(string task, string detail)
{
return $"Provide a detailed explanation about {task}. Context: {detail}";
}
var optimizedPrompt = GeneratePrompt("distributed caching", ".NET application optimization");Log.Information("Sending prompt to OpenAI: {Prompt}", prompt);
var response = await CallOpenAIAsync(prompt);
Log.Information("Received AI response: {Response}", response);