Saravanan666/pypi-org huggingface dataset:
Package: openai-chat-thread
GPT 聊天程式碼庫 (絕對繁體中文、串流逐步回應)這是一個使用 OpenAI API 的 GPT 聊天程式碼庫，可以讓你輕鬆地與 GPT 進行對話支持 OpenAI 的 gpt-3.5-turbo 或 gpt-4 模型(可抽換)，並且可以用作命令列界面或 Python 函式庫支援全自動簡體中文轉繁體中文(採用opencc)支援串流回應，用queue方式得到串流回應，回應的字可以一個一個跑出來CLI可測試使用import套件方式也可以運用安裝您可以使用以下命令快速安裝此程式碼庫：python3-mpipinstallopenai-chat-thread安裝後，您需要設定OPENAI_API_KEY環境變數。一種簡單的方法是在您的主目錄中創建一個.env檔案，並在其中添加以下行：OPENAI_API_KEY=your_api_key_here記得用您自己的 API 金鑰替換your_api_key_here。命令列界面安裝後，您可以在命令列中使用openai_chat_thread命令。請使用以下命令查看可用選項：python3-mopenai_chat_thread--help要與 GPT 進行對話，只需提供一個提示（prompt），例如：python3-mopenai_chat_thread"你好，GPT！"然後 GPT 將回應您的提示。函式庫用法您也可以在 Python 程式中導入此庫並使用它。只需導入openai_chat_thread函數，並提供一個提示（prompt）：fromopenai_chat_threadimportopenai_chat_thread_taiwan,openai_chat_threadq=openai_chat_thread_taiwan('妳好',model='gpt-4')# 若改用 openai_chat_thread 就不會自動轉繁體中文whileTrue:response=q.get()ifresponseisNone:breakprint(response,end="",flush=True)openai_chat_thread_taiwan函數將返回一個queue.Queue對象，您可以使用它來讀取 GPT 的回應。運作原理該程式碼庫使用 OpenAI 提供的 GPT 模型(可參數抽換模型)。當您提供一個提示（prompt）時，該程序將向 GPT 模型發送請求，並將其回應返回給您。
為了實現實時回應，我們在後台啟動一個新的執行緒，並在其中與 GPT 模型進行通信。這意味著您可以在等待 GPT 的回應時繼續執行其他任務。
該程式碼庫使用 Python 的標準庫queue和threading來實現多執行緒和通信。這使得程式碼庫易於使用，而無需依賴額外的第三方庫。
Package: openai-copilot
OpenAI CopilotYour life Copilot powered by OpenAI (CLI interface for OpenAI with searching).Features:Web access and Google search support without leaving the terminal.Automatically execute any steps predicted from prompt instructions.Human interactions on uncertain instructions to avoid inappropriate operations.InstallInstall the copilot with pip command below:pipinstallopenai-copilotSetupOpenAI API key should be set toOPENAI_API_KEYenvironment variable to enable the ChatGPT feature.OPENAI_API_BASEshould be set as well for Azure OpenAI service.Google Search API key and CSE ID should be set toGOOGLE_API_KEYandGOOGLE_CSE_ID.How to useUsage:openai-copilot[OPTIONS]YourlifeCopilotpoweredbyOpenAI

