ShareShortcuts
Fazer fork de “Gemini via API”

Criou algo novo a partir deste atalho? Compartilhe como uma derivação: ela se torna um atalho seu, que você gerencia, e as duas páginas têm links entre si para que twilsonco receba o crédito.

  1. 1Obtenha o atalho e altere-o no app Atalhos. Dê a ele um nome próprio.
  2. 2Compartilhe pelo app Atalhos e copie o link do iCloud.
  3. 3Volte aqui, cole o link e descreva o que mudou, por exemplo: “Adicionei uma etapa que usa a Apple Intelligence para personalizar o texto.”
Downloads
27K
Salvo
0
Ações
286
Categoria
Productivity
Versão
1.0
Idioma
EN

Pré-visualização

Google Gemini Pro API

Here you'll find the main shortcut, as well as a companion shortcut for viewing/continuing conversations, and some auxiliary shortcuts that work by calling the main shortcut.

  • Drop-in replacement for the "Ask ChatGPT" shortcut action, or
  • Runs standalone for text/PDF/image-based Gemini requests
  • Quick back and forth conversations when run standalone
  • When PDF is used for input, you can select specific page(s) to include , or use entire document
  • Logs conversations/images to Files App at /Shortcuts/GeminiAPI
  • View/continue Gemini conversation with this companion shortcut 🔗
  • Companion shortcut optionally uses actions from Toolbox Pro🔗 (no purchase necessary)

Currently, Gemini-Pro API access is FREE for up to 60 queries per minute!Bring your own free API key (get one here) 🔗

Shortcuts using this Shortcut

View/continue Gemini Pro conversation 🔗

  • A shortcut providing a convenient interface for viewing and continuing text/image conversations with Gemini that were created and logged using the current shortcut

A. Summarize article 🔗

  • Share a website from Safari/Chrome/etc to the shortcut and have Google Gemini Pro create a natural language summary

B. What is this? 🔗

  • A simple example of a shortcut utilizing the “Gemini via API” shortcut
  • This takes a picture and has gemini describe it. This is intended to be used via Siri or through a widget
  • Same thing as selecting image input in "Gemini via API", but with fewer taps

C. I have a question 🔗

  • This shortcut allows you to have a voice-only, back-and-forth conversation with Google Gemini Pro, using the “Gemini via API” shortcut
  • You can also pass this shortcut an image/photo via the share sheet and the image will be included with every request so you can query the same image repeatedly. (No previous messages are retained when an image is used, due to Google API constraints)
  • Basically the same thing as selecting dictation as input in "Gemini via API", but can be used from Siri more easily and requires no tapping

C1. Gemini Chat 🔗

  • This shortcut allows you to have a back-and-forth text conversation with Google Gemini Pro, using the “Gemini via API” shortcut
  • You can also pass this shortcut an image/photo via the share sheet and the image will be included with every request so you can query the same image repeatedly. (No previous messages are retained when an image is used, due to Google API constraints)
  • Basically the same as selecting text input in "Gemini via API", but with fewer taps

D. Weather summary 🔗

  • Fetches weather data for your current location and have Gemini read back a natural language summary of the upcoming weather

E. Today's agenda and weather 🔗

  • Same but for weekly agenda🔗
  • Define a list of iOS calendars and reminder lists which are used to fetch your scheduled events for the day, and have Gemini read back a summary of your agenda along with the weather

F. Create calendar events 🔗

  • Suggest/create one or more calendar events from a block of text shared using the Share Sheet or copied text, or a copied screenshot (using OCR)
  • Because Gemini Pro is used, you get contextually named event titles, notes, and it automatically suggests which calendar the event should be added to, as well as auto populating most event fields
  • You get a chance to modify events before they're added

Novidades

Versão 1.0

First release

Histórico de versões
1.0 9 de fev de 2024

First release

O que ele faz

