Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix UI/UX Page Chats [Memory Prompt] [Stored Local Storage] #3369

Merged
merged 1 commit into from
Nov 27, 2023

Conversation

H0llyW00dzZ
Copy link
Contributor

  • [+] fix(chat.ts): update the memory prompt in onFinish callback
  • [+] feat(chat.ts): update the current session with lastSummarizeIndex and memoryPrompt

Issue known : [Bug] Memory Prompt not stored properly in top 1 of chat list #3368

- [+] fix(chat.ts): update the memory prompt in onFinish callback
- [+] feat(chat.ts): update the current session with lastSummarizeIndex and memoryPrompt
@H0llyW00dzZ
Copy link
Contributor Author

Show off

image

A memory prompt after summarizing:

Go Programming Language Expert

System Memory Prompt:

The provided Go code implements a reverse proxy server that forwards incoming requests to a target URL. It includes command-line flags to configure the server's behavior, such as the target URL, request rate limit, and server port. The code uses various Go packages to handle HTTP requests, rate limiting, concurrency, logging, and graceful server shutdown.

The main function is the entry point of the program. It parses command-line flags, configures the server, initializes necessary components, and starts the server. The loggingMiddleware function logs incoming requests, and the handleProxy function decides whether to block or proxy requests based on the request path and headers. The waitForExitSignal function listens for OS signals and triggers a graceful server shutdown.

Each function is explained in detail, along with relevant code snippets, to provide a comprehensive understanding of the code's functionality.

This summary can be used as a prompt for future context when discussing the implementation of a reverse proxy server in Go, including command-line configuration, rate limiting, concurrency control, logging, and graceful server shutdown.

Message From ChatGPT:

This is a Go program that implements a reverse proxy server. A reverse proxy server receives requests from clients and forwards them to another server, acting as an intermediary. The code includes command-line flags to configure the server's behavior and uses various Go packages to handle HTTP requests, rate limiting, concurrency, logging, and graceful server shutdown.

Let's go through the code and explain its different parts.

Package and Imports

The code begins with the package declaration package main. In Go, the main package is used to create an executable program.

The code imports several packages required for the program's functionality, including context, crypto/tls, flag, fmt, net/http, net/http/httputil, net/url, os, os/signal, strings, syscall, time, github.com/sirupsen/logrus, and golang.org/x/time/rate. Each package provides specific functionality used in the program.

Global Variables

After the imports, the code declares several global variables. These variables store the values of command-line arguments and are used to configure the server. The variables are declared using the var keyword and their types are specified.

main Function

The main function is the entry point of the program. It performs the following tasks:

  1. Parses the command-line flags to configure the server. The flag.StringVar, flag.Int64Var, flag.Float64Var, and flag.IntVar functions are used to define and parse the command-line arguments.

  2. Customizes the usage message and descriptions for each flag using the flag.Usage function. This function is called when the user runs the program with the -h flag to display the program's usage information.

  3. Creates a new logger instance using the logrus.New function. The logger is configured to output log messages in a specific format and color.

  4. Initializes rate limiter and concurrency limiter based on the command-line arguments. The rate.NewLimiter function from the golang.org/x/time/rate package is used to create a rate limiter, and a buffered channel is used as a concurrency limiter.

  5. Sets up the HTTP handler for the proxy functionality using the http.Handle function. The handler is wrapped with a logging middleware using the loggingMiddleware function. The handler function is defined as an anonymous function that limits the maximum request size, checks the request rate limit, acquires a concurrency limiter slot, logs the incoming request, and calls the handleProxy function to handle the request.

  6. Creates a new HTTP server instance with custom TLS settings using the http.Server struct. The server's address, handler, and TLS configuration are set.

  7. Starts the server in a new goroutine using the server.ListenAndServe or server.ListenAndServeTLS methods, depending on whether TLS is enabled.

  8. Blocks the main goroutine until an exit signal is received, then gracefully shuts down the server using the waitForExitSignal function.

Helper Functions

