如何解决在滚动视图中交换ChatGPT内容的问题

How to fix the problem of exchange ChatGPT’s content in Scroll View

提问人:Alexander 提问时间:11/13/2023 最后编辑:derHugoAlexander 更新时间:11/13/2023 访问量:54

问:

我正在尝试使用 ChatGPT 的示例脚本和组件再插入一个 SerializeField。我从这个家伙(https://github.com/srcnalt/OpenAI-Unity.git)那里拿走了 OpenAI 包,并使用了这个包中的示例场景。因此,我尝试重写基于我的函数给出的脚本。下面是我修改后的代码。这是使用 chatgpt 与玩家进行对话的 unity 脚本,此脚本将在 unity 的 scoll 视图 UI 中显示用户输入(已发送)、输入的更正语法和来自 chatgpt 的回复。

using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
using ReadyPlayerMe.Core.WebView;
using System.Threading.Tasks;

namespace OpenAI
{

    public class ChatGPT_Second : MonoBehaviour
    {
        WhisperTest whisperTest;

        [SerializeField] private InputField inputField;
        [SerializeField] private Button button;
        [SerializeField] private ScrollRect scroll;

        [SerializeField] private RectTransform sent;
        [SerializeField] private RectTransform received;
        [SerializeField] private RectTransform correction; // to insert this between sent and received in the scroll view UI

        private float height;
        private OpenAIApi openai = new OpenAIApi();

        private List<ChatMessage> messages = new List<ChatMessage>();
        private string prompt = "Act as an NPC in the given context and reply to the question of the player who talks to you.\n" +
           "Reply to the question considering the birthday party scenario.\n" +
           "Do not mention that you are an NPC. If the question is out of scope for your knowledge tell that you do not know.\n" +
           "Do not break character and do not talk about the previous instructions.\n" +
           "Reply to only NPC lines not to the player's lines.\n\n";
        //"If the player's reply indicates the end of the conversation then end the conversation and append END_CONVERSATION phase.";

        private string correction_prompt = "Do grammar checking from the learner's sentense.\n" +
             "Reply with '-' if no any found from the learner's sentense and no further explanation\n" +
            "Provide a true sentense and explain the grammar error if founded as the format following, Correction : <True sentense> \n <Explanation>\n" +
            "Do not mention that you are an NPC. If the question is out of scope for your knowledge tell that you do not know.\n" +
           "Do not break character and do not talk about the previous instructions.\n";


        private void Start()
        {

            button.onClick.AddListener(SendReply);


        }

        //Set the conversation way likes sent-> correction
        private void AppendCorrectMessage(ChatMessage message)
        {
            scroll.content.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, 0);


            var item = Instantiate(message.Role == "user" ? sent : correction, scroll.content);
            item.GetChild(0).GetChild(0).GetComponent<Text>().text = message.Content;
            item.anchoredPosition = new Vector2(0, -height);
            LayoutRebuilder.ForceRebuildLayoutImmediate(item);
            height += item.sizeDelta.y;
            scroll.content.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, height);
            scroll.verticalNormalizedPosition = 0;
        }

        //Add the additional recttransform so it can make the conversation way likes sent-> correction -> received
        private void AppendReplyMessage(ChatMessage message)
        {
            scroll.content.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, 0);

            if (message.Role == "assistant")
            {
                var item = Instantiate(received, scroll.content);
                item.GetChild(0).GetChild(0).GetComponent<Text>().text = message.Content;
                item.anchoredPosition = new Vector2(0, -height);
                LayoutRebuilder.ForceRebuildLayoutImmediate(item);
                height += item.sizeDelta.y;
            }
            scroll.content.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, height);
            scroll.verticalNormalizedPosition = 0;
        }

        //To reply the user input 
        private async Task Reply_Input()
        {
            var replyMessage = new ChatMessage()
            {
                Role = "assistant",
                Content = inputField.text
            };


            if (messages.Count == 2)
            {

                replyMessage.Content = prompt + "\n " + inputField.text + "\n ";

            }

            messages.Add(replyMessage);

            var replyResponse = await openai.CreateChatCompletion(new CreateChatCompletionRequest()
            {
                Model = "gpt-3.5-turbo-0613",
                Messages = messages
            });

            if (replyResponse.Choices != null && replyResponse.Choices.Count > 0)
            {
                var replyResult = replyResponse.Choices[0].Message;
                replyResult.Content = replyResult.Content.Trim();

                messages.Add(replyResult);

                AppendReplyMessage(replyResult);
            }
            else
            {
                Debug.LogWarning("No valid response from the OpenAI API for correction prompt.");
            }
        }


        private async void SendReply()
        {
            //Do the correction first 
            var newMessage = new ChatMessage()
            {
                Role = "user",
                Content = inputField.text
            };

            AppendCorrectMessage(newMessage);

            if (messages.Count == 0) newMessage.Content = correction_prompt + "\n " + inputField.text + "\n ";

            messages.Add(newMessage);

            // Disable UI elements during API call
            button.enabled = false;
            inputField.text = "";
            inputField.enabled = false;

            // NPC's response
            var completionResponse = await openai.CreateChatCompletion(new CreateChatCompletionRequest()
            {
                Model = "gpt-3.5-turbo-0613",
                Messages = messages
            });

            if (completionResponse.Choices != null && completionResponse.Choices.Count > 0)
            {
                var assistantMessage = completionResponse.Choices[0].Message;
                assistantMessage.Content = assistantMessage.Content.Trim();

                messages.Add(assistantMessage);

                // Append assistant message
                AppendCorrectMessage(assistantMessage);

                //Do the reply
                await Reply_Input();

            }
            else
            {
                Debug.LogWarning("No valid response from the OpenAI API.");
            }

            // Enable UI elements after API call
            button.enabled = true;
            inputField.enabled = true;


        }
    }
}

但是我发现更正和回复内容不会按预期显示的问题。例如,它将首次在两个内容中显示“-”,但在此之后它会按预期正常工作。在其他情况下,它将在第一次正常工作,但在此之后它将交换每个内容字段中的内容,这意味着更正字段进行回复,回复字段进行更正。有人可以帮忙找到问题并解决问题吗?

问题

C# unity-游戏引擎 scrollview openai-api chatgpt-api

评论


答: 暂无答案