Options:--versionShowtheversionandexit.--verboseEnableverboseinformationofcopilotexecutionsteps--modelMODELOpenAImodeltouseforcopilotexecution,defaultisgpt-3.5-turbo--enable-terminalEnableCopilottorunprogramswithinterminal.EnablewithcautionsinceCopilotmayexecuteinappropriatecommands--helpShowthismessageandexit.Here is a conversation sample (user inputs are after>>>)):# openai-copilot>>>WhatisOpenAI?
OpenAIisanartificialintelligenceresearchlaboratoryconsistingofthefor-profitcorporationOpenAILPanditsparentcompany,thenon-profitOpenAIInc.Thecompanyisdedicatedtoadvancingdigitalintelligenceinawaythatissafeandbeneficialforhumanityasawhole.OpenAIwasfoundedin2015byagroupoftechnologyleadersincludingElonMusk,SamAltman,GregBrockman,andIlyaSutskever.ItsmissionistodevelopandpromotefriendlyAIforthebettermentofallhumans.
>>>WhatarethedifferencesbetweenGPT-4andGPT-3.5?
Accordingtomysearchresults,oneofthemaindifferencesbetweenGPT-4andGPT-3.5isthatwhileGPT-3.5isatext-to-textmodel,GPT-4ismoreofadata-to-textmodel.Additionally,GPT-4hastheadvantageofprovidingmorecreativerepliestoprompts.However,it'simportanttonotethatGPT-4isnotyetreleasedandthereislimitedinformationavailableaboutit.
>>>Run in Kubernetes# Run with gpt-4 (default model)kubectlrun-it--rmcopilot\--env="OPENAI_API_KEY=$OPENAI_API_KEY"\--restart=Never\--image=ghcr.io/feiskyer/openai-copilot# Run with a different model and enable verbose outputskubectlrun-it--rmcopilot\--env="OPENAI_API_KEY=$OPENAI_API_KEY"\--restart=Never\--image=ghcr.io/feiskyer/openai-copilot\----model=gpt-3.5-turbo--verboseContributionThe project is opensource at githubfeiskyer/openai-copilotwith Apache License.If you would like to contribute to the project, please follow these guidelines:Fork the repository and clone it to your local machine.Create a new branch for your changes.Make your changes and commit them with a descriptive commit message.Push your changes to your forked repository.Open a pull request to the main repository.
Package: openai-cost-tracker
OpenAI Cost TrackerA simple light weight wrapper for OpenAI's API that tracks the cost of each request. It also provides simulation mode to test the cost of a request without actually sending it to OpenAI.Installationpipinstallopenai-cost-trackerUsageImport thequery_openaifunction fromopenai_cost_tracker:fromopenai_cost_trackerimportquery_openaiUsequery_openaifunction as a drop-in replacement for openAI's completion function, such asopenai.Completion.create(). Thequery_openaiwill return the same response as the original function, but will also print the cost of the request.Turn onsimulationto test the cost of a request without actually sending it to OpenAI. Turn onprint_costto print the cost of each request.importopenaifromopenai_cost_trackerimportquery_openaiopenai.api_key="<YOUR_OPENAI_API_KEY_HERE>"prompt="Hello World!"# your prompt hereresponse=query_openai(model="gpt-4-1106-preview",# support gpt-4-1106-preview,  gpt-3.5-turbo-1106,  gpt-4messages=[{'role':'user','content':prompt}],max_tokens=5,# rest of your OpenAI params here ...simulation=True,# set to True to test the cost of a request without actually sending it to OpenAIprint_cost=True# set to True to print the cost of each request)print(response["choices"][0]["message"]["content"])OutputInput tokens: 10 | Output tokens: 5 | Cost: $0.0003 | Total: $0.0003
Hello! How can INotesThe cost of the request is calculated based on the number of tokens in the input and output using the OpenAI tokenization scheme. This is an approximation of the actual cost.
Package: openai-detector
Openai DetectorOpen AI classifier for indicating AI-written textInstallationpip3installgit+https://github.com/promptslab/openai-detector.gitUsagefromdetectorimportOpenaiDetectorsentence="""All children, except one, grow up. They soon know that they will grow up, and the way Wendy knew was this. One day when she was two years old she was playing in a garden, and she plucked another flower and ran with it to her mother. I suppose she must have looked rather delightful, for Mrs. Darling put her hand to her heart and cried, “Oh, why can’t you remain like this for ever!” This was all that passed between them on the subject, but henceforth Wendy knew that she must grow up. You always know after you are two. Two is the beginning of the end. Of course they lived at 14, and until Wendy came her mother was the chief one. She was a lovely lady, with a romantic mind and such a sweet mocking mouth. Her romantic mind was like the tiny boxes, one within the other, that come from the puzzling East, however many you discover there is always one more; and her sweet mocking mouth had one kiss on it that Wendy could never get, though there it was, perfectly conspicuous in the right-hand corner. The way Mr. Darling won her was this: the many gentlemen who had been boys when she was a girl discovered simultaneously that they loved her, and they all ran to her house to propose to her except Mr. Darling, who took a cab and nipped in first, and so he got her. He got all of her, except the innermost box and the kiss. He never knew about the box, and in time he gave up trying for the kiss. Wendy thought Napoleon could have got it, but I can picture him trying, and then going off in a passion, slamming the door. Mr. Darling used to boast to Wendy that her mother not only loved him but respected him. He was one of those deep ones who know about stocks and shares. Of course no one really knows, but he quite seemed to know, and he often said stocks were up and shares were down in a way that would have made any woman respect him."""bearer_token='Bearer sess-abcd1234..'od=OpenaiDetector(bearer_token)response=od.detect(sentence)print(response)### Output{"output":"The classifier considers the text to be very unlikely AI-generated.","Confidence score":96.15870427207666}Run on colabCommunityIf you are interested in Prompt-Engineering, LLMs, ChatGPT and other latest research discussions, please consider joining PromptsLabSteps to get Bearer token from chromeGo tohttps://platform.openai.com/ai-text-classifierHit F12 to access the Developer toolsSelect the Network TabSelect nearly any POST Operation (paste text into detection box and click on submit)Find your current Bearer token in the Request HeadersHere is an exampleTO-DOAdd all classes labels (total 5 classes from openai) ✅add verifier to check if the sentence is 1000 characters longautomatically detect token from user_name, passwordWeb Versionhttps://openai.com/blog/new-ai-classifier-for-indicating-ai-written-text/
Package: openai-func-parser
OpenAI Function ParserTransform Python function docstrings into JSON schemas compliant with OpenAI function calling protocols.Installationpipinstallopenai-function-parserUsagefromopenai_function_parserimportget_function_calling_schemadefmy_function(a:int,b:str,c:float=1.0)->int:"""My function description.Args:a: My first argument.b: My second argument.c: My third argument.Returns:My return value."""return1function_call_schema=get_function_calling_schema(my_function)print(function_call_schema)AuthorsXiaotian Duan (xduan7 at gmail dot com)
Package: openai-function-calling-aeolin
openai-function-callingIs a simple library which adds convenience methods to query open ai's chat endpoint with support for function calling.Installationpip install openai-function-calling-aeolinBasic Usage ExamplefromtypingimportAnyfromfunction_callingimportsetup_api,get_chat_compmetion,ChatHistory,ChatRole,descriptiondefto_string(obj:Any)->str:returnstr(obj)setup_api("openai api key",to_string)@description("Generates a password of the given length")defgenerate_password(length:int)->str:return"".join([random.choice("123456789abcdefghijklmnopqrstuvwxyz")forxinrange(length)])functions=[generate_password]history=ChatHistory("gpt-3.5-turbo",4096,functions)history.add_message(ChatRole.SYSTEM,"You're PasswordBot an ai that can generate passwords for people")history.add_message(ChatRole.USER,"can you generate me a password of length 16?")response=get_chat_completion(history)print(response.content)setup_apiThe setup api function takes two parameters, the first one is your openai api key, the second one is a function which can be used to convert objects to the type string. The string function is used by the library when ever a callable function returns something which is not of type stringChatHistoryThe ChatHistory will keep track of all messages and function responses. With the last parameter ofadd_messagea function can be marked as ephemeral. Per default all messages which are not of the roleSYSTEMare ephemeral.
Ephemeral messages can and will be removed by the library if the context runs out of tokens.get_chat_completionThis function take a ChatHistory object as an argument and queries the openai chat endpoint with it. The resulting function responses and messages are automatically recorded in the history itself. Upon completion aChatMessageobject is returned with the assitant response. The message is stored in the fieldcontentinside theChatMessageThe second parameter is an optional function which receives a list of responses if N was greated than 1 and returns one of the responses. If this function is not supplied the first response will be taken by default
The following optional parameters are passed through to the openai library (parameter name: default value)function_call: automax_tokens: 1024temperature: 0.9top_p: 1.0n: 1
Package: openai-functions
OpenAI functionsTheopenai-functionsPython project simplifies the usage of OpenAI's ChatGPTfunction callingfeature. It abstracts away the complexity of parsing function signatures and docstrings by providing developers with a clean and intuitive interface.InstallationYou can installopenai-functionsfrom PyPI using pip:pip install openai-functionsUsageImport the necessary modules and provide your API key:importenumimportopenaifromopenai_functionsimportConversationopenai.api_key="<YOUR_API_KEY>"Create aConversationinstance:conversation=Conversation()Define your functions using the@conversation.add_functiondecorator:classUnit(enum.Enum):FAHRENHEIT="fahrenheit"CELSIUS="celsius"@conversation.add_function()defget_current_weather(location:str,unit:Unit=Unit.FAHRENHEIT)->dict:"""Get the current weather in a given location.Args:location (str): The city and state, e.g., San Francisco, CAunit (Unit): The unit to use, e.g., fahrenheit or celsius"""return{"location":location,"temperature":"72","unit":unit.value,"forecast":["sunny","windy"],}Ask the AI a question:response=conversation.ask("What's the weather in San Francisco?")# Should return something like:# The current weather in San Francisco is 72 degrees Fahrenheit and it is sunny and windy.You can read more about how to useConversationhere.More barebones use - just schema generation and result parsing:fromopenai_functionsimportFunctionWrapperwrapper=FunctionWrapper(get_current_weather)schema=wrapper.schemaresult=wrapper({"location":"San Francisco, CA"})Or you could useskills.Another use case: data extractionImport the necessary modules and provide your API key:fromdataclassesimportdataclassimportopenaifromopenai_functionsimportnlpopenai.api_key="<YOUR_API_KEY>"Define your data container using the@nlpdecorator:@nlp@dataclassclassPerson:"""Extract personal info"""name:strage:intAsk the AI for the extracted data:person=Person.from_natural_language("I'm Jack and I'm 20 years old.")You can read more about@nlphere.Note: mypy does not parse class decorators (#3135), so you might have trouble getting type checking when using it like this. Consider using something likenlp(Person).from_natural_languageto get proper type support.How it Worksopenai-functionstakes care of the following tasks:Parsing the function signatures (with type annotations) and docstrings.Sending the conversation and function descriptions to the OpenAI model.Deciding whether to call a function based on the model's response.Calling the appropriate function with the provided arguments.Updating the conversation with the function response.Repeating the process until the model generates a user-facing message.This abstraction allows developers to focus on defining their functions and adding user messages without worrying about the details of function calling.NotePlease note thatopenai-functionsis an unofficial project not maintained by OpenAI. Use it at your discretion.
Package: openai-function-tokens
OpenAI Function Tokens EstimatorEstimate OpenAI token usage for chat completions, including functions, with this Python utility!This package is based uponhmarr'sopenai-chat-tokens. As of right now (September 2023) there is no official documentation from openai on how to accurately predict the number of tokens from functions. This package solves that! Use it to get a very precise estimation of the token count for chat completions and better manage your OpenAI API usage.Most often it is correct down to the token.InstallationInstall the Package via pippip install openai-function-tokensImport the Estimation Functionfromopenai_function_tokensimportestimate_tokensUsageTo use the estimator, call theestimate_tokensfunction:estimate_tokens(messages,functions=None,function_call=None)Pass in themessages, and optionallyfunctionsandfunction_call, to receive a precise token count.AcknowledgmentsCredit tohmarrfor the original TypeScript tool. For a better understanding of token counting logic, check out hisblog post.Further ReadingFunction CallingHow to call functions with chat modelsHow to use functions with a knowledge baseJSON Schema documentationCounting tokens (only messages)ContributingFeedback, suggestions, and contributions are highly appreciated. Help make this tool even better!
Package: openai-helper
OpenAI-HelperOpenAI Helper for Easy I/OGithubhttps://github.com/craigtrim/openai-helperUsageSet the OpenAI credentialsimportosos.environ['OPENAI_KEY']="<encrypted key>"os.environ['OPENAI_ORG']="<encrypted key>"UseCryptoBase.encrypt_str("...")fromhttps://pypi.org/project/baseblock/Initialize the OpenAI Helper:run=OpenAITextCompletion().runThis will connect to OpenAI and establish performant callbacks.Call OpenAI:run(input_prompt="Generate a one random number between 1 and 5000")orrun(engine="text-ada-001",temperature=1.0,max_tokens=256,input_prompt="Rewrite the input in grammatical English:\n\nInput: You believe I can help you understand what trust yourself? don't you?\nOutput:\n\n")The output will contain both the input and output values:{"input":{"best_of":1,"engine":"text-davinci-003","frequency_penalty":0.0,"input_prompt":"Rewrite the input in grammatical English:\n\nInput: You believe I can help you understand what trust yourself? don't you?\nOutput:\n\n","max_tokens":256,"presence_penalty":2,"temperature":1.0,"timeout":5,"top_p":1.0},"output":{"choices":[{"finish_reason":"stop","index":0,"logprobs":"None","text":"Don't you believe that I can help you understand trust in yourself?"}],"created":1659051242,"id":"cmpl-5Z7IwXM5bCwWj8IuHaGnOLn6bCvHz","model":"text-ada-001","object":"text_completion","usage":{"completion_tokens":17,"prompt_tokens":32,"total_tokens":49}}}Supported Parameters and DefaultsThis method signature describes support:defprocess(self,input_prompt:str,engine:str=None,best_of:int=None,temperature:float=None,max_tokens:int=None,top_p:float=None,frequency_penalty:int=None,presence_penalty:int=None)->dict:""" Run an OpenAI eventArgs:input_prompt (str): The Input Prompt to execute against OpenAIengine (str, optional): The OpenAI model (engine) to run against. Defaults to None.Options as of July, 2022 are:'text-davinci-003''text-curie-001','text-babbage-001''text-ada-001'best_of (int, optional): Generates Multiple Server-Side Combinations and only selects the best. Defaults to None.This can really eat up OpenAI tokens so use with caution!temperature (float, optional): Control Randomness; Scale is 0.0 - 1.0. Defaults to None.Scale is 0.0 - 1.0Lower values approach predictable outputs and determinate behaviorHigher values are more engaging but also less predictableUse High Values cautiouslymax_tokens (int, optional): The Maximum Number of tokens to generate. Defaults to None.Requests can use up to 4,000 tokens (this takes the length of the input prompt into account)The higher this value, the more each request will cost.top_p (float, optional): Controls Diversity via Nucleus Sampling. Defaults to None.no idea what this meansfrequency_penalty (int, optional): How much to penalize new tokens based on their frequency in the text so far. Defaults to None.Scale: 0.0 - 2.0.presence_penalty (int, optional): Seems similar to frequency penalty. Defaults to None.Returns:dict: an output dictionary with two keys:input: the input dictionary with validated parameters and default values where appropriateoutput: the output event from OpenAI"""Counting Tokens (tiktoken)
Package: openai-image
openai_imagePython script for generating image from text by Open AI1. Install openai & openai-imagepip install openai


pip install openai-image2. Recieve your OpenAI API KEYhttps://platform.openai.com/account/api-keys3. SettingsAPI_KEY = 'your-secret-openai-api-key'

PIC_SIZE = '256x256'

IMAGES = ''

TARGET_TEXT = ''PIC_SIZE options :'256x256', '512x512', '1024x1024'IMAGES options: if IMAGES = '', script will use current folder. But you can set your own dir, for example: IMAGES = 'D:\Pictures'TARGET_TEXT options: TARGET_TEXT = '', you will input your target text from keyboard. And you can set it in code, for example TARGET_TEXT = 'Alice in Wonderland'4. Use openai_imageimport openai_imageExample1:import openai_image

API_KEY = 'your-secret-openai-api-key'

PIC_SIZE = '256x256'

IMAGES = ''

TARGET_TEXT = ''

openai_image.get_image(API_KEY, PIC_SIZE, IMAGES, TARGET_TEXT)Prompt target text:blue birdYour image file ready:blue_bird.pngExample2:from openai_image import *

API_KEY = 'your-secret-openai-api-key'

PIC_SIZE = '256x256'

IMAGES = 'D:\Pictures\'

TARGET_TEXT = 'Alice in Wonderland'

get_image(API_KEY, PIC_SIZE, IMAGES, TARGET_TEXT)Your image file ready:D:\Pictures\Alice_in_Wonderland.pngDocumentationhttps://best-itpro.ru/news/openai_image/That's All, Folks!
;)
Package: openai-load-balancer
OpenAI Load BalancerDescriptionThe OpenAI Load Balancer is a Python library designed to distribute API requests across multiple endpoints (supports both OpenAI and Azure). It implements a round-robin mechanism for load balancing and includes exponential backoff for retrying failed requests.Supported OpenAI functions: ChatCompletion, Embedding, Completion (will be deprecated soon)FeaturesRound Robin Load Balancing: Distributes requests evenly across a set of API endpoints.Exponential Backoff: Includes retry logic with exponential backoff for each API call.Failure Detection: Temporarily removes failed endpoints based on configurable thresholds.Flexible Configuration: Customizable settings for endpoints, failure thresholds, cooldown periods, and more.Easy Integration: Designed to be easily integrated into projects that use OpenAI's API.Fallback: If OpenAI's endpoint goes down, if your Azure endpoint is still up, then your service stays up, and vice versa.InstallationTo install the OpenAI Load Balancer, run the following command:pipinstallopenai-load-balancerUsageFirst, setup your OpenAI API Endpoints. The API keys and base_url will be read from your env variable.# Example configurationENDPOINTS=[{"api_type":"azure","base_url":"AZURE_API_BASE_URL_1","api_key_env":"AZURE_API_KEY_1","version":"2023-05-15"},{"api_type":"open_ai","base_url":"https://api.openai.com/v1","api_key_env":"OPENAI_API_KEY_1","version":None}# Add more configurations as needed]If you are using both Azure and OpenAI, specify the mapping of the OpenAI's model name to your Azure's engine nameMODEL_ENGINE_MAPPING={"gpt-4":"gpt4","gpt-3.5-turbo":"gpt-35-turbo","text-embedding-ada-002":"text-embedding-ada-002"# Add more mappings as needed}Import and initialize the load balancer with the endpoints and mapping:fromopenai_load_balancerimportinitialize_load_balanceropenai_load_balancer=initialize_load_balancer(endpoints=ENDPOINTS,model_engine_mapping=MODEL_ENGINE_MAPPING)Making API CallsSimply replaceopenaiwithopenai_load_balancerin your function calls!:response=openai_load_balancer.ChatCompletion.create(model="gpt-3.5-turbo",messages=[{"role":"system","content":"You are a helpful assistant."},{"role":"user","content":"Hello! This is a request."}],# Additional parameters...)Additional configurationsYou can also configure the load balancer with the following variables# The number of consecutive failures of a request to an endpoint before the endpoint is temporarily marked as inactiveFAILURE_THRESHOLD=5# The minimum amount of time an endpoint is marked as inactive before it is reset to active.COOLDOWN_PERIOD=timedelta(minutes=10)# Whether or not to enable load balancing. If disabled, the first active endpoint will always be used, and other endpoints will only be used in case the first one fails.LOAD_BALANCING_ENABLED=TrueContributingContributions to the OpenAI Load Balancer are welcome!LicenseThis project is licensed under theMIT License.