286 ações
  1. Comment
    Google Gemini Pro via API. By Tim Wilson, December 2023 This shortcut is design to be run standalone or from other Shortcuts. It passes the input prompt to Google via their API and returns the response if successful. Logs conversations to Files/Shor…
  2. Comment
    Dictionary input arguments: “model” a valid model name to use. “temperature” a number between 0 and “messages” a JSON array passed as the “contents” to the API. You don’t have to build it manually, since it’spart of the output. Just maintain it betw…
  3. Comment
    Enter your Google API key. Get one here: https://makersuite.google.com/app/apikey
  4. Text
  5. Set Variable
    APIKey
  6. Comment
    Set default text model to use when not provided in input dictionary. Possible options: “gemini-pro” https://platform.openai.com/docs/models/continuous-model-upgrades
  7. Text
  8. Set Variable
    ModelName
  9. Comment
    Set default text + vision model to use. Possible values: “gemini-pro-vision”
  10. Text
  11. Comment
    Set model temperature. Value must be between 0 and 2 https://platform.openai.com/docs/api-reference/chat/create#chat-create-temperature
  12. Number
  13. Set Variable
    Temperature
  14. Comment
    By default, conversations are logged so that they can be accessed using the “View or continue Gemini conversation” companion shortcut. When conversations are logged, Gemini Pro will create a title for the conversation automatically. Should the title…
  15. Number
  16. Comment
    Check for shortcut updates
  17. Nothing
  18. Comment
    【Auto-Update Routine】 Checks For Latest Shortcut Version ↳ https://routinehub.co/shortcut/16590/
  19. Dictionary
  20. Get Dictionary Value
  21. If
  22. Get IP Address
  23. If
  24. Get Contents of URL
    https://routinehub.co/api/v1/shortcuts/…/versions/latest
  25. If
  26. Split Text
  27. Repeat with Each
  28. Calculate Expression
  29. Set Variable
    Latest Version
  30. Split Text
  31. Repeat with Each
  32. Calculate Expression
  33. Set Variable
    Current Version
  34. If
  35. Choose from Menu
    New Version: … Release: … Whats New: "…"
  36. Choose from Menu
    Update → Result (Version)
  37. Expand URL
  38. Replace Text
  39. Open URLs
  40. Stop This Shortcut
  41. Choose from Menu
    Skip (Info (Version))
  42. Comment
    【Auto-Update Routine Ends Here】 Support → https://www.reddit.com/r/shortcuts/comments/18j4f9p/ 【⚙️】 Convert Semantic Number to Decimals ↳ https://routinehub.co/shortcut/16589/
  43. Nothing
  44. Comment
    Get date for naming log file
  45. Date
  46. Text
  47. Set Variable
    DateTime
  48. Comment
    Set default parameter values
  49. Nothing
  50. Set Variable
    Messages
  51. Set Variable
    Image
  52. Number
  53. Set Variable
    OutputDict
  54. Number
  55. Set Variable
    Repeat
  56. Set Variable
    Speak
  57. Set Variable
    DoLog
  58. Set Variable
    Input selection override
  59. If
  60. Set Variable
    Speak
  61. Set Variable
    Repeat
  62. Comment
    Process shortcut input, if provided
  63. Get Type
  64. If
  65. If
  66. Get Contents of URL
    …
  67. Set Variable
    PDF file
  68. Set Variable
    Input selection override
  69. Set Variable
    Repeat
  70. If
  71. Text
  72. Set Variable
    Prompt
  73. If
  74. Set Variable
    PDF file
  75. Set Variable
    Input selection override
  76. Set Variable
    Repeat
  77. If
  78. Comment
    Process dictionary input
  79. Set Variable
    OutputDict
  80. If
  81. Set Variable
    Prompt
  82. If
  83. Set Variable
    ModelName
  84. If
  85. Get Dictionary Value
  86. Set Variable
    Temperature
  87. If
  88. Set Variable
    APIKey
  89. If
  90. Set Variable
    Messages
  91. If
  92. Base64 Encode
  93. Set Variable
    Image
  94. If
  95. Set Variable
    Repeat
  96. If
  97. Set Variable
    Input selection override
  98. If
  99. Set Variable
    Speak
  100. If
  101. Set Variable
    DateTime
  102. Get Dictionary Value
  103. If
  104. Set Variable
    DoLog
  105. Text
  106. Comment
    Empty prompt value, so all user for text/image to use.
  107. If
  108. If
  109. Set Variable
    Image
  110. Text
  111. If
  112. If
  113. If
  114. Wait
  115. Dictate Text
  116. Set Variable
    Prompt
  117. If
  118. If
  119. Text
  120. If
  121. Text
  122. If
  123. Choose from Menu
    What kind of request?
  124. Choose from Menu
    Text
  125. Set Variable
    Speak
  126. Text
  127. Choose from Menu
    Dictate
  128. Dictate Text
  129. Set Variable
    Prompt
  130. Choose from Menu
    Camera
  131. Set Variable
    Speak
  132. Take Photo
  133. Save to Photo Album
  134. Set Variable
    Image
  135. Text
  136. Choose from Menu
    Last photo
  137. Set Variable
    Speak
  138. Get Latest Photos
  139. Set Variable
    Image
  140. Show Result
  141. Text
  142. Choose from Menu
    Photo from library
  143. Set Variable
    Speak
  144. Select Photos
  145. Set Variable
    Image
  146. Text
  147. Choose from Menu
    Image from Files
  148. Set Variable
    Speak
  149. Select File
  150. Get Images from Input
  151. Set Variable
    Image
  152. Text
  153. Choose from Menu
    PDF file
  154. Set Variable
    Speak
  155. Select File
  156. Set Variable
    PDF file
  157. Text
  158. Choose from Menu
    From clipboard
  159. Set Variable
    Speak
  160. Get Clipboard
  161. Get Images from Input
  162. Count
  163. If
  164. Set Variable
    Image
  165. Text
  166. If
  167. Get Text from Input
  168. Set Variable
    Prompt
  169. If
  170. Ask for Input
    Please enter a prompt to send to Gemini
  171. Set Variable
    Prompt
  172. If
  173. Choose from Menu
    Use entire PDF or select pages to include (after viewing file)?
  174. Choose from Menu
    Entire PDF
  175. Gettextfrompdf
  176. Choose from Menu
    Select pages
  177. Show Result
  178. Split PDF
  179. Choose from List
  180. Make PDF
  181. Gettextfrompdf
  182. Date
  183. Text
  184. Set Variable
    Prompt
  185. Replace Text
  186. Set Variable
    Prompt
  187. Comment
    Prepare image for sending in API call
  188. If
  189. Set Variable
    DateTime
  190. Set Variable
    ModelName
  191. Set Variable
    Messages
  192. Resize Image
  193. Convert Image
  194. Comment
    Log image
  195. If
  196. Save File
  197. Base64 Encode
  198. Dictionary
  199. Set Variable
    NoImageMessages
  200. Dictionary

