Comments (2)
Sharing some sample code would be really helpful. Could you provide some assistance with that?
from openai.
This is my code:
public async Task<ActionResult> OnPostChatAsync(string message)
{
var messages = new List<ChatMessage>();
messages.Add(ChatMessage.FromUser(message));
var fn1 = new FunctionDefinitionBuilder("get_current_weather", "Get the current weather")
.AddParameter("location", PropertyDefinition.DefineString("The city and state, e.g. San Francisco, CA"))
.AddParameter("format", PropertyDefinition.DefineEnum(new List<string> { "celsius", "fahrenheit" }, "The temperature unit to use. Infer this from the users location."))
.Validate()
.Build();
var fn2 = new FunctionDefinitionBuilder("get_n_day_weather_forecast", "Get an N-day weather forecast")
.AddParameter("location", new() { Type = "string", Description = "The city and state, e.g. San Francisco, CA" })
.AddParameter("format", PropertyDefinition.DefineEnum(new List<string> { "celsius", "fahrenheit" }, "The temperature unit to use. Infer this from the users location."))
.AddParameter("num_days", PropertyDefinition.DefineInteger("The number of days to forecast"))
.Validate()
.Build();
var fn3 = new FunctionDefinitionBuilder("get_current_datetime", "Get the current date and time, e.g. 'Saturday, June 24, 2023 6:14:14 PM'")
.Build();
var fn4 = new FunctionDefinitionBuilder("identify_number_sequence", "Get a sequence of numbers present in the user message")
.AddParameter("values", PropertyDefinition.DefineArray(PropertyDefinition.DefineNumber("Sequence of numbers specified by the user")))
.Build();
var completionResult = await _openAiService.ChatCompletion.CreateCompletion(new ChatCompletionCreateRequest
{
Messages = messages,
Functions = new List<FunctionDefinition> { fn1, fn2, fn3, fn4 },
Model = "gpt-3.5-turbo",
});
string data="";
bool success = completionResult.Successful;
if (completionResult.Successful)
{
var choice = completionResult.Choices.First();
data = choice.Message.Content;
var fn = choice.Message.FunctionCall;
if (fn != null)
{
data += $"\nFunction call: {fn.Name}\n";
foreach (var entry in fn.ParseArguments())
{
data += $"\n {entry.Key}: {entry.Value}\n";
}
}
}
else
{
if (completionResult.Error == null)
{
data = "Unknown Error";
}
else
{
data = $"{completionResult.Error.Code}: {completionResult.Error.Message}";
}
}
var datas = new
{
success = success,
notLogin = notLogin,
data = data
};
return new JsonResult(datas);
}
public async Task<ActionResult> OnPostChatStreamAsync(string message, CancellationToken cancellationToken)
{
Response.ContentType = "text/event-stream";
Response.Headers.Add("Cache-Control", "no-cache");
Response.Headers.Add("Connection", "keep-alive");
Response.Headers["X-Accel-Buffering"] = "no";//Nginx
Response.Headers["Cache-Control"] = "no-cache, no-store";//Apache
Response.Headers["Pragma"] = "no-cache";//Apache
string data = "";
string curData = "";
bool success = false;
var messages = new List<ChatMessage>();
messages.Add(ChatMessage.FromUser(message));
var fn1 = new FunctionDefinitionBuilder("get_current_weather", "Get the current weather")
.AddParameter("location", PropertyDefinition.DefineString("The city and state, e.g. San Francisco, CA"))
.AddParameter("format", PropertyDefinition.DefineEnum(new List<string> { "celsius", "fahrenheit" }, "The temperature unit to use. Infer this from the users location."))
.Validate()
.Build();
var fn2 = new FunctionDefinitionBuilder("get_n_day_weather_forecast", "Get an N-day weather forecast")
.AddParameter("location", new() { Type = "string", Description = "The city and state, e.g. San Francisco, CA" })
.AddParameter("format", PropertyDefinition.DefineEnum(new List<string> { "celsius", "fahrenheit" }, "The temperature unit to use. Infer this from the users location."))
.AddParameter("num_days", PropertyDefinition.DefineInteger("The number of days to forecast"))
.Validate()
.Build();
var fn3 = new FunctionDefinitionBuilder("get_current_datetime", "Get the current date and time, e.g. 'Saturday, June 24, 2023 6:14:14 PM'")
.Build();
var fn4 = new FunctionDefinitionBuilder("identify_number_sequence", "Get a sequence of numbers present in the user message")
.AddParameter("values", PropertyDefinition.DefineArray(PropertyDefinition.DefineNumber("Sequence of numbers specified by the user")))
.Build();
var completionResult = _openAiService.ChatCompletion.CreateCompletionAsStream(new ChatCompletionCreateRequest
{
Messages = messages,
Functions = new List<FunctionDefinition> { fn1, fn2, fn3, fn4 },
Stream = true,
Model = "gpt-3.5-turbo",
}, cancellationToken: cancellationToken);
await foreach (var completion in completionResult)
{
if (cancellationToken.IsCancellationRequested)
{
break;
}
if (completion.Successful)
{
var choice = completion.Choices.First();
curData = choice.Message.Content;
data += curData;
await Response.WriteAsync(curData, cancellationToken);
await Response.Body.FlushAsync(cancellationToken);
var fn = choice.Message.FunctionCall;
if (fn != null)
{
curData = $"\nFunction call: {fn.Name}\n";
data += curData;
await Response.WriteAsync(curData, cancellationToken);
await Response.Body.FlushAsync(cancellationToken);
foreach (var entry in fn.ParseArguments())
{
data += $"\n {entry.Key}: {entry.Value}\n";
await Response.WriteAsync($"\n {entry.Key}: {entry.Value}\n", cancellationToken);
await Response.Body.FlushAsync(cancellationToken);
}
}
}
else
{
if (completion.Error == null)
{
data = "Unknown Error";
}
else
{
data = $"{completion.Error.Code}: {completion.Error.Message}";
}
await Response.WriteAsync(data, cancellationToken);
await Response.Body.FlushAsync(cancellationToken);
break;
}
}
return new EmptyResult();
}
I use ajax to get Chat result, and use fetch to get ChatStream result.
If I do not to use Functions , the result is OK, but when I use Functions ,the result is bad.
Chat reult may like this:
Function call: get_current_weather
location: Beijing
format: celsius
And ChatStream result may like this:
Value cannot be null. (Parameter 'text')
from openai.
Related Issues (20)
- Long Responses are truncated HOT 2
- Support for Extensions, eg. Azure CognitiveSearch HOT 3
- I am encountering a 400 error when performing fine-tuning. HOT 2
- GPT3.5 Turbo 16 Token availability HOT 1
- gpt-3.5-turbo-instruct? HOT 1
- Enhancing the contributing.md file HOT 1
- Usage is always null when using CreateCompletionAsStream HOT 1
- FunctionCallingHelper unable to handle array parameter HOT 5
- System.Text.Json.JsonException The JSON value could not be converted to System.String. Path: $.error.code | LineNumber: 0 | BytePositionInLine: 20. HOT 32
- When will the dall-e-3 model be supported? HOT 1
- Documentation Improvement HOT 1
- Enums for Image Style should be lower case
- Question about DALL-E-3 HOT 1
- Fooo HOT 1
- Regarding the issue of calling the Gpt_4_vision_preview model HOT 7
- '<' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0 while calling CreateEmbedding api HOT 5
- Expose Dall-E 3 revised prompt in the API HOT 1
- upgrading to .NET8.0
- Create Speech example HOT 1
- How to use Vision API ? Unity HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from openai.