The code includes several helper functions:

  • loggingMiddleware: This function logs incoming requests and calls the next handler in the chain.

  • handleProxy: This function decides whether to block the request or proxy it to the target URL. If the request path matches the blocked path and lacks CORS headers, a custom response is sent. Otherwise, a reverse proxy is created to forward the request to the target URL.

  • waitForExitSignal: This function listens for OS signals (e.g., interrupt or termination) and triggers a graceful shutdown of the server when a signal is received.

Summary

In summary, this Go program sets up a reverse proxy server that forwards incoming requests to a target URL. It uses command-line flags to configure its behavior and includes functionality for rate limiting, concurrency control, logging, and graceful server shutdown. The code is well-structured and follows common Go programming conventions.

If you have any specific questions about the code or need further assistance, feel free to ask!

Message From You:

need further assistance for explaining it each function with code snippets if its possible

Message From ChatGPT:

Certainly! Let's go through each function in the code and provide detailed explanations along with relevant code snippets.

main Function

The main function is the entry point of the program. It parses command-line flags, configures the server, initializes necessary components, and starts the server.

func main() {
    // Parse command-line flags to configure the server.
    // ...

    // Customize usage message and descriptions for each flag.
    // ...

    flag.Parse()

    // Create a new logger instance with the desired configuration.
    // ...

    // Initialize rate limiter and concurrency limiter based on command-line arguments.
    // ...

    // Set up the HTTP handler for the proxy functionality.
    // ...

    // Create a new HTTP server instance with custom TLS settings.
    // ...

    // Start the server in a new goroutine, allowing the main goroutine to listen for exit signals.
    // ...

    // Block the main goroutine until an exit signal is received, then gracefully shut down the server.
    // ...
}

loggingMiddleware Function

The loggingMiddleware function is a middleware that logs incoming requests before passing them to the next handler in the chain.

func loggingMiddleware(logger *logrus.Logger, next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        logger.Infof("[Middleware] Received request: %s %s (User-Agent: %s)", r.Method, r.URL.Path, r.UserAgent())
        next.ServeHTTP(w, r)
    })
}

handleProxy Function

The handleProxy function decides whether to block the request or proxy it to the target URL. If the request path matches the blocked path and lacks CORS headers, a custom response is sent. Otherwise, a reverse proxy is created to forward the request to the target URL.

func handleProxy(w http.ResponseWriter, r *http.Request, logger *logrus.Logger) {
    logger.Infof("[Visitor] Received request: %s %s (User-Agent: %s)", r.Method, r.URL.Path, r.UserAgent())

    // Check if the request path matches the blocked path and lacks CORS headers.
    if strings.TrimPrefix(r.URL.Path, "/api/") == blockedPath && r.Header.Get("no-cors") == "" && r.Header.Get("cors") == "" {
        // Handle the blocked path with a custom response.

        // ...

    } else {
        // If the request is not blocked, create a reverse proxy to the target URL.

        // ...
    }
}

waitForExitSignal Function

The waitForExitSignal function listens for OS signals (e.g., interrupt or termination) and triggers a graceful shutdown of the server when a signal is received.

func waitForExitSignal(server *http.Server, logger *logrus.Logger) {
    exitChan := make(chan os.Signal, 1)
    signal.Notify(exitChan, os.Interrupt, syscall.SIGTERM)
    <-exitChan

    // Create a context with a timeout for the server shutdown.
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()

    // Attempt to gracefully shut down the server.
    logger.Info("Shutting down server...")
    if err := server.Shutdown(ctx); err != nil {
        logger.Errorf("Server shutdown error: %v", err)
    } else {
        logger.Info("Server gracefully stopped")
    }
}

These are the explanations and code snippets for each function in the provided code. If you have any further questions or need additional assistance, please let me know!


JSON/JSONL