Ver como código
Beta

Todas as ações deste atalho escritas em Cherri, uma linguagem de programação para o app Atalhos. Ótimo para aprender como ele funciona.

#include 'actions/web'
#include 'actions/network'
#define color lightblue
#define glyph atom

/*
Google Gemini Pro via API. 
By Tim Wilson, December 2023

This shortcut is design to be run standalone or from other Shortcuts. It passes the input prompt to Google via their API and returns the response if successful. Logs conversations to Files/Shortcuts/GeminiAPI. 

Input: Text (a prompt, possibly via Share Sheet), 
OR 
a valid Dictionary with optional keys, 
“prompt”, “messages”, “image”, “model”, “temperature”, “apikey”, “repeat”, “speak”, “datetime”, and “disablelogging”
OR 
nothing. If no prompt is provided, user will be asked to provide one before continuing. 

Output: A text string containing the bot response, OR an output dictionary containing “messages” and “output”. 

Setup:  Can set default model, API key and temperature.
*/
/*
Dictionary input arguments:
“model” a valid model name to use.
“temperature” a number between 0 and 
“messages” a JSON array passed as the “contents” to the API. You don’t have to build it manually, since it’spart of the output. Just maintain it between calls to the shortcut. (see https://ai.google.dev/tutorials/rest_quickstart#multi-turn_conversations_chat). 
“image” is a text string that is a base64-encoded image. 
“repeat” is 0 or 1 to control if this shortcut repeats automatically (ongoing conversation). 1 to repeat. 
“speak” is 0 or 1 to control if output is read aloud. 1 to speak. 
“datetime” used to save image/json files. 
“disablelogging” set to “1” to disable logging (to Files/Shortcuts/GeminiAPI)

https://ai.google.dev/docs/concepts#model_parameters
https://ai.google.dev/tutorials/rest_quickstart#configuration

Dictionary output content:
When a dictionary is used as input, this shortcut will output a dictionary with “output” string, “messages” JSON array, “title” automatically made by Gemini, and “datetime” string that can be passed back into the shortcut.
*/
// Enter your Google API key. Get one here: https://makersuite.google.com/app/apikey

