生成式AI導論2024 - 快速呼叫Gemini API 與互動
生成式AI導論2024 - 快速呼叫Gemini API 與互動¶
來源是台大開放式課程Hung-yi Lee 教授的課程
快速上手透過VScode 呼叫Gemini
- 去拿到你的Gemini API key,並且妥善保存
- 再terminal 運行 Git clone https://github.com/1daniel3333/genAI_HW.git
- 依據Readme指令,創建cred.py檔案,貼上keys = { ‘GEMINI_API_KEY’: ‘這裡放入你的API Key’, }
- 運行AI_HW3 (要先安裝對應package)
如何拿到API Key?
🔑 步驟一:註冊 Google Cloud Platform 帳號¶
- 前往 https://console.cloud.google.com/
- 如果你還沒有 Google Cloud 帳戶,註冊一個並完成驗證(包含信用卡驗證,但不會立即收費)。
🧭 步驟二:建立新專案¶
- 點選左上角的 「專案選擇器」(Select Project)
- 按下「新增專案」
- 命名後建立,等待幾秒鐘
🔌 步驟三:啟用 Gemini API¶
- 在主控台搜尋框輸入 Gemini 或 Generative Language API
- 點進 Generative Language API(或叫 Vertex AI Gemini)
- 點選 「啟用」
🗝️ 步驟四:建立 API 金鑰¶
- 左側選單點選 API 與服務 → 認證資訊(Credentials)
- 點選 「建立認證」 → 選擇 API 金鑰
- 系統會產生一串金鑰(即你的 Gemini API key)
如何複製github 專案 (專案位置: https://github.com/1daniel3333/genAI_HW)
✅ 使用 Git 指令(推薦)¶
- 打開終端機(Terminal)或命令提示字元(Command Prompt)
- 執行以下指令:
git clone https://github.com/1daniel3333/genAI_HW.git
成功後你會在當前資料夾下看到一個 genAI_HW 資料夾,裡面就是專案的所有內容。
如何與Gemini 對話?
import google.generativeai as genaigenai.configure(api_key="你的 API 金鑰")model = genai.GenerativeModel("gemini-pro")response = model.generate_content("Hello Gemini!")print(response.text)
如果一切順利,你應該會看到Gemini跟你打招呼
如何進行多輪對話
方法一: 透過內建function model.start_chat()
# 建立模型物件# model...# 開啟對話(保持上下文)chat = model.start_chat()# 第一次對話response = chat.send_message("你好,幫我想一個旅遊計畫")print("Gemini:", response.text)# 第二次對話(有記憶)response = chat.send_message("可以包含海邊嗎?")print("Gemini:", response.text)# 第三次對話(還記得前面說過的)response = chat.send_message("太好了,那附近有推薦的美食嗎?")print("Gemini:", response.text)
透過呼叫model.start_chat(),程式會自動記憶跟你的對話並延續
方法二: 自行維護對話歷史
def interact_customize(chatbot: list[tuple[str, str]], prompt: str ,user_input: str, temp = 1.0)->list: ''' * Arguments - chatbot: the model itself, the conversation is stored in list of tuples - prompt: the prompt for your desginated task - user_input: the user input of each round of conversation - temp: the temperature parameter of this model. Temperature is used to control the output of the chatbot. The higher the temperature is, the more creative response you will get. ''' try: messages = [] for input_text, response_text in chatbot: messages.append({'role': 'user', 'parts': [input_text]}) messages.append({'role': 'model', 'parts': [response_text]}) messages.append({'role': 'user', 'parts': [prompt]}) response = model.generate_content( messages, generation_config=genai.types.GenerationConfig(temperature=temp), safety_settings=[ {"category": "HARM_CATEGORY_HARASSMENT","threshold": "BLOCK_NONE",}, {"category": "HARM_CATEGORY_HATE_SPEECH","threshold": "BLOCK_NONE",}, {"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT","threshold": "BLOCK_NONE",}, {"category": "HARM_CATEGORY_DANGEROUS_CONTENT","threshold": "BLOCK_NONE",}, ] ) chatbot.append((user_input, response.text)) except Exception as e: print(f"Error occurred: {e}") chatbot.append((user_input, f"Sorry, an error occurred: {e}")) return chatbot#呼叫chatbot = []prompt = 'You are a poet'user_input = "Hello, can you create a poet for me?"chatbot = interact_customize(chatbot, prompt, user_input)
以上的程式碼,
interact_customize程式內會不停的把來自AI的回應{‘role’: ‘model’, ‘parts’: 'AI的回答'} 以及使用者的輸入{‘role’: ‘user’, ‘parts’: '使用者的提問'}做成一個list,再一次性丟給AI,因此也需要注意整體對話如果過長,超出token限制就會導致錯誤。
這樣就可以簡易透過API呼叫Gemini作互動,例如傳統需要爬蟲去拿到特定股價,現在可以直接呼叫Gemini (聯網的) 去拿到最新資料即可,更多應用等待開發。
Comments
Loading comments…
Leave a Comment