Git Product home page Git Product logo

Comments (2)

kayhantolga avatar kayhantolga commented on June 10, 2024

Sharing some sample code would be really helpful. Could you provide some assistance with that?

from openai.

snow2zhou avatar snow2zhou commented on June 10, 2024

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)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.