@APIKey = ""
/*
Set default text model to use when not provided in input dictionary.
Possible options: “gemini-pro”

https://platform.openai.com/docs/models/continuous-model-upgrades
*/
@ModelName = "gemini-pro"
// Set default text + vision model to use. Possible values: “gemini-pro-vision”

/*
Set model temperature. Value must be between 0 and 2

https://platform.openai.com/docs/api-reference/chat/create#chat-create-temperature
*/
@Temperature = 0.2
// By default, conversations are logged so that they can be accessed using the “View or continue Gemini conversation” companion shortcut. When conversations are logged, Gemini Pro will create a title for the conversation automatically. Should the title be updated with each message to better reflect the conversation content, which slows things down a bit? 0 for no, or 1 to update title on every logged message.

const AlwaysNewTitle = 0
// Check for shortcut updates

nothing()
/*
【Auto-Update Routine】
Checks For Latest Shortcut Version
↳ https://routinehub.co/shortcut/16590/
*/
const Info = {
	"Author": "twilsonco",
	"RoutineHub ID": 17624,
	"Version": "1.6.1",
	"Version Check": true
}
const True = getValue(Info, "Version Check")

if True == "Yes" {
	const CurrentIPAddress = getExternalIP("IPv4")
	if CurrentIPAddress {
		const Result = downloadURL("https://routinehub.co/api/v1/shortcuts/{Info['RoutineHub ID']}/versions/latest")
		if Result contains "success" {
			const SplitText = splitText(Result['Version'], ".")
			for _ in SplitText {
				@LatestVersion = ((1/1000)^@RepeatIndex)*@RepeatItem+@LatestVersion
			}
			const SplitText1 = splitText(Info['Version'], ".")
			for _ in SplitText1 {
				@CurrentVersion = ((1/1000)^@RepeatIndex)*@RepeatItem+@CurrentVersion
			}
			if @LatestVersion > @CurrentVersion {
				menu "New Version: {Result['Version']}\nRelease: {Result['Release']}\nWhats New: \"{Result['Notes']}\"" {
				item "Update → {Result['Version']}":
					expandURL(Result['URL'])
					const UpdatedText = replaceText("https://www.icloud.com/", "shortcuts://", false)
					openURL(UpdatedText)
					stop()
				item "Skip ({Info['Version']})":
				}
			}
		}
	}
}
/*
【Auto-Update Routine Ends Here】
Support → https://www.reddit.com/r/shortcuts/comments/18j4f9p/

【⚙️】
Convert Semantic Number to Decimals
↳ https://routinehub.co/shortcut/16589/
*/
nothing()
// Get date for naming log file

currentDate()
@DateTime = "{}"
// Set default parameter values

nothing()
@Messages
@Image
@OutputDict = 0
@Repeat = 1
@Speak = True1
@DoLog = True1
@InputSelectionOverride = False

if ShortcutInput {
	@Speak = False
	@Repeat = False
}
// Process shortcut input, if provided

const InputType = typeOf(ShortcutInput)

if InputType == "Text" {
	if ShortcutInput endsWith ".pdf" {
		downloadURL(ShortcutInput)
		@PDFFile
		@InputSelectionOverride = True1
		@Repeat = True1
	} else {
		@Prompt = "You are a helpful assistant. Please respond to the following:\n\n{ShortcutInput}"
	}
}

if InputType == "PDF" {
	@PDFFile = ShortcutInput
	@InputSelectionOverride = True1
	@Repeat = True1
}