{
    "messages": [
        {
            "role": "system",
            "content": "The provided Go code implements a reverse proxy server that forwards incoming requests to a target URL. It includes command-line flags to configure the server's behavior, such as the target URL, request rate limit, and server port. The code uses various Go packages to handle HTTP requests, rate limiting, concurrency, logging, and graceful server shutdown.\n\nThe `main` function is the entry point of the program. It parses command-line flags, configures the server, initializes necessary components, and starts the server. The `loggingMiddleware` function logs incoming requests, and the `handleProxy` function decides whether to block or proxy requests based on the request path and headers. The `waitForExitSignal` function listens for OS signals and triggers a graceful server shutdown.\n\nEach function is explained in detail, along with relevant code snippets, to provide a comprehensive understanding of the code's functionality.\n\nThis summary can be used as a prompt for future context when discussing the implementation of a reverse proxy server in Go, including command-line configuration, rate limiting, concurrency control, logging, and graceful server shutdown."
        },
        {
            "role": "assistant",
            "content": "This is a Go program that implements a reverse proxy server. A reverse proxy server receives requests from clients and forwards them to another server, acting as an intermediary. The code includes command-line flags to configure the server's behavior and uses various Go packages to handle HTTP requests, rate limiting, concurrency, logging, and graceful server shutdown.\n\nLet's go through the code and explain its different parts.\n\n### Package and Imports\nThe code begins with the package declaration `package main`. In Go, the `main` package is used to create an executable program.\n\nThe code imports several packages required for the program's functionality, including `context`, `crypto/tls`, `flag`, `fmt`, `net/http`, `net/http/httputil`, `net/url`, `os`, `os/signal`, `strings`, `syscall`, `time`, `github.com/sirupsen/logrus`, and `golang.org/x/time/rate`. Each package provides specific functionality used in the program.\n\n### Global Variables\nAfter the imports, the code declares several global variables. These variables store the values of command-line arguments and are used to configure the server. The variables are declared using the `var` keyword and their types are specified.\n\n### `main` Function\nThe `main` function is the entry point of the program. It performs the following tasks:\n\n1. Parses the command-line flags to configure the server. The `flag.StringVar`, `flag.Int64Var`, `flag.Float64Var`, and `flag.IntVar` functions are used to define and parse the command-line arguments.\n\n2. Customizes the usage message and descriptions for each flag using the `flag.Usage` function. This function is called when the user runs the program with the `-h` flag to display the program's usage information.\n\n3. Creates a new logger instance using the `logrus.New` function. The logger is configured to output log messages in a specific format and color.\n\n4. Initializes rate limiter and concurrency limiter based on the command-line arguments. The `rate.NewLimiter` function from the `golang.org/x/time/rate` package is used to create a rate limiter, and a buffered channel is used as a concurrency limiter.\n\n5. Sets up the HTTP handler for the proxy functionality using the `http.Handle` function. The handler is wrapped with a logging middleware using the `loggingMiddleware` function. The handler function is defined as an anonymous function that limits the maximum request size, checks the request rate limit, acquires a concurrency limiter slot, logs the incoming request, and calls the `handleProxy` function to handle the request.\n\n6. Creates a new HTTP server instance with custom TLS settings using the `http.Server` struct. The server's address, handler, and TLS configuration are set.\n\n7. Starts the server in a new goroutine using the `server.ListenAndServe` or `server.ListenAndServeTLS` methods, depending on whether TLS is enabled.\n\n8. Blocks the main goroutine until an exit signal is received, then gracefully shuts down the server using the `waitForExitSignal` function.\n\n### Helper Functions\nThe code includes several helper functions:\n\n- `loggingMiddleware`: This function logs incoming requests and calls the next handler in the chain.\n\n- `handleProxy`: This function decides whether to block the request or proxy it to the target URL. If the request path matches the blocked path and lacks CORS headers, a custom response is sent. Otherwise, a reverse proxy is created to forward the request to the target URL.\n\n- `waitForExitSignal`: This function listens for OS signals (e.g., interrupt or termination) and triggers a graceful shutdown of the server when a signal is received.\n\n### Summary\nIn summary, this Go program sets up a reverse proxy server that forwards incoming requests to a target URL. It uses command-line flags to configure its behavior and includes functionality for rate limiting, concurrency control, logging, and graceful server shutdown. The code is well-structured and follows common Go programming conventions.\n\nIf you have any specific questions about the code or need further assistance, feel free to ask!"
        },
        { "role": "user", "content": "need further assistance for explaining it each function with code snippets if its possible " },
        {
            "role": "assistant",
            "content": "Certainly! Let's go through each function in the code and provide detailed explanations along with relevant code snippets.\n\n### `main` Function\nThe `main` function is the entry point of the program. It parses command-line flags, configures the server, initializes necessary components, and starts the server.\n\n```go\nfunc main() {\n    // Parse command-line flags to configure the server.\n    // ...\n\n    // Customize usage message and descriptions for each flag.\n    // ...\n\n    flag.Parse()\n\n    // Create a new logger instance with the desired configuration.\n    // ...\n\n    // Initialize rate limiter and concurrency limiter based on command-line arguments.\n    // ...\n\n    // Set up the HTTP handler for the proxy functionality.\n    // ...\n\n    // Create a new HTTP server instance with custom TLS settings.\n    // ...\n\n    // Start the server in a new goroutine, allowing the main goroutine to listen for exit signals.\n    // ...\n\n    // Block the main goroutine until an exit signal is received, then gracefully shut down the server.\n    // ...\n}\n```\n\n### `loggingMiddleware` Function\nThe `loggingMiddleware` function is a middleware that logs incoming requests before passing them to the next handler in the chain.\n\n```go\nfunc loggingMiddleware(logger *logrus.Logger, next http.Handler) http.Handler {\n    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n        logger.Infof(\"[Middleware] Received request: %s %s (User-Agent: %s)\", r.Method, r.URL.Path, r.UserAgent())\n        next.ServeHTTP(w, r)\n    })\n}\n```\n\n### `handleProxy` Function\nThe `handleProxy` function decides whether to block the request or proxy it to the target URL. If the request path matches the blocked path and lacks CORS headers, a custom response is sent. Otherwise, a reverse proxy is created to forward the request to the target URL.\n\n```go\nfunc handleProxy(w http.ResponseWriter, r *http.Request, logger *logrus.Logger) {\n    logger.Infof(\"[Visitor] Received request: %s %s (User-Agent: %s)\", r.Method, r.URL.Path, r.UserAgent())\n\n    // Check if the request path matches the blocked path and lacks CORS headers.\n    if strings.TrimPrefix(r.URL.Path, \"/api/\") == blockedPath && r.Header.Get(\"no-cors\") == \"\" && r.Header.Get(\"cors\") == \"\" {\n        // Handle the blocked path with a custom response.\n\n        // ...\n\n    } else {\n        // If the request is not blocked, create a reverse proxy to the target URL.\n\n        // ...\n    }\n}\n```\n\n### `waitForExitSignal` Function\nThe `waitForExitSignal` function listens for OS signals (e.g., interrupt or termination) and triggers a graceful shutdown of the server when a signal is received.\n\n```go\nfunc waitForExitSignal(server *http.Server, logger *logrus.Logger) {\n    exitChan := make(chan os.Signal, 1)\n    signal.Notify(exitChan, os.Interrupt, syscall.SIGTERM)\n    <-exitChan\n\n    // Create a context with a timeout for the server shutdown.\n    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n    defer cancel()\n\n    // Attempt to gracefully shut down the server.\n    logger.Info(\"Shutting down server...\")\n    if err := server.Shutdown(ctx); err != nil {\n        logger.Errorf(\"Server shutdown error: %v\", err)\n    } else {\n        logger.Info(\"Server gracefully stopped\")\n    }\n}\n```\n\nThese are the explanations and code snippets for each function in the provided code. If you have any further questions or need additional assistance, please let me know!"
        }
    ]
}

@Yidadaa Yidadaa merged commit ce1715c into ChatGPTNextWeb:main Nov 27, 2023
@H0llyW00dzZ H0llyW00dzZ deleted the chatz branch November 27, 2023 07:47
spongeBor pushed a commit to spongeBor/ChatGPT-Next-Web that referenced this pull request Jan 18, 2024
gaogao1030 pushed a commit to gaogao1030/ChatGPT-Next-Web that referenced this pull request May 16, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants