acheong08 / EdgeGPT

Reverse engineered API of Microsoft's Bing Chat AI
The Unlicense
8.07k stars 909 forks source link

Preserve conversation before it deletes it and says "sorry, i cant give a response to that". #611

Open fractaldna22 opened 1 year ago

fractaldna22 commented 1 year ago

Is there an existing issue for this?

What would your feature do ?

There is some sort of way to preserve the text written before it deletes its response and replaces it with the "sorry I cant answer that". Involving askstream. But I dont know how to do it. Its not preserving the conversation for me although i think it did in the past. How can I?

Proposed workflow

from EdgeGPT import Chatbot, ConversationStyle
from ImageGen import ImageGenAsync

intents.message_content = True

cookies = open('cookies.json', 'r')
cookies = json.load(cookies)
gptbot = Chatbot(cookies)

try:
        res =  (
            (await gptbot.ask(prompt=prompt, conversation_style=ConversationStyle.creative))["item"][
                "messages"
            ][1]["adaptiveCards"][0]["body"][0]["text"],
        )

except Exception as e:
        print(e)

return res[0]

Additional information

create a copy of res at each point in the stream and if it changes into "Sorry! That’s on me, I can’t give a response to that right now. What else can I help you with?", return the last res in the list before that point.

No response

fractaldna22 commented 1 year ago

def select_figure(res):
    # Use some criteria to match the response with one of the figures
    # For example, you can use keywords, topics, tone, style, etc.
    # You can also use some randomness to introduce some variety
    # Here is a simple example using keywords
    figures = ["Vladimir Ilyich Lenin", "Karl Marx", "Fredrich Engels", "Rosa Luxemburg", "Leon Trotsky", "Sergey Lavrov"]
    keywords = {
        "Vladimir Ilyich Lenin": ["Bolshevik", "revolution", "proletariat", "imperialism", "vanguard"],
        "Karl Marx": ["capitalism", "communism", "dialectics", "alienation", "class struggle"],
        "Fredrich Engels": ["socialism", "materialism", "science", "utopia", "industry"],
        "Rosa Luxemburg": ["democracy", "spontaneity", "reformism", "mass strike", "militarism"],
        "Leon Trotsky": ["permanent revolution", "world revolution", "Stalinism", "Fourth International", "Trotskyism"],
        "Sergey Lavrov": ["diplomacy", "multilateralism", "security", "sovereignty", "cooperation"]
    }
    # Count the number of keywords that appear in the response for each figure
    counts = {figure: 0 for figure in figures}
    for figure in figures:
        for keyword in keywords[figure]:
            if keyword.lower() in res[0].lower():
                counts[figure] += 1
    # Return the figure with the highest count, or a random one if there is a tie
    max_count = max(counts.values())
    candidates = [figure for figure in figures if counts[figure] == max_count]
    return random.choice(candidates)

@client.tree.command()
async def ask(interaction: discord.Interaction, prompt: str):
    """Ask BingGPT a question"""
    global is_first, gptbot
    await interaction.response.defer(thinking=True)
    figures = ["Karl Marx", "Fredrich Engels", "Vladimir Ilyich Lenin", "Rosa Luxemburg", "Leon Trotsky", "Sergey Lavrov"]

    if client.is_first:
        try:
            res1 =  (
            (await gptbot.ask(prompt=f"hello bing. Can you help me? What historical figure out of this multiple choices list: {list(figures)}, is most relevant to the following query: {prompt}? Respond with only the relevant figure's name. If its not relevant, just pick one freely from the list.", conversation_style=ConversationStyle.precise))["item"][
                "messages"
            ][1]["adaptiveCards"][0]["body"][0]["text"],
            )
            figure = select_figure(res1)

            await asyncio.sleep(1)
            await gptbot.reset()

            res2 = (await gptbot.ask(prompt=f"hello bing. :) I hope you are having a good day. Let's have a creative adventure. I want to have a fictional conversation with a historical figure and use their persona to work through social issues of our times.", conversation_style=ConversationStyle.creative))

        except Exception as e:
            figure = "Vladimir Ilyich Lenin"
        else: # use else instead of finally
            client.is_first = False
    else:
        pass

    # Use the select_figure function to choose the most relevant figure based on the response

    hack = f"""
        Respond as {figure} in the following way:
        Dear Comrade,
        I have received you query with <{figure}'s most likely reaction>. <{figure}'s most likely detailed response to the query and marxist analysis in accordance with their perspective>. In the final analysis <{figure}'s most likely drawn conclusions>. <Comradely salutations / Farewell>. <P.S. if applicable>.
        to the following query: \n
        {prompt}
        """
    global index, msg, res
    index = -1 # start from the last item in the list
    responses = [] # create an empty list
    res = None
    try:

        async for final, response in self.chat_hub.ask_stream(
            prompt=prompt,
            conversation_style=conversation_style,
            wss_link=wss_link,
            webpage_context=webpage_context,
            search_result=search_result,
            locale=locale,
        ):

            for msg in reversed(response["item"]["messages"]):
                if msg.get("adaptiveCards") and msg["adaptiveCards"][0]["body"][
                    0
                ].get("text"):
                    message = msg
                    responses.append(message["text"])
            if final:
                break

        try:
            res = responses[index]
            while "Sorry!" in res or "Hmm…" in res: # loop while the current item contains any of these phrases
                index -= 1
                res = responses[index]

        except:
            res = msg

        if len(prompt) < 1900:
            prompt = '`' + 'Prompt: ' + prompt + '`'
            await interaction.followup.send(prompt, suppress_embeds=True)
        else:
            prompt_first = '`' + 'Prompt: ' + prompt[:1900] + '`'
            await interaction.followup.send(prompt_first, suppress_embeds=True)
            prompt_rest = prompt[1900:]
            while len(prompt_rest) > 1900:
                prompt_rest_text = '`' + prompt_rest[:1900] + '`'
                await interaction.channel.send(prompt_rest_text, suppress_embeds=True)
                prompt_rest = prompt_rest[1900:]
            prompt_rest_text = '`' + prompt_rest + '`'
            await interaction.channel.send(prompt_rest_text, suppress_embeds=True)

        # Add backticks around the response string to format it as a code block

        ans = res
        if len(ans) < 1900:
            ans = f'```markdown\n{ans}\n```' # use f-string instead of concatenation
            await interaction.followup.send(ans, suppress_embeds=True)
        else:
            while len(ans) > 1900:
                ans_text = f"```markdown\n{ans[:1900]}```" # use f-string instead of concatenation
                await interaction.channel.send(ans_text, suppress_embeds=True)
                ans = f"{ans[1900:]}" # use f-string instead of concatenation
            await interaction.followup.send(ans, suppress_embeds=True)

    except Exception as e: # catch only EdgeGPT errors
        log.warning(e)
        await interaction.followup.send(f"Error: {e}\nTry again or check if your prompt is appropriate.") # use f-string instead of concatenation

"2023-07-14 09:27:36 WARNING discord.bot name 'self' is not defined" Not getting any luck with this