ChatGPT networking implementation [complete code + calling method]

Article directory

    • Interface code
    • Calling method
    • Test effect

Interface code

<?php
header("Content-Type:application/json;charset=utf-8");
date_default_timezone_set('Asia/Shanghai');
header("Access-Control-Allow-Origin: *");
ob_start(); // Turn on output buffering



function send_post_lw($post_data) {<!-- -->
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,"https://lite.duckduckgo.com/lite/");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');
    $headers = array();
    $headers[] = "Host: lite.duckduckgo.com";
    $headers[] = "Content-Type: application/x-www-form-urlencoded";
    $headers[] = "Origin: https://lite.duckduckgo.com";
    $headers[] = "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101 Firefox/107.0";
    $headers[] = "Accept: text/html,application/xhtml + xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8";
    $headers[] = "Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2" ;
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    $result = curl_exec($ch);
    if (curl_errno($ch)) {<!-- -->
        $content=array(
            'code' => "500",
            'msg' => "Access error");
        print_r(json_encode($content,JSON_NUMERIC_CHECK|JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));
        exit();
    }
    curl_close($ch);
    return $result;
}
function calculate_cost($num_tokens){<!-- -->
    $cost_per_token = 0.000048;
    $total_cost = $num_tokens * $cost_per_token;
    return $total_cost;
}
function send_post_json($jsonStr,$key)
{<!-- -->
    $timeout = 120;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_URL, "https://api.openai.com/v1/chat/completions");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT, $timeout);
    $headers = array();
    $headers[] = "Host: api.openai.com";
    $headers[] = "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101 Firefox/107.0";
    $headers[] = "Accept: text/html,application/xhtml + xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8";
    $headers[] = "Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2" ;
    $headers[] = "Content-Type: application/json;charset=utf-8";
    $headers[] = "Authorization: Bearer ".$key;
    curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
    $result = curl_exec($ch);
    if (curl_errno($ch)) {<!-- -->
        $content=array(
            'code' => "500",
            'msg' => "Access error");
        print_r(json_encode($content,JSON_NUMERIC_CHECK|JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));
        exit();
    }
    curl_close($ch);
    return $result;
}



@$message=$_REQUEST['message'];

if(empty($message)){<!-- -->
    $content = array(
        'code' => "203",
        'msg' => "Please enter the question to be answered"
    );
    print_r(json_encode($content, JSON_NUMERIC_CHECK|JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));
    exit();
} else {<!-- -->

    ob_flush();
    flush();
    
    $message_bm = urlencode($message);
    $post_data = "q=$message_bm & amp;df= & amp;kl=cn-zh";
    $data = send_post_lw($post_data);

  
    ob_flush();
    flush();

    preg_match_all("/<a rel="nofollow" href="(.*?)" class='result-link'>.*<\/a>/", $data, $urlss) ;
    preg_match_all("/<td class='result-snippet'>\s*(.*?)\s*<\/td>/", $data, $contentss);
    $urls = $urlss[1];
    $contents = $contentss[1];
    $array = array();
    $date = date('Y/m/d');
    for($i=0; $i<3; $i + + ){<!-- -->
        $js = $i + 1;
        $content = $contents[$i];
        $url = $urls[$i];
        $content_bq = strip_tags($content);
        $string = "[$js]:"$content_bq"\
URL:$url";
        array_push($array, $string);
    }
    $allcontents = implode("\
\
", $array);
    $resultwb = "Web search results:\
\
" . $allcontents . "\
\
Current date:$date\
\
Instructions: Using the provided web search results, write a comprehensive reply to the given query. If the provided search results refer to multiple subjects with the same name, write separate answers for each subject.\
\
Query: $message\
\
Reply in 中文";

    ob_flush();
    flush();

    if (array_key_exists('key', $_GET)) {<!-- -->
        $keys = $_GET['key'];
    } else {<!-- -->
        $keys = "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";
    }

    $postdata = array(
        'model' => "gpt-3.5-turbo-16k",
        'messages' => array(
            array(
                'role' => "user",
                'content' => "$resultwb"
            )
        ),
        'temperature' => 0.7
    );

    $jsonStr = json_encode($postdata);
    $data = send_post_json($jsonStr, $keys);


    ob_flush();
    flush();

    $jsondata = json_decode($data,true);
    $choices = $jsondata['choices'][0]['message']['content'];
    if(empty($choices)){<!-- -->
        $content = array(
            'code' => "201",
            'msg' => "Failed to obtain, please contact the webmaster (key is invalid)"
        );
        print_r(json_encode($content,JSON_NUMERIC_CHECK|JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));
    } else {<!-- -->
        $tokens = $jsondata['usage']['total_tokens'];
        $money = calculate_cost($tokens);
        $content = array(
            'code' => "200",
            'msg' => "Get successful",
            'total_money' => "$money",
            'message' => "$message",
            'answer' => "$choices"
        );
        print_r(json_encode($content,JSON_NUMERIC_CHECK|JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));
    }
}
ob_end_flush(); // End output buffering
?>

Calling method

# coding=utf-8
import requests
import json

def ask_question(question):
    base_url = "The interface address you deployed"
    response = requests.get(base_url, params={<!-- -->"message": question}, stream=True)

    # Check response status
    if response.status_code != 200:
        return {<!-- -->"error": f"API responded with status code {response.status_code}"}

    # Process streaming output
    content = []
    for chunk in response.iter_content(chunk_size=None): # Use None to read the entire content chunk
        decoded_chunk = chunk.decode('utf-8') # Convert the content chunk from bytes to string
        content.append(decoded_chunk)


    # Merge all content blocks and parse JSON
    full_content = ''.join(content)
    return json.loads(full_content)


if __name__ == "__main__":
    question = input("Please enter your question:")
    response = ask_question(question)
    answer=response["answer"]
    print(answer)

Test effect

Please enter your question: How do you see Japan putting nuclear wastewater into the ocean this year?
According to the search results provided, the Japanese government plans to discharge the nuclear wastewater generated by the Fukushima nuclear accident into the sea near Fukushima in the summer of 2023. These nuclear wastewater will contain the radioactive isotope "Tritium" (Tritium). This decision has triggered widespread concern and controversy at home and abroad.

Discharging nuclear wastewater into the ocean may pose risks to human health and marine ecology around the world. Many countries and regions, especially China and South Korea, strongly criticized and opposed this decision. Some international environmental groups and neighboring countries have also expressed concerns about the nuclear wastewater discharge plan.

However, the United States expressed support for the Japanese government's decision. In addition, European countries have not expressed a clear position on this issue.

In short, the decision to discharge nuclear wastewater into the ocean sparked widespread controversy. Different countries and regions hold different views on this, and environmental organizations and people around the world have also expressed concerns about this.

Please note that the above answers are based solely on the search results provided and may not cover all relevant information. It is recommended to further search for reliable news sources or government statements for more comprehensive and accurate information.