if InputType == "Dictionary" {
	// Process dictionary input

	@OutputDict = True1
	if ShortcutInput {
		@Prompt = ShortcutInput
	}
	if ShortcutInput {
		@ModelName = ShortcutInput
	}
	if ShortcutInput {
		@Temperature = ShortcutInput['temperature']
	}
	if ShortcutInput {
		@APIKey = ShortcutInput
	}
	if ShortcutInput {
		@Messages = ShortcutInput
	}
	if ShortcutInput {
		base64Encode(ShortcutInput)
		@Image
	}
	if ShortcutInput {
		@Repeat = ShortcutInput
		if @Repeat ==  {
			@InputSelectionOverride = @Repeat
		}
	}
	if ShortcutInput {
		@Speak = ShortcutInput
	}
	if ShortcutInput {
		@DateTime = ShortcutInput
	}
	const DictionaryValue = getValue(ShortcutInput, "disablelogging")
	if DictionaryValue == 1 {
		@DoLog = False
	}
}
const ImageTypeList = "Image\nPhoto media"
// Empty prompt value, so all user for text/image to use. 


if !@Prompt {
	if ImageTypeList contains InputType {
		@Image = ShortcutInput
	} else {
		if @InputSelectionOverride ==  {
			if @Speak ==  {
				wait(2)
				listen()
				@Prompt
			} else {
				if @PDFFile {
				} else {
				}
			}
		} else {
			menu "What kind of request?" {
			item "Text":
				@Speak = ""
			item "Dictate":
				listen()
				@Prompt
			item "Camera":
				@Speak = False
				const Photo = takePhoto(1, true)
				savePhoto(Photo)
				@Image = Photo
			item "Last photo":
				@Speak = "What is this picture?"
				getLatestPhotos(0)
				@Image
				show(@Image)
			item "Photo from library":
				@Speak = "What is this picture?"
				selectPhotos()
				@Image
			item "Image from Files":
				@Speak = "What is this picture?"
				const File = selectFile()
				getImages(File)
				@Image
			item "PDF file":
				@Speak = "What is this image?"
				selectFile()
				@PDFFile
			item "From clipboard":
				@Speak = "Please summarize the following PDF file"
				const Clipboard = getClipboard()
				const Images = getImages(Clipboard)
				const Count = count(Images)
				if Count > 0 {
					@Image = Images
				} else {
					getText(Clipboard)
					@Prompt
				}
			}
		}
	}
	if !@Prompt {
		prompt("Please enter a prompt to send to Gemini")
		@Prompt
	}
	if @PDFFile {
		menu "Use entire PDF or select pages to include (after viewing file)?" {
		item "Entire PDF":
			const PDFContent = getPDFText(@PDFFile)
		item "Select pages":
			show(@PDFFile)
			const PDFPages = splitPDF(@PDFFile)
			const ChosenItem = chooseFromList(PDFPages, "Select pages", true)
			const PDF = makePDF(ChosenItem)
			getPDFText(PDF)
		}
		currentDate()
		@Prompt = "I have a question or request pertaining to the contents of a PDF file. The name of the file is {@PDFFile['Name']}, created at {@PDFFile['Creation Date']}. The current date and time are {}. Here is my question or request:\n```\n{@Prompt}\n```\nThen, here is the content of the PDF file, which should be used to answer my question or request:\n```\n{}\n```"
	}
}
replaceText("\"", "\\"", @Prompt)
@Prompt
// Prepare image for sending in API call


if @Image {
	@DateTime = DateTimeString
	@ModelName = VisionModelName
	@Messages
	const ResizedImage = resizeImage(@Image, "", "500")
	const ConvertedImage = convertImage(ResizedImage, "", 1, false)
	// Log image

	if @DoLog ==  {
		saveFile("/GeminiAPI/{@DateTime}.jpg", ConvertedImage, true)
	}
	base64Encode(ConvertedImage)
	@NoImageMessages = {
		"parts": [
			{
				"text": "{@Prompt}"
			}
		],
		"role": "user"
	}
	const CurPromptDict1 = {
		"parts": [
			{
				"text": "{@Prompt}"
			},
			{
				"inline_data": {
					"data": "{}",
					"mime_type": "image/jpeg"
				}
			}
		],
		"role": "user"
	}
} else {
	const CurPromptDict2 = {
		"parts": [
			{
				"text": "{@Prompt}"
			}
		],
		"role": "user"
	}
}
// We don’t log the image bytes, so some bookkeeping is done to maintain the messages sent via api versus those saved in logs


if @NoImageMessages {
	@SaveMessage = @NoImageMessages
} else {
	@SaveMessage = CurPromptDict3
}
@OldMessages = @Messages

if @Messages {
	@RunMessages = @Messages
	@RunMessages = CurPromptDict3
	@Messages = @SaveMessage
} else {
	@Messages = @SaveMessage
	@RunMessages = CurPromptDict3
}
// Prepare and make API call

const Dictionary = {
	"generationConfig": {
		"temperature": "{@Temperature}"
	}
}
const Dictionary1 = setValue(Dictionary, "contents", @RunMessages)
const Text = "{@RunMessages}"

if Text contains "inline_data" {
	@ModelName = VisionModelName
}
url("https://generativelanguage.googleapis.com/v1beta/models/{@ModelName}:generateContent?key={@APIKey}")
@TryAgain = True1

repeat _ for 5 {
	if @TryAgain ==  {
		const APIResponse = fileRequest(, "POST", Dictionary1, {
			"Content-Type": "application/json"
		})
		// Extract returned chatbot response

		const candidates = getValue(APIResponse, "candidates")
		if candidates {
			const firstCandidate = getLastItem(candidates)
			const content = getValue(firstCandidate, "content")
			// Update Messages list with chatbot response

			const parts = getValue(content, "parts")
			const firstPart = getListItems(parts, 0, 0)
			const DictionaryValue1 = getValue(firstPart, "text")
			if DictionaryValue1 {
				@TryAgain = False
				@Messages = content
			}
		} else {
			wait(1)
		}
	}
}

if @TryAgain ==  {
	show("Error accessing Gemini: {APIResponse}")
	@Messages = @OldMessages
}
// Prepare shortcut output


if @OutputDict == 1 {
	const Dictionary2 = {
		"datetime": "{@DateTime}",
		"output": "{Output}"
	}
	setValue(Dictionary2, "messages", @Messages)
} else {
}
// Log conversation


if @DoLog ==  {
	createFolder("GeminiAPI")
	@Title
	if AlwaysNewTitle == 0 {
		const ContentsOfFolder = getFolderContents()
		if ContentsOfFolder contains "{@DateTime}.txt" {
			const File1 = getFile("{@DateTime}.txt", false)
			if File1 {
				@Title = File1['title']
			}
		}
	}
	const MessageList = joinText(@Messages, ",")
	if !@Title {
		const Dictionary3 = {
			"disablelogging": 1,
			"prompt": "{}",
			"temperature": 0
		}
		runSelf(Dictionary3)
		@Title = ['output']
	}
	const Text1 = "{\\"title\\": \\"{@Title}\\", \\"messages\\":[{MessageList}]}"
	saveFile("/GeminiAPI/{@DateTime}.json", Text1, true)
}
// If continuing conversation within shortcut, prepare input for recursive shortcut call


if @Repeat == 1 {
	if @Speak == 1 {
		speak(Output, false)
		show(Output)
	} else {
		show(Output)
	}
	const Dictionary4 = {
		"datetime": "{@DateTime}",
		"model": "{@ModelName}",
		"repeat": "1",
		"speak": "{@Speak}",
		"temperature": "{@Temperature}"
	}
	if @Image {
		base64Encode(@Image)
		setValue(Dictionary4, "image")
	} else {
		setValue(Dictionary4, "messages", @Messages)
	}
	runSelf(IfResult)
}

if @Speak == 1 {
	speak(Output, false)
}
mustOutput(, Output)
Descompilado com cherri 2.3.0 (GPL-2.0). Pode precisar de pequenos ajustes antes de compilar.

Avaliações e comentários

Escrever uma avaliação
–
de 5
★★★★★
★★★★
★★★
★★
★
0 ratings

Ainda não há avaliações. Seja o primeiro a compartilhar o que você pensa!

Publicidade

Mais de twilsonco

Ver tudo

Você também pode gostar

Ver tudo
Publicidade