作者:AI小火箭的HB
我是AI小火箭的HB,我探索和寫作人工智能和語言交叉點的所有事物,範圍從LLM,聊天機器人,語音機器人,開發架構,以資料為中心的潛在空間等。
範例
初步體驗
OpenAI新增了“函數調用”功能,這是什麼呢?
我們先調用API來體驗下。
下面是發送到模型的 JSON 文檔。此調用的目的是生成一個 JSON 檔案,該檔案可用于發送到發送電子郵件的 API。
您可以看到函數名稱為 send_email,并定義了三個參數, to_address , subject 和 body ,即電子郵件正文。
使用者請求為:Send Cobus from humanfirst ai an email asking for the monthly report?
curl --location 'https://api.openai.com/v1/chat/completions' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer sk-xxxx' \--data '{ "model": "gpt-3.5-turbo-0613", "messages": [ {"role": "user", "content": "Send Cobus from humanfirst ai an email asking for the monthly report?"} ], "functions": [ { "name": "send_email", "description": "Please send an email.", "parameters": { "type": "object", "properties": { "to_address": { "type": "string", "description": "To address for email" }, "subject": { "type": "string", "description": "subject of the email" }, "body": { "type": "string", "description": "Body of the email" } } } } ]}'
下面是傳回的 JSON
{ "id": "chatcmpl-7TQuwzJpQAY470saQM2RPfxwF6DDE", "object": "chat.completion", "created": 1687249338, "model": "gpt-3.5-turbo-0613", "choices": [ { "index": 0, "message": { "role": "assistant", "content": null, "function_call": { "name": "send_email", "arguments": "{\n \"to_address\": \"[email protected]\",\n \"subject\": \"Request for Monthly Report\",\n \"body\": \"Hi Cobus,\\n\\nI hope you're doing well. Could you please share the monthly report with me? It would be great to have it before the end of the week.\\n\\nThanks,\\n[Your Name]\"\n}" } }, "finish_reason": "function_call" } ], "usage": { "prompt_tokens": 86, "completion_tokens": 82, "total_tokens": 168 }}
GPT模型會傳回需要調用的函數名 send_email和對應的參數(放在arguments字段)。
{ "to_address": "[email protected]", "subject": "Request for Monthly Report", "body": "Hi Cobus,\n\nI hope you're doing well. Could you please share the monthly report with me? It would be great to have it before the end of the week.\n\nThanks,\n[Your Name]"}
這就非常有用,第三方的應用可以提供多個函數/服務(類似插件),GPT模型可以根據使用者的指令自動選擇不同的函數/服務。
現在再來看示例,就比較清晰了。
用途
根據官網文檔,函數調用允許您更可靠地從模型中擷取結構化資料。例如,您可以:
- 建立聊天機器人,通過調用外部 API 來回答問題(例如 ChatGPT 插件)
- 例如,定義像 send_email(to: string, body: string) 或 get_current_weather(location: string, unit: 'celsius' | 'fahrenheit') 這樣的函數
- 将自然語言轉換為 API 調用
- 例如,将“誰是我的頂級客戶?”轉換為 get_customers(min_revenue: int, created_before: string, limit: int) 并調用您的内部 API
- 從文本中提取結構化資料
- 例如,定義一個名為 extract_data(name: string, birthday: string) 或 sql_query(query: string) 的函數
函數調用的基本步驟順序如下:
- 使用使用者查詢和函數參數中定義的一組函數調用模型。
- 模型可以選擇調用函數;如果是這樣,内容将是符合自定義架構的字元串化 JSON 對象(注意:模型可能會生成無效的 JSON 或幻覺參數)。
- 在代碼中将字元串解析為 JSON,并使用提供的參數調用函數(如果存在)。
- 通過将函數響應追加為新消息來再次調用模型,并讓模型将結果彙總回給使用者。
AI小火箭
AI小火箭已經支援函數調用和gpt-3.5-turbo-16k、gpt-3.5-turbo-0613、gpt-3.5-turbo-16k-0613,大家可以去體驗下。