### Create Chat Completion (PHP) Source: https://github.com/xing61/zzz-api/blob/main/openai接口说明.md This PHP code demonstrates how to set up headers and parameters for a chat completion request. It includes an example of a single user message. ```php 'user', "content" => "1+100="]; $messages = array(); $messages[] = $one; $params['messages'] = $messages; } // 调用请求 ?> ``` -------------------------------- ### Example cURL Request with Authentication Source: https://github.com/xing61/zzz-api/blob/main/openai接口说明.md This cURL command demonstrates how to make a request to the chat completions endpoint, including the necessary Content-Type and Authorization headers with your Zzengzeng API key. ```bash curl -H "Content-Type: application/json" -H "Authorization: Bearer 你在智增增的key" -XPOST https://api.zhizengzeng.com/v1/chat/completions -d '{"messages": [{"role":"user","content":"请介绍一下你自己"}]}' | iconv -f utf-8 -t utf-8 ``` -------------------------------- ### Python Function Calling Example Source: https://github.com/xing61/zzz-api/blob/main/示例代码/函数调用.md This Python script demonstrates a complete function calling workflow with the OpenAI API. It includes setting up API keys, defining a tool (get_current_weather), and orchestrating the conversation flow between the user, the GPT model, and the tool. ```python import os import openai import requests import time import json import time API_SECRET_KEY = "xxxx"; BASE_URL = "https://api.zhizengzeng.com/v1" openai.api_key = API_SECRET_KEY openai.api_base = BASE_URL # Example dummy function hard coded to return the same weather # In production, this could be your backend API or an external API def get_current_weather(location, unit="fahrenheit"): """Get the current weather in a given location""" weather_info = { "location": location, "temperature": "72", "unit": unit, "forecast": ["sunny", "windy"], } return json.dumps(weather_info) def run_conversation(): # Step 1: send the conversation and available functions to GPT messages = [{"role": "user", "content": "What's the weather like in Boston?"}] functions = [ { "name": "get_current_weather", "description": "Get the current weather in a given location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA", }, "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, }, "required": ["location"], }, } ] response = openai.ChatCompletion.create( model="gpt-3.5-turbo-0613", messages=messages, functions=functions, # function_call="auto", # auto is default, but we'll be explicit function_call={"name": "get_current_weather"}, # auto is default, but we'll be explicit ) response_message = response["choices"][0]["message"] # Step 2: check if GPT wanted to call a function if response_message.get("function_call"): # Step 3: call the function # Note: the JSON response may not always be valid; be sure to handle errors available_functions = { "get_current_weather": get_current_weather, } # only one function in this example, but you can have multiple function_name = response_message["function_call"]["name"] function_to_call = available_functions[function_name] function_args = json.loads(response_message["function_call"]["arguments"]) function_response = function_to_call( location=function_args.get("location"), unit=function_args.get("unit"), ) # Step 4: send the info on the function call and function response to GPT response_message["content"]="Testing" #注意这里要传入content,content不能为空,否则openai会报错 messages.append(response_message) # extend conversation with assistant's reply messages.append( { "role": "function", "name": function_name, "content": function_response, } ) # extend conversation with function response second_response = openai.ChatCompletion.create( model="gpt-3.5-turbo-0613", messages=messages, ) # get a new response from GPT where it can see the function response return second_response #print(run_conversation()) if __name__ == '__main__': run_conversation(); ``` -------------------------------- ### Python Chat Completion using Official Library Source: https://github.com/xing61/zzz-api/blob/main/openai接口说明.md Demonstrates how to use the official OpenAI Python library to create a chat completion. Ensure you have the library installed and your API key and base URL are correctly configured. ```python import os import openai openai.api_key = "您的api_secret_key" openai.base_url = "https://api.zhizengzeng.com/v1" # 要注意openai的版本号,目前最新的是base_url,旧版可能是api_base chat_completion = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[{ "role": "user", "content": "Hello world" }] ) print(chat_completion.choices[0].message.content) ``` -------------------------------- ### PHP Chat Completion Request Source: https://github.com/xing61/zzz-api/blob/main/openai接口说明.md Example of making a POST request to the chat completions endpoint using PHP. ```php $cburl = 'https://api.zhizengzeng.com/v1/chat/completions'; $chatgpt_resp = Tool::_request('post', $cburl, $params, $headers); $data = json_decode($chatgpt_resp, true); ``` -------------------------------- ### Image Understanding using Base64 Encoding Source: https://github.com/xing61/zzz-api/blob/main/示例代码/gpt-4-vision.图片理解.md This example demonstrates how to use the GPT-4 Vision model with a base64 encoded image. You will need to replace the placeholder API key and URL with your specific zzz-api credentials. ```python # Direct replacement of key and url with your zzz-api credentials is required. # key is the secret key obtained from the zzz-api backend. # url is: https://api.zhizengzeng.com/v1/chat/completions # Example structure (actual base64 encoding and client setup omitted for brevity): # from openai import OpenAI # import base64 # # API_SECRET_KEY = "your_secret_key" # BASE_URL = "https://api.zhizengzeng.com/v1/" # # client = OpenAI(api_key=API_SECRET_KEY, base_url=BASE_URL) # # # Assume image_path points to your image file # with open(image_path, "rb") as image_file: # encoded_string = base64.b64encode(image_file.read()).decode('utf-8') # # response = client.chat.completions.create( # model="gpt-4-vision-preview", # messages=[ # { # "role": "user", # "content": [ # {"type": "text", "text": "What’s in this image?"}, # { # "type": "image_url", # "image_url": { # "url": f"data:image/jpeg;base64,{encoded_string}" # } # } # ] # } # ], # max_tokens=300, # ) # # print(response) ``` -------------------------------- ### Call Chat Completions API in JavaScript Source: https://github.com/xing61/zzz-api/blob/main/示例代码/js.md This snippet demonstrates how to import and use the chatgpt function defined previously. It shows a basic example of sending a message to the API and logging the response. This requires the chatgpt.js file to be in the same directory or accessible via the module path. ```javascript // test.js文件 import {chatgpt} from "./chatgpt.js"; // 调用chatgpt接口 chatgpt({ "messages": [ {"role": "user", "content": "1+100="} ] }).then(res => {console.log(res)}) ``` -------------------------------- ### Example API Response Structure Source: https://github.com/xing61/zzz-api/blob/main/openai接口说明.md This JSON object illustrates the structure of a successful API response, including Zzengzeng's custom 'code' and 'msg' fields alongside standard OpenAI response fields. ```json { "code": 0, "msg": "", "id": "as-bcmt5ct4iy", "created": 1680167072, "choices":[{"message":{"role":"assistant","content":"1+100=101"},"finish_reason":"stop","index":0}], "usage": { "prompt_tokens": 470, "completion_tokens": 198, "total_tokens": 668 } } ``` -------------------------------- ### Python Chat Completion using Requests Library Source: https://github.com/xing61/zzz-api/blob/main/openai接口说明.md Example of making a chat completion request using the Python requests library. This method requires manual construction of the request payload and headers. ```python import os import requests import time import json def chat_completions(): url="https://api.zhizengzeng.com/v1/chat/completions" api_secret_key = 'xxxxxxxxx'; # 你的api_secret_key headers = {'Content-Type': 'application/json', 'Accept':'application/json', 'Authorization': "Bearer "+api_secret_key} params = {'user':'张三', 'messages':[{'role':'user', 'content':'1+100='}]}; r = requests.post(url, json.dumps(params), headers=headers) print(r.json()) if __name__ == '__main__': chat_completions(); ``` -------------------------------- ### Image Understanding using Image URL Source: https://github.com/xing61/zzz-api/blob/main/示例代码/gpt-4-vision.图片理解.md This snippet shows how to use the GPT-4 Vision model with a provided image URL. Ensure you have the OpenAI Python library installed and replace placeholder API keys and base URLs with your actual credentials. ```python from openai import OpenAI API_SECRET_KEY = "xxxxxx"; BASE_URL = "https://api.zhizengzeng.com/v1/" client = OpenAI(api_key=API_SECRET_KEY, base_url=BASE_URL) response = client.chat.completions.create( model="gpt-4-vision-preview", messages=[ { "role": "user", "content": [ {"type": "text", "text": "What’s in this image?"}, { "type": "image_url", "image_url": { "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg" } }, ], } ], max_tokens=300, ) print(response) #print(response.choices[0]) ``` -------------------------------- ### C++ API Request with libcurl Source: https://github.com/xing61/zzz-api/blob/main/示例代码/c++语言.md This snippet shows how to send a POST request to the ZZZ API using libcurl. It includes setting up the API key, URL, headers, and a JSON payload for chat completions. Ensure you have libcurl and a JSON library (like jsoncpp) installed. ```c++ #include #include #include #include // You'll need to have a JSON library like jsoncpp size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp) { ((std::string*)userp)->append((char*)contents, size * nmemb); return size * nmemb; } int main() { CURL* curl; CURLcode res; std::string apiKey = "你在智增增获取的api-key"; std::string urlString = "https://api.zhizengzeng.com/v1/chat/completions"; // Initialize the Curl library curl_global_init(CURL_GLOBAL_ALL); curl = curl_easy_init(); if (curl) { struct curl_slist* headers = NULL; headers = curl_slist_append(headers, "Content-Type: application/json"); headers = curl_slist_append(headers, ("Authorization: Bearer " + apiKey).c_str()); // Prepare request data Json::Value requestData; requestData["model"] = "gpt-3.5-turbo"; Json::Value message1; message1["role"] = "system"; message1["content"] = "You are a helpful assistant."; Json::Value message2; message2["role"] = "user"; message2["content"] = "Tell me a joke."; requestData["messages"].append(message1); requestData["messages"].append(message2); Json::StreamWriterBuilder writer; std::string jsonString = Json::writeString(writer, requestData); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_URL, urlString.c_str()); curl_easy_setopt(curl, CURLOPT_POST, 1L); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonString.c_str()); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, jsonString.length()); // Response handling std::string response; curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); // Perform the request res = curl_easy_perform(curl); // Check for errors if (res != CURLE_OK) { std::cerr << "Curl error: " << curl_easy_strerror(res) << std::endl; } else { std::cout << "Response: " << response << std::endl; } // Clean up curl_slist_free_all(headers); curl_easy_cleanup(curl); } curl_global_cleanup(); return 0; } ``` -------------------------------- ### POST Request with JSON Payload Source: https://github.com/xing61/zzz-api/blob/main/示例代码/curl.md Example of sending a POST request to the chat completions API with a JSON payload and authentication headers. The output is piped to iconv for character encoding conversion. ```shell curl -H "Content-Type: application/json" -H "Authorization: Bearer $api_secret_key" -XPOST https://api.zhizengzeng.com/v1/chat/completions -d '{ "messages": [ {"role":"user","content":"请介绍一下你自己"}, {"role":"assistant","content":"您好,我是小一机器人。我能够与人对话互动,回答问题,协助创作,高效便捷地帮助人们获取信息、知识和灵感。"}, {"role":"user","content": "1+100="} ] }' | iconv -f utf-8 -t utf-8 ``` -------------------------------- ### Get Batch Job Results Source: https://github.com/xing61/zzz-api/blob/main/batch/batch示例.md Fetches the content of the results file for a completed batch job using the file ID. ```python API_SECRET_KEY = "你的智增增获取的api_key"; BASE_URL = "https://api.zhizengzeng.com/v1"; #智增增的base_url def get_result(fid): client = OpenAI(api_key=API_SECRET_KEY, base_url=BASE_URL) content = client.files.content(fid) print(content.text); ``` -------------------------------- ### Prepare Training Data for Fine-tuning Source: https://github.com/xing61/zzz-api/blob/main/fine-tune.微调/微调示例.md Use this snippet to upload your training data file (e.g., mydata.jsonl) for fine-tuning. Ensure the openai package version is compatible and the base_url is correctly set to ZhiZengZeng's endpoint. ```python API_SECRET_KEY = "你的智增增获取的api_key"; BASE_URL = "https://api.zhizengzeng.com/v1"; #智增增的base_url # files def files(): openai.api_key = API_SECRET_KEY openai.api_base = BASE_URL resp = openai.File.create( file=open("mydata.jsonl", "rb"), purpose='fine-tune' ) print(resp) ``` -------------------------------- ### Create an Assistant Source: https://github.com/xing61/zzz-api/blob/main/assistant.助手/assistant示例.md Use this snippet to create a new assistant with a specified name, instructions, tools, and model. Ensure you have your API key and base URL configured. ```python API_SECRET_KEY = "你的智增增获取的api_key"; BASE_URL = "https://api.zhizengzeng.com/v1/"; #智增增的base_url # assistant def create_assistant(): client = OpenAI(api_key=API_SECRET_KEY, base_url=BASE_URL) assistant = client.beta.assistants.create( name="Math Tutor", instructions="You are a personal math tutor. Write and run code to answer math questions.", tools=[{"type": "code_interpreter"}], model="gpt-4-1106-preview" ) print(assistant) ``` -------------------------------- ### Run Assistant with Streaming Source: https://github.com/xing61/zzz-api/blob/main/assistant.助手/assistant示例.md Initiates a run of the assistant on a thread. This version supports streaming, returning results as they are generated. Ensure you have both assistant and thread IDs. ```python API_SECRET_KEY = "你的智增增获取的api_key"; BASE_URL = "https://api.zhizengzeng.com/v1/"; #智增增的base_url # run a assistant def run(assistant_id, thread_id): client = OpenAI(api_key=API_SECRET_KEY, base_url=BASE_URL) stream = client.beta.threads.runs.create( thread_id=thread_id, # 助手的会话id要从上一步获取得到 assistant_id=assistant_id, # 助手的id要从上一步获取得到 instructions="Please address the user as Jane Doe. The user has a premium account.", stream=True ) for event in stream: print(event) ``` -------------------------------- ### 安装openai Node.js库 Source: https://github.com/xing61/zzz-api/blob/main/示例代码/兼容openai的Node.js库.md 使用npm安装openai的Node.js库。 ```bash npm install openai ``` -------------------------------- ### Python OpenAI Client Configuration (New Version) Source: https://github.com/xing61/zzz-api/blob/main/openai接口说明.md This Python snippet shows how to configure the OpenAI client in newer versions of the library, setting both the API key and the custom base URL for Zzengzeng's service. ```python client = OpenAI(api_key=API_SECRET_KEY, base_url=BASE_URL) ``` -------------------------------- ### Python OpenAI Client Configuration (Old Version) Source: https://github.com/xing61/zzz-api/blob/main/openai接口说明.md This Python snippet illustrates the older method for setting the base URL for the OpenAI client, which is necessary when using Zzengzeng's API with older library versions. ```python openai.api_base = BASE_URL ``` -------------------------------- ### Setting up Langchain with Zhizengzeng API Source: https://github.com/xing61/zzz-api/blob/main/示例代码/langchain的支持.md This snippet shows how to configure Langchain's OpenAI models and embeddings by setting environment variables for the API key and base URL of the Zhizengzeng service. It includes functions for text prediction and generating embeddings. ```python import os import requests import time import json import time from langchain.llms import OpenAI from langchain.embeddings.openai import OpenAIEmbeddings API_SECRET_KEY = "你的智增增的key"; BASE_URL = "https://api.zhizengzeng.com/v1"; #智增增的base-url os.environ["OPENAI_API_KEY"] = API_SECRET_KEY os.environ["OPENAI_API_BASE"] = BASE_URL # 根据你提供的输入来预测输出,也就是进行问答: def text(): llm = OpenAI(temperature=0.9,model='gpt-3.5-turbo-instruct') text = "What would be a good company name for a company that makes colorful socks?" print(llm(text)) def embedding(): embeddings = OpenAIEmbeddings() #text = "This is a test document." #doc_result = embeddings.embed_documents([text]); doc_result = embeddings.embed_documents( [ "Hi there!", "Oh, hello!", "What's your name?", "My friends call me World", "Hello World!" ] ); print(doc_result) # 查询 embedded_query = embeddings.embed_query("What was the name mentioned in the conversation?") print(embedded_query) if __name__ == '__main__': #text(); embedding(); ``` -------------------------------- ### Make API Request with Object-C Source: https://github.com/xing61/zzz-api/blob/main/示例代码/object-c语言(支持苹果IOS).md This snippet demonstrates how to send a POST request to a chat completions API using Object-C. It includes setting up the request with an API key, URL, JSON parameters, and handling the asynchronous response. ```Objective-C #import int main(int argc, const char * argv[]) { @autoreleasepool { NSString *apiKey = @"你的小一的api-key"; NSString *urlString = @"https://api.zhizengzeng.com/v1/chat/completions"; NSDictionary *parameters = @{ @"model": @"gpt-3.5-turbo", @"messages": @[ @{@"role": @"system", @"content": @"You are a helpful assistant."}, @{@"role": @"user", @"content": @"Tell me a joke."} ] }; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]]; request.HTTPMethod = @"POST"; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [request setValue:[NSString stringWithFormat:@"Bearer %@", apiKey] forHTTPHeaderField:@"Authorization"]; request.HTTPBody = jsonData; NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (error) { NSLog(@"Error: %@", error); } else { NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; NSLog(@"Response: %@", responseDict); } }]; [dataTask resume]; [[NSRunLoop currentRunLoop] run]; } return 0; } ``` -------------------------------- ### Python TTS Speech Synthesis Source: https://github.com/xing61/zzz-api/blob/main/示例代码/tts.speech.语音合成.md This Python function `tts` synthesizes speech from a given text query using the OpenAI API. It requires setting the API key and base URL, and saves the output to an MP3 file. The example also measures the processing time. ```Python import os from openai import OpenAI import openai import requests import time import json import time API_SECRET_KEY = "xxxx"; #智增增的key BASE_URL = "https://api.zhizengzeng.com/v1/"; #智增增的base_url # speech def tts(query): openai.api_key = API_SECRET_KEY openai.base_url = BASE_URL speech_file_path = "test.mp3"; response = openai.audio.speech.create( model="tts-1", voice="alloy", input=query ) response.stream_to_file(speech_file_path) if __name__ == '__main__': start = time.time(); tts("今天是星期二"); end = time.time() print('本次处理时间(s): ', end - start) ``` -------------------------------- ### 安装 OpenAI Python 库 Source: https://github.com/xing61/zzz-api/blob/main/示例代码/兼容openai的python库.md 使用 pip 安装 OpenAI 的 Python 库。 ```bash pip install openai ``` -------------------------------- ### Langchain中使用OpenAI Source: https://github.com/xing61/zzz-api/blob/main/README.md 在Langchain框架中,通过设置环境变量来配置智增增的API Key和Base URL,以便集成大模型功能。 ```bash export OPENAI_API_KEY="智增增后台获取的API_KEY" export OPENAI_API_BASE_URL="https://api.zhizengzeng.com/v1/" ``` -------------------------------- ### Python中使用OpenAI包 Source: https://github.com/xing61/zzz-api/blob/main/README.md 在Python项目中使用官方OpenAI库,通过设置智增增的API Key和Base URL来调用大模型服务。 ```python import openai openai.api_key = "智增增后台获取的API_KEY" openai.base_url = "https://api.zhizengzeng.com/v1/" ``` -------------------------------- ### 查询智增增账户余额 Source: https://github.com/xing61/zzz-api/blob/main/智增增API接口.md 此Python函数用于查询智增增账户的可用余额。它需要一个智增增的api_secret_key,并使用requests库发送POST请求到指定的URL。 ```python BASE_URL = "https://api.zhizengzeng.com/v1" # credit_grants def credit_grants(query): api_secret_key = API_SECRET_KEY; # 智增增的secret_key url = BASE_URL+'/dashboard/billing/credit_grants'; # 余额查询url headers = {'Content-Type': 'application/json', 'Accept':'application/json', 'Authorization': "Bearer "+api_secret_key} resp = requests.post(url, headers=headers) resp = resp.json(); json_str = json.dumps(resp, ensure_ascii=False) print(json_str) ``` -------------------------------- ### Set OpenAI API Key and Base URL using Environment Variables Source: https://github.com/xing61/zzz-api/blob/main/场景示例/langchain的支持.md This snippet demonstrates how to set the OPENAI_API_KEY and OPENAI_API_BASE environment variables to configure Langchain's OpenAI client to use a custom API endpoint. It then uses the configured client to generate text. ```python import os import requests import time import json import time from langchain.llms import OpenAI API_SECRET_KEY = "你在智增增的key"; BASE_URL = "https://api.zhizengzeng.com/v1"; #智增增的base-url os.environ["OPENAI_API_KEY"] = API_SECRET_KEY os.environ["OPENAI_API_BASE"] = BASE_URL def text(): llm = OpenAI(temperature=0.9,model='gpt-3.5-turbo-instruct') text = "What would be a good company name for a company that makes colorful socks?" print(llm(text)) if __name__ == '__main__': text(); ``` -------------------------------- ### 使用Node.js库调用兼容OpenAI的API Source: https://github.com/xing61/zzz-api/blob/main/示例代码/兼容openai的Node.js库.md 配置API密钥和基础路径,然后创建一个聊天完成请求。请确保替换"您的智增增key"为您的实际API密钥。 ```javascript const { Configuration, OpenAIApi } = require("openai"); const configuration = new Configuration({ apiKey: "您的智增增key", basePath: "https://api.zhizengzeng.com/v1" }); const openai = new OpenAIApi(configuration); const chatCompletion = await openai.createChatCompletion({ model: "gpt-3.5-turbo", messages: [{role: "user", content: "Hello world"}], }); console.log(chatCompletion.data.choices[0].message.content); ``` -------------------------------- ### Submit Fine-tuning Job Source: https://github.com/xing61/zzz-api/blob/main/fine-tune.微调/微调示例.md This code submits a fine-tuning job using the file ID obtained from the previous step. The model will be trained on the provided data. Ensure the API key and base_url are correctly configured. ```python API_SECRET_KEY = "你的智增增获取的api_key"; BASE_URL = "https://api.zhizengzeng.com/v1"; #智增增的base_url # jobs def jobs(file_id): openai.api_key = API_SECRET_KEY openai.api_base = BASE_URL resp = openai.FineTuningJob.create(training_file=file_id, model="gpt-3.5-turbo") #训练文件的id要从上一步获取得到 print(resp) ``` -------------------------------- ### Python: Generate and Download Image using OpenAI API Source: https://github.com/xing61/zzz-api/blob/main/示例代码/文字生成图片.md This Python script sends a request to the OpenAI API to generate an image based on a prompt. It then downloads and saves the generated image to a local file. Ensure you replace '$api_secret_key' with your actual API key. ```python import os import requests import time import json # 请求openai的API生成图片 def images_generations(): response = requests.post( # 智增增的API base_url,优质稳定的api "https://api.zhizengzeng.com/v1/images/generations", headers={ "Content-Type": "application/json", "Authorization": "Bearer $api_secret_key" # 用您的智增增api_secret_key替换此处 }, json={ "model": "dall-e-3", "prompt": "a cat sitting on a mat", # 图像描述 "n": 1, # 生成图像数量 "size": "512x512", # 图像大小 "response_format": "url" # 图像格式 } ) # 获取图像URL print(response.text) image_url = json.loads(response.text)("data")[0]("url") # 下载图像 response = requests.get(image_url) # 保存图像 with open("cat.png", "wb") as f: f.write(response.content) if __name__ == '__main__': images_generations(); ``` -------------------------------- ### 查询余额 Source: https://github.com/xing61/zzz-api/blob/main/智增增API接口.md 获取账户余额信息。该接口用于查询用户在智增增平台的可用金额。 ```APIDOC ## POST v1/dashboard/billing/credit_grants ### Description 获取账户余额信息。该接口用于查询用户在智增增平台的可用金额。 ### Method POST ### Endpoint `https://api.zhizengzeng.com/v1/dashboard/billing/credit_grants` ### Parameters #### Header Parameters - **Content-Type** (string) - Required - application/json - **Authorization** (string) - Required - Bearer $api_secret_key ### Request Example ```python import requests import json BASE_URL = "https://api.zhizengzeng.com/v1" API_SECRET_KEY = "YOUR_API_SECRET_KEY" # 智增增的secret_key def credit_grants(): url = BASE_URL+'/dashboard/billing/credit_grants' headers = { 'Content-Type': 'application/json', 'Accept': 'application/json', 'Authorization': "Bearer "+API_SECRET_KEY } resp = requests.post(url, headers=headers) resp = resp.json() json_str = json.dumps(resp, ensure_ascii=False, indent=4) print(json_str) credit_grants() ``` ### Response #### Success Response (200) - **code** (integer) - 状态码,0表示成功 - **msg** (string) - 消息 - **object** (string) - 响应对象类型,固定为 "credit_summary" - **grants** (object) - 包含余额信息的对象 - **available_amount** (string) - 可用金额 #### Response Example ```json { "code": 0, "msg": "ok", "object": "credit_summary", "grants": { "available_amount": "111.8658" } } ``` ``` -------------------------------- ### Create Batch Job Source: https://github.com/xing61/zzz-api/blob/main/batch/batch示例.md Creates a batch job using a previously uploaded file ID. Specify the target endpoint and a completion window for the batch job. ```python API_SECRET_KEY = "你的智增增获取的api_key"; BASE_URL = "https://api.zhizengzeng.com/v1"; #智增增的base_url def batches(file_id): client = OpenAI(api_key=API_SECRET_KEY, base_url=BASE_URL) resp = client.batches.create(input_file_id=file_id, endpoint="/v1/chat/completions", completion_window="24h") print(resp) return resp.id ``` -------------------------------- ### API认证请求头 Source: https://github.com/xing61/zzz-api/blob/main/README.md 所有API请求都需要在HTTP头中携带用户的API Key进行认证。请从智增增管理后台获取。 ```http Content-Type: application/json Authorization: Bearer 你在智增增的key ``` -------------------------------- ### Main Execution Block for Audio Processing Source: https://github.com/xing61/zzz-api/blob/main/示例代码/translation(识别并翻译成英文).md This block demonstrates how to time the execution of audio transcription or translation functions. It calls the translation function by default. ```Python if __name__ == '__main__': start = time.time(); #audio_transcriptions("腾讯流量卡试音(1).wav"); translation("腾讯流量卡试音(1).wav"); end = time.time() print('本次处理时间(s): ', end - start) ``` -------------------------------- ### Audio Transcription and Translation with Whisper API Source: https://github.com/xing61/zzz-api/blob/main/示例代码/audio_transcriptions(语音识别).md This Python script demonstrates how to use the Whisper API for audio transcription and translation. Ensure you have your API key and the necessary audio file. ```Python import os import openai import requests import time import json import time API_SECRET_KEY = "你的智增增获取的api_key"; BASE_URL = "https://api.zhizengzeng.com/v1" # audio_transcriptions def audio_transcriptions(file_name): openai.api_key = API_SECRET_KEY openai.api_base = BASE_URL audio_file = open(file_name, "rb") resp = openai.Audio.transcribe("whisper-1", audio_file) json_str = json.dumps(resp, ensure_ascii=False) #打出中文来 print(json_str) def translation(file_name): openai.api_key = API_SECRET_KEY openai.api_base = BASE_URL audio_file = open(file_name, "rb") resp = openai.Audio.translate("whisper-1", audio_file) json_str = json.dumps(resp, ensure_ascii=False) #打出中文来 print(json_str) if __name__ == '__main__': start = time.time(); #audio_transcriptions("腾讯流量卡试音(1).wav"); translation("腾讯流量卡试音(1).wav"); end = time.time() print('本次处理时间(s): ', end - start) ``` -------------------------------- ### 配置并运行聊天完成示例 Source: https://github.com/xing61/zzz-api/blob/main/示例代码/兼容openai的python库.md 配置 API 密钥和基础 URL,然后使用聊天模型发送消息并获取响应。 ```python import os import openai openai.api_key = "您在智增增的api_secret_key" openai.api_base = "https://api.zhizengzeng.com/v1/" #智增增的base_url,注意加上最后的/ chat_completion = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[{ "role": "user", "content": "Hello world" }] ) print(chat_completion.choices[0].message.content) ``` -------------------------------- ### Use Fine-tuned Model for Chat Completions Source: https://github.com/xing61/zzz-api/blob/main/fine-tune.微调/微调示例.md Once fine-tuning is complete, use this snippet to interact with your custom model. Replace the placeholder model name with your actual fine-tuned model ID obtained from the previous steps. ```python API_SECRET_KEY = "你的智增增获取的api_key"; BASE_URL = "https://api.zhizengzeng.com/v1"; #智增增的base_url # chat def chat_completions(query): openai.api_key = API_SECRET_KEY openai.api_base = BASE_URL resp = openai.ChatCompletion.create( model="ft:gpt-3.5-turbo-0613xxxxxxxxxxxxxxxxxxx", # 模型名字要从上一步获取得到 messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": query} ] ) print(resp) ``` -------------------------------- ### Upload Batch Data File Source: https://github.com/xing61/zzz-api/blob/main/batch/batch示例.md Uploads a file to be used for batch processing. Ensure the file is in JSONL format and specify 'batch' as the purpose. ```python API_SECRET_KEY = "你的智增增获取的api_key"; BASE_URL = "https://api.zhizengzeng.com/v1"; #智增增的base_url # files def files(): client = OpenAI(api_key=API_SECRET_KEY, base_url=BASE_URL) resp = client.files.create( file=open("test.jsonl", "rb"), purpose='batch' ) print(resp) return resp.id ``` -------------------------------- ### Create Chat Completion Source: https://github.com/xing61/zzz-api/blob/main/openai接口说明.md This endpoint allows you to create chat completions by sending a POST request with your messages and parameters. It supports various programming languages for integration. ```APIDOC ## POST /v1/chat/completions ### Description Creates a chat completion by sending messages and parameters to the API. ### Method POST ### Endpoint https://api.zhizengzeng.com/v1/chat/completions ### Parameters #### Request Body - **messages** (array) - Required - The messages to send to the model. - **model** (string) - Required - The model to use for chat completion. - **user** (string) - Optional - A unique identifier representing your end-user. ### Request Example ```json { "user": "张三", "messages": [ { "role": "user", "content": "1+100=" } ] } ``` ### Response #### Success Response (200) - **code** (integer) - Status code, 0 for success. - **msg** (string) - Message, empty for success. - **id** (string) - Unique identifier for the completion. - **created** (integer) - Unix timestamp of when the completion was created. - **choices** (array) - An array of choices, each containing a message, finish reason, and index. - **message** (object) - **role** (string) - The role of the author of the message (e.g., 'assistant'). - **content** (string) - The content of the message. - **finish_reason** (string) - The reason the model stopped generating tokens. - **index** (integer) - The index of the choice in the array. - **usage** (object) - Information about token usage. - **prompt_tokens** (integer) - Number of tokens in the prompt. - **completion_tokens** (integer) - Number of tokens in the completion. - **total_tokens** (integer) - Total tokens used. #### Response Example ```json { "code": 0, "msg": "", "id": "as-bcmt5ct4iy", "created": 1680167072, "choices": [ { "message": { "role": "assistant", "content": "1+100=101" }, "finish_reason": "stop", "index": 0 } ], "usage": { "prompt_tokens": 470, "completion_tokens": 198, "total_tokens": 668 } } ``` ``` -------------------------------- ### Create Chat Completion (cURL) Source: https://github.com/xing61/zzz-api/blob/main/openai接口说明.md Use this cURL command to send a chat completion request to the API. Ensure you replace '$api_secret_key' with your actual API key and adjust the messages as needed. ```curl curl -H "Content-Type: application/json" -H "Authorization: Bearer $api_secret_key" -XPOST https://api.zhizengzeng.com/v1/chat/completions -d '{ "messages": [ {"role":"user","content":"请介绍一下你自己"}, {"role":"assistant","content":"您好,我是智增增机器人。我能够与人对话互动,回答问题,协助创作,高效便捷地帮助人们获取信息、知识和灵感。"}, {"role":"user","content": "1+100="} ] }' | iconv -f utf-8 -t utf-8 ``` -------------------------------- ### 智增增API通用请求示例 Source: https://github.com/xing61/zzz-api/blob/main/智增增API接口.md 此示例展示了如何使用curl命令与智增增API进行交互,包括设置必要的请求头和发送消息内容。请确保使用智增增提供的api_secret_key。 ```shell curl -H "Content-Type: application/json" -H "Authorization: Bearer $api_secret_key" -XPOST https://api.zhizengzeng.com/v1/chat/completions -d '{"messages": [{"role":"user","content":"请介绍一下你自己"}]}' | iconv -f utf-8 -t utf-8 ``` -------------------------------- ### HTTP请求调用API Source: https://github.com/xing61/zzz-api/blob/main/README.md 直接通过HTTP请求调用大模型API,需要在请求头中包含API Key,并设置正确的Base URL。 ```http POST /v1/chat/completions HTTP/1.1 Host: api.zhizengzeng.com Content-Type: application/json Authorization: Bearer 智增增后台获取的API_KEY ``` -------------------------------- ### Python Stream Chat Completion Source: https://github.com/xing61/zzz-api/blob/main/示例代码/流式示例stream.md This Python script shows how to make a streaming chat completion request to the ZhiZengZeng API. Replace 'xxxxx' with your actual API key. The function prints content as it is received. ```python import os import openai import requests import time import json import time API_SECRET_KEY = "xxxxx"; # 你在智增增的key BASE_URL = "https://api.zhizengzeng.com/v1" def stream_chat(prompt: str): openai.api_key = API_SECRET_KEY openai.api_base = BASE_URL for chunk in openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[{"role": "user", "content": prompt}], stream=True, ): content = chunk["choices"][0].get("delta", {}).get("content") if content is not None: print(content) if __name__ == '__main__': stream_chat("圆周率的前10位"); ``` -------------------------------- ### Unity C# API POST Request Source: https://github.com/xing61/zzz-api/blob/main/示例代码/c This snippet demonstrates how to send a POST request with a JSON payload from a Unity application. It uses Coroutines and UnityWebRequest for asynchronous operations. Ensure you have the LitJson library imported into your Unity project. ```csharp using System; using System.Collections; using System.Text; using UnityEngine; using UnityEngine.Networking; using LitJson; //这个需要百度下载一个LitJson库然后放入Assets目录下 public class ChatGPTScripts : MonoBehaviour { private string postUrl = "https://api.zhizengzeng.com/v1/chat/completions"; private const string user = "user"; private const string messages = "messages"; private void Start() { StartCoroutine(Post()); } IEnumerator Post() {/**//**/ WWWForm form = new WWWForm();/**/ // 配置数据 string apiSecretKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; JsonData data = new JsonData(); data[user] = "测试者"; // messages JsonData messageDatas = new JsonData(); messageDatas.SetJsonType(JsonType.Array); // 单个 message JsonData messageData = new JsonData(); messageData["role"] = "user"; messageData["content"] = "请介绍一下你自己"; // 存入 message messageDatas.Add(messageData); // 配置内容 data[messages] = messageDatas; // 编码 JSON var dataBytes = Encoding.Default.GetBytes(data.ToJson()); UnityWebRequest request = UnityWebRequest.Post(postUrl, form); request.uploadHandler = new UploadHandlerRaw(dataBytes); // 发送 https request.SetRequestHeader("Content-Type", "application/json"); request.SetRequestHeader("Authorization", "Bearer "+apiSecretKey); yield return request.SendWebRequest(); if(request.isHttpError || request.isNetworkError) { Debug.LogError(request.error); } else { string receiveContent = request.downloadHandler.text; Debug.Log(receiveContent); } } } ``` -------------------------------- ### API响应示例 Source: https://github.com/xing61/zzz-api/blob/main/示例代码/兼容openai的Node.js库.md 展示了成功调用API后预期的控制台输出。 ```text Hello there! How can I assist you today ? ```