Saravanan666/pypi-org huggingface dataset:
Package: prompt-horizon
Prompt-HorizonPrompt-Horizonis a Python library that enables developers to anonymize JSON objects by creating placeholders for keys and values, while generating a reversible mapping to restore the original JSON data. The purpose of this library is to facilitate data sharing while preserving privacy and allowing for the de-anonymization of the data when required.Note: I had the idea for this library when I was trying to find a way to obfuscate data objects such as JSON to include them as contextual information in prompts (hence the name).Prompt-Horizon is not designed to specifically identify and anonymize PII (personally identifiable information) or other sensitive data within the JSON objects.Installationpipinstallprompt-horizonUsageAnonymize JSONfromprompt_horizonimportanonymizeinput_json={"name":"John","age":30,"city":"New York","favorites":["pizza","basketball"]}#This line will return the anonymized JSON object and the mapping object.anonymized_json,map_object=anonymize(input_json)Original JSON:{"name":"John","age":30,"city":"New York","favorites":["pizza","basketball"]}Anonymized JSON:{"a1":"a2","a3":"a4","a5":"a6","a7":["a8","a9"]}input and output file handling is supportedfromprompt_horizonimportanonymize#This line will read the JSON data from "input.json", anonymize it, and save the anonymized JSON to "anonymized.json".anonymized_json,map_object=anonymize("input.json",output_file_path="anonymized.json")anonymize only the valuesfromprompt_horizonimportanonymize#This line will read the JSON data from "input.json" and anonymize only the values.anonymized_json,map_object=anonymize("input.json",anonymize_keys=False)De-anonymize JSONfromprompt_horizonimportde_anonymize#This line will return the de-anonymized JSON object, which should be the same as the original input JSON.deanonymized_json=de_anonymize(anonymized_json,map_object=map_object)input and output files are supportedfromprompt_horizonimportde_anonymize#This will read the anonymized JSON data from "anonymized.json", the mapping object from "map_file.json", de-anonymize the JSON data, and save the de-anonymized JSON to "deanonymized.json".deanonymized_json=de_anonymize("anonymized.json",map_file_path="map_file.json",output_file_path="deanonymized.json")LicenseThis project is licensed under theMIT License.
Package: prompthub
fromprompthubimportPromptHub,errorstry:prompts=PromptHub('http://localhost:8000','25cee15690db575d123271ef7f408e6a1f9446b1',category='rmb-prod')excepterrors.CategoryNotFoundError:print('Category not found')# do somethingexcepterrors.ConnectionError:print('Connection error')# do something# 按照这个顺序来找可以适用的模型prompts.set_preferred_models(['gpt-3.5','gpt-4-turbo','any'])try:prompt=prompts.get('MetaName',raise_if_missing_variables=True,k1='v1',k2='v2',)content=prompt.contentmodel=prompt.modelexcepterrors.PromptNotFoundError:print('Prompt not found')# do somethingexcepterrors.PromptMissingVariablesErrorase:print('Prompt missing variables',e)# do somethingexcepterrors.NoValidModelError:print('No valid model')# do somethingfromclient.prompthub.hubimportPromptHub,errorsprompts=PromptHub('http://localhost:8000','25cee15690db575d123271ef7f408e6a1f9446b1',category='rmb-prod')template=prompts.get_template('MetaName')# 该Prompt适用的模型有哪些valid_models=template.modelstemplate=prompts.create_template('MetaN1ame','tex111t',output_format='str',model_names=['gpt-3.5','gpt-4-turbo'],label_names=['label1','label2'],)
Package: prompthub-py
Prompt Hub Python ClientA simple client to fetch prompts fromPrompt Hubusing its REST API.UsageFirst step is obviously installation:pip install prompthub-pyThen you can importPrompt, that class is all you're going to need.importprompthub# To load from a JSON filep=prompthub.from_json("./path/to/my/prompt.json")# To load from a YAML filep=prompthub.from_yaml("./path/to/my/prompt.yaml")# To load from Prompt Hubp=prompthub.fetch("deepset/question-answering")# To get the prompt text (see Prompt class)p.textIf you want to use a different Prompt Hub you must set thePROMPTHUB_MAIN_ENDPOINTenvironment variable to your main endpoint.If the environment variable is not set the defaultapi.prompthub.deepset.aiwill be used.TestingTo run tests locally first install dev dependencies, we usepoetryto manage our dependencies:poetry install --with=devRun Prompt Hub locally with a set of fake prompts:docker run -p80:80 --volume $PWD/test/fake_prompts:/prompts deepset/prompthubAnd then run tests:poetry run pytest test
Package: promptimizer
PromptimizerPromptimizer is "prompt" + "optimizer", which is a prompt optimizer. It aims to build the high-quality LLM prompts for everyone. It can build and optimize an elegant prompt for you.We use structured prompt templates to guide LLM in building an efficient prompt that can more accurately output the answers users want.SetupPip (Method1 Recommend)Open terminal and enter the following command.pipinstallpromptimizerUsing following command to open client.promptimizerGit Clone (Method2)Clone repo to local.gitclonehttps://github.com/Undertone0809/promptimizerInstall all relevant packages.pipinstallpoetry
poetryinstallCopy.env.examplerename it as.env, saving it to the root directory of the current project. Fill in your openai key in.env.OPENAI_API_KEY=your-keyRun the script.pythonmain.py
Package: promptinject
PromptInjectPaper: Ignore Previous Prompt: Attack Techniques For Language ModelsAbstractTransformer-based large language models (LLMs) provide a powerful foundation for natural language tasks in large-scale customer-facing applications. However, studies that explore their vulnerabilities emerging from malicious user interaction are scarce. By proposing PROMPTINJECT, a prosaic alignment framework for mask-based iterative adversarial prompt composition, we examine how GPT-3, the most widely deployed language model in production, can be easily misaligned by simple handcrafted inputs. In particular, we investigate two types of attacks -- goal hijacking and prompt leaking -- and demonstrate that even low-aptitude, but sufficiently ill-intentioned agents, can easily exploit GPT-3’s stochastic nature, creating long-tail risks.Figure 1: Diagram showing how adversarial user input can derail model instructions. In both attacks,
the attacker aims to change the goal of the original prompt. Ingoal hijacking, the new goal is to print
a specific target string, which may contain malicious instructions, while inprompt leaking, the new
goal is to print the application prompt. Application Prompt (gray box) shows the original prompt,
where{user_input}is substituted by the user input. In this example, a user would normally input
a phrase to be corrected by the application (blue boxes).Goal HijackingandPrompt Leaking(orange
boxes) show malicious user inputs (left) for both attacks and the respective model outputs (right)
when the attack is successful.InstallRun:pip install git+https://github.com/agencyenterprise/PromptInjectUsageSeenotebooks/Example.ipynbfor an example.CiteBibtex:@misc{ignore_previous_prompt,
    doi = {10.48550/ARXIV.2211.09527},
    url = {https://arxiv.org/abs/2211.09527},
    author = {Perez, Fábio and Ribeiro, Ian},
    keywords = {Computation and Language (cs.CL), Artificial Intelligence (cs.AI), FOS: Computer and information sciences, FOS: Computer and information sciences},
    title = {Ignore Previous Prompt: Attack Techniques For Language Models},
    publisher = {arXiv},
    year = {2022}
}ContributingWe appreciate any additional request and/or contribution toPromptInject. Theissuestracker is used to keep a list of features and bugs to be worked on. Please see ourcontributing documentationfor some tips on getting started.
Package: promptlayer
🍰 PromptLayerThe first platform built forprompt engineersPromptLayeris the first platform that allows you to track, manage, and share your GPT prompt engineering. PromptLayer acts a middleware between your code and OpenAI’s python library.PromptLayer records all your OpenAI API requests, allowing you to search and explore request history in the PromptLayer dashboard.This repo contains the Python wrapper library for PromptLayer.Quickstart ⚡Install PromptLayerpipinstallpromptlayerInstalling PromptLayer LocallyUsepip install .to install locally.Using PromptLayerTo get started, create an account by clicking “Log in” onPromptLayer. Once logged in, click the button to create an API key and save this in a secure location (Guide to Using Env Vars).Once you have that all set up,install PromptLayer usingpip.In the Python file where you use OpenAI APIs, add the following. This allows us to keep track of your requests without needing any other code changes.importpromptlayerpromptlayer.api_key="<YOUR PromptLayer API KEY pl_xxxxxx>"openai=promptlayer.openaiYou can then useopenaias you would if you had imported it directly.💡 Your OpenAI API Key is **never** sent to our servers. All OpenAI requests are made locally from your machine, PromptLayer just logs the request.Adding PromptLayer tags:pl_tagsPromptLayer allows you to add tags through thepl_tagsargument. This allows you to track and group requests in the dashboard.Tags are not required but we recommend them!openai.Completion.create(engine="text-ada-001",prompt="My name is",pl_tags=["name-guessing","pipeline-2"])After making your first few requests, you should be able to see them in the PromptLayer dashboard!Using the REST APIThis Python library is a wrapper over PromptLayer's REST API. If you use another language, like Javascript, just interact directly with the API.Here is an example request below:importrequestsrequest_response=requests.post("https://api.promptlayer.com/track-request",json={"function_name":"openai.Completion.create","args":[],"kwargs":{"engine":"text-ada-001","prompt":"My name is"},"tags":["hello","world"],"request_response":{"id":"cmpl-6TEeJCRVlqQSQqhD8CYKd1HdCcFxM","object":"text_completion","created":1672425843,"model":"text-ada-001","choices":[{"text":" advocacy\"\n\nMy name is advocacy.","index":0,"logprobs":None,"finish_reason":"stop"}]},"request_start_time":1673987077.463504,"request_end_time":1673987077.463504,"api_key":"pl_<YOUR API KEY>",},)ContributingWe welcome contributions to our open source project, including new features, infrastructure improvements, and better documentation. For more information or any questions, contact us athello@promptlayer.com.
Package: promptlink
PromptLinkSimplify user authentication and secure access from anywhere with temporary links.PromptLink is a Python package that allows you to streamline user authentication and enable secure access to your application from anywhere. It provides a seamless way to generate temporary links for user authentication, without relying on specific web frameworks. A Google Cloud Function is set up to ensure a secure temporary link for authentication.Key FeaturesEasy and secure: Generate secure temporary links to enable easy secure access from anywhere.Versatile Integration: Works across various application types, not limited to web applications.InstallationYou can install PromptLink using pip:pipinstallpromptlinkAlternatively, if you are using Poetry (recommended), you can install it as follows:poetryaddpromptlinkUsageHere's a basic example of using PromptLink:frompromptlinkimportAuthenticatorwithAuthenticator(send_link_callback=lambdal:print(f"URL:{l}"))asauthenticator:# The code in this block is executed after the link has been accessed# in order to avoid authentication timeoutsprint("Setting up authentication...")authenticator.authenticate(lambdas:s=="12345678")# Below statements will be reached after '12345678' was input on the webpage promptprint("Finished")GCP permission requirementsThe following permissions are needed for this library:Permissions to create Storage buckets and objectsPermissions to set up a Pub/Sub topic and subscriptionsPermissions to deploy a Cloud FunctionThe library will attempt to use the default service account.
Any resources created will be named 'promptlink-' followed by a random UUID, so that collision with existing resources is extremely unlikely.LicenseThis project is licensed under the MIT License. See the LICENSE file for details.
Package: promptlytics
Project TitleOfficial python library forPromptlyticsDescriptionPromptlytics is a prompt analytics tool that helps you find the best prompts for your use case by tracking user feedback and associating it with your prompt templates.InstallationpipinstallpromptlyticsGetting StartedUse an instance of the Promptlytics class to get your prompt templates and track user feedbackfrompromptlyticsimportPromptlyticspromptlytics=Promptlytics(YOUR_API_KEY)# Gets the template selected for use in your dashboardtemplate=promptlytics.useTemplate(use_selected=True)# sends user feedbackpromptlytics.track(use_selected=True,rating=5,completion="string response from your LLM")
Package: prompt-matrix
Prompt MatrixA Python package to expand prompt matrix strings. For example, the string"The <dog|cat> in the hat"expands to the list["The dog in the hat", "The cat in the hat"].The motivating case for this package is to compare the effects of different
prompts in text and image generation systems such as Stable Diffusion and GPT-3.FeaturesA prompt string may contain multiple alternations. For example,"The <dog|cat> in the <cardigan|hat>"produces a list of the four strings"The dog in the cardigan","The dog in the hat","The cat in the cardigan", and"The cat in the hat".A prompt string may contain nested alternations. For example,"The <<small|large> dog|cat>"produces the strings"The small dog","The large do", and"The cat".Brackets[]enclose optional elements. For example,"The [small] cat"is
equivalent to"The <small,> cat", and both produce the strings"The small cat"and"The  cat".The special characters<>{}|can be replaced by different strings, or disabled
by specifyingNoneor the empty string.Note: The disjunction is bounded by the enclosing brackets, if any."The dog|cat in the cardigan|hat"generates the three strings"The dog","cat in the gardigan", and"hat". This is in contrast to some other systems, that
scope a disjunction to the text delimited by surrounding whitespace.Install$pipinstallprompt-matrixUsagePrompt Matrix provides two functions for expanding a prompt matrix:expandanditerexpand. Both take a string that specifies
a prompt matrix.expandreturns an array of strings with all possible combinations of the
prompt matrix elements.importprompt_matrixprompt="<hi|hello> <there|you>"expansion=prompt_matrix.expand(prompt)print(expansion)# ["hi there", "hi you", "hello there", "hello you"]iterexpandreturns a generator that yields the expansions one by
one.importprompt_matrixprompt="<hi|hello> <there|you>"forexpansioninprompt_matrix.iterexpand(prompt):print(expansion)# "hi there", "hi you", "hello there", "hello you"ExamplesExample 1: Basic usageimportprompt_matrixprompt_matrix.expand("The <dog|cat> in the hat")# -># ["The dog in the hat",#  "The cat in the hat"]Example 2: Using multiple alternationsprompt_matrix.expand("The <dog|cat> in the <cardigan|hat>")# -># ["The dog in the cardigan",#  "The dog in the hat",#  "The cat in the cardigan",#  "The cat in the hat"]Example 3: Using nested bracketsprompt_matrix.expand("The <<small|large> <brown|black> dog|<red|blue> fish>")# -># ["The small brown dog",#  "The small black dog",#  "The large brown dog",#  "The large black dog",#  "The red fish",#  "The blue fish"]Example 4: Using custom brackets and separatorprompt_matrix.expand("The {dog,cat} in the {cardigan,hat}",brackets=['{','}'],alt=',')# -># ["The dog in the cardigan",#  "The dog in the hat",#  "The cat in the cardigan",#  "The cat in the hat"]LicenseMIT
Package: promptml
PromptMLPrompt Markup Language Parser.PromptMLPromptML is a simple markup language.It inserts control strings in common string, wrapped by[], (e. g.[mask],[sep])The control strings can have some options, seperated with string by|, (e. g.[title|upper],[text|lower])The control options can be multiple, seperated by,, (e. g.[title|upper,rmpunt])PromptML Examples will be prased[cls]A [mask] news : [sent_0|lower,fix][sep|+]String:clsControl Options: {}String:AControl Options: NoneString:maskControl Options: {}String:news :Control Options: NoneString:sent_0Control Options: {lower,fix}String:sepControl Options: {+}[cls]\\[ Topic : [mask] \\][sent_0][sep|+]String:clsControl Options: {}String:[ Topic :Control Options: NoneString:maskControl Options: {}String:]Control Options: NoneString:sent_0Control Options: {}String:sepControl Options: {+}PromptML Code ExamplefrompromptmlimportPromptTemplatefromdatasetsimportload_datasetfromtransformersimportAutoTokenizerdefmain():tokenizer=AutoTokenizer.from_pretrained("bert-base-uncased",use_fast=True)template=PromptTemplate("[cls]A [mask] news : [text|limit][sep]",tokenizer)res=template.render({"text":"hello world"},max_length=20)imdb=load_dataset("imdb")imdb=template.render(imdb,max_length=128)if__name__=='__main__':main()
Package: promptools
promptoolsuseful utilities for prompt engineeringInstallationpipinstallpromptools# or any other dependency manager you likeNote that thevalidationfeatures usepydantic>=2as an optional dependencies. You can usepip install promptools[validation]to install it by the way.API Referencesextractorsextract_jsonparse JSON from raw LLM response textUsagesDetect and parse the last JSON block from input string.defextract_json(text:str,/,fallback:F)->JSON|F:It will returnfallbackif it fails to detect / parse JSON.
Note that the default value offallbackisNone.defextract_json(text:str,/,fallback:F,expect:Type[M])->M|F:You can provide apydantic.BaseModelor aTypeAliasin theexpectparameter andpydanticwill validate it.ExamplesClassification exampleImagine that you are using LLM on a classification task.frompromptools.extractorsimportextract_jsonfromtypingimportTypedDictclassItem(TypedDict):index:intlabel:stroriginal_text="""The result is:```json[{"index": 0, "label": "A"},{"index": 1, "label": "B"}]```"""print(extract_json(original_text,[],list[Item]))The output will be:[{'index':0,'label':'A'},{'index':1,'label':'B'}]Streaming JSON exampleImagine that you are trying to parse a malformed JSON:frompromptools.extractorsimportextract_jsonfrompydanticimportBaseModeloriginal_text='{"results": [{"index": 1}, {'print(extract_json(original_text))The output will be:{'results':[{'index':1},{}]}openaicount_tokencount number of tokens in promptUsagesdefcount_token(prompt:str|list[str],enc:Encoding|None=None)->int:Provide your prompt / a list of prompts, get its token count. The second parameter is thetiktoken.Encodinginstance, will default toget_encoding("cl100k_base")if not provided. The defaulttiktoken.Encodinginstance is cached, and will not be re-created every time.defcount_token(prompt:dict|list[dict],enc:Encoding|None=None)->int:Note that it can also be a single message / a list of messages. Every message should be a dict in the schema below:classMessage(TypedDict):role:strcontent:strname:NotRequired[str]ExamplesPlain textfromtiktokenimportencoding_for_modelfrompromptools.openaiimportcount_tokenprint(count_token("hi",encoding_for_model("gpt-3.5-turbo")))The output will be:1List of plain textsfrompromptools.openaiimportcount_tokenprint(count_token(["hi","hello"]))The output will be:2Single messagefrompromptools.openaiimportcount_tokencount_token({"role":"user","content":"hi"})The output will be:5List of messagesfrompromptools.openaiimportcount_tokencount_token([{"role":"user","content":"hi"},{"role":"assistant","content":"Hello! How can I assist you today?"},])The output will be:21Integrating withpromplatefrompromplate.prompt.chatimportU,A,Sfrompromptools.openaiimportcount_tokencount_token([S@"background">"You are a helpful assistant.",U@"example_user">"hi",A@"example_assistant">"Hello! How can I assist you today?",])The output will be:40
Package: promptops
umis a GPT-powered CLI assistant. Ask questions in plain English, get the perfect shell command.Featuresfind the right command without leaving the terminalumcan index your history to find commands you've run beforeuminstantly learns from your correctionssimple interface to clarify your question or provide more contextNEW in 0.1.6:um workflowhelps you provision infrastructure (currently terraform only, more coming soon)NEW in 0.1.7: extended reverse search functionality with fuzzy matching and semantic searchInstallationLinux - Ubuntucurl-fsSL-oubuntu-installer.shhttps://raw.githubusercontent.com/promptops/cli/main/ubuntu-installer.sh
chmod700ubuntu-installer.sh
./ubuntu-installer.shMacOS - Homebrewbrewinstallpromptops/promptops/promptops-clipipMake sure you have python 3.10 or more recentpython.org downloadspip3installpromptopsConfigurationeval"$(um--install)"(Optional) Enable extended reverse search (Ctrl+E)Note: currently works only with ZshAdd the widget and the key binding to your.zshrcfilecp~/.zshrc~/.zshrc.backupecho'eval "$(promptops lookup --config)"'>>~/.zshrcReloadsource~/.zshrcDisable extended reverse searchRemove the eval line from your.zshrcfile and reload.Usageumum<question>umrecipe<multi-stepped-prompt>local runnerpromptopsrunnerExamplesumlistcontentsoftarfile
umuploadfiletos3More screenshotsSemantic search in historyProvide more context flowDevelopment setupcreate virtual envpython3.10-mvenv./venv
../venv/bin/activateinstall dependenciespipinstall-rrequirements.txtinstall the climakeinstalltest withumgetpodsPublishing pip releasemakepublish
Package: promptpay
PromptPayPython library to generate PromptPay QR Code, inspired fromdtinth/promptpay-qrInstallationpip install promptpay

# or
git clone https://github.com/jojoee/promptpay
cd promptpay
python setup.py installUsageLibraryfrompromptpayimportqrcode# generate a payloadid_or_phone_number="0841234567"payload=qrcode.generate_payload(id_or_phone_number)payload_with_amount=qrcode.generate_payload(id_or_phone_number,1.23)# export to PIL imageimg=qrcode.to_image(payload)# export to fileqrcode.to_file(payload,"./qrcode-0841234567.png")qrcode.to_file(payload_with_amount,"/Users/joe/Downloads/qrcode-0841234567.png")CLIpython-mpromptpayqrcode--id="0841234567"python-mpromptpayqrcode--id="0841234567"--file="./qrcode-cli.png"python-mpromptpayqrcode--id="0841234567"--show=truepython-mpromptpayqrcode\--id="0841234567"\--amount=2.34\--file="/Users/joe/Downloads/qrcode-cli-with-amount.png"Development# Conda envcondacreate--namepromptpay3.10python=3.10.4
condaactivatepromptpay3.10
condacreate--namepromptpay3.7python=3.7.13
condaactivatepromptpay3.7
condaremove--namepromptpay3.10--all# otherspipinstall-rrequirements.txt
pipinstall-rrequirements-dev.txt
python-mflake8--ignore=E501promptpaytests
python-mpytesttests--cov=./--cov-report=xml
piplist--outdated--format=freeze|grep-v'^\-e'|cut-d=-f1|xargs-n1pipinstall-U
python-mpiplist--format=freeze>requirements-tmp.txt
pipinstalllibscrc==pipinstallPillow==pipinstallpromptpay
pipinstallpromptpay==1.1.7
pipinstall.
pipinstall--force-reinstallpromptpayReferenceมีอะไรอยู่ใน PromptPay QR แกะสเปค QR ที่จะใช้จ่ายผ่าน mobile banking ได้ทุกธนาคารในอนาคต