toolslà một tham số tùy chọn trong API Hoàn thành trò chuyện có thể được sử dụng để cung cấp thông số kỹ thuật hàm. Mục đích của việc này là cho phép các mô hình tạo ra các đối số hàm tuân thủ các thông số kỹ thuật được cung cấp. Lưu ý rằng API sẽ không thực sự thực hiện bất kỳ lệnh gọi hàm nào. Việc thực hiện các lệnh gọi hàm bằng cách sử dụng đầu ra của mô hình là tùy thuộc vào các nhà phát triển.
Trong toolstham số, nếu functionstham số được cung cấp thì theo mặc định, mô hình sẽ quyết định khi nào thì phù hợp để sử dụng một trong các hàm. API có thể bị buộc phải sử dụng một hàm cụ thể bằng cách đặt tham số tool_choicethành {"type": "function", "function": {"name": "my_function"}}. API cũng có thể bị buộc không sử dụng bất kỳ hàm nào bằng cách đặt tham tool_choicesố thành "none". Nếu một hàm được sử dụng, đầu ra sẽ chứa "finish_reason": "tool_calls"trong phản hồi, cũng như một tool_callsđối tượng có tên hàm và các đối số hàm được tạo.
- Chỉ với vài bước đơn giản mọi người đã có thể sở hữu ngay tài khoản ChatGPT 4 chính hãng giá rẻ
Tổng quan
Sổ tay này bao gồm 2 phần sau:
- Cách tạo đối số hàm: Chỉ định một tập hợp các hàm và sử dụng API để tạo đối số hàm.
- Cách gọi hàm với các đối số do mô hình tạo ra: Đóng vòng lặp bằng cách thực sự thực thi các hàm với các đối số do mô hình tạo ra.
Cách tạo đối số hàm
!pip install scipy --quiet
!pip install tenacity --quiet
!pip install tiktoken --quiet
!pip install termcolor --quiet
!pip install openai --quiet
import json
from openai import OpenAI
from tenacity import retry, wait_random_exponential, stop_after_attempt
from termcolor import colored
GPT_MODEL = "gpt-4o"
client = OpenAI()Tiện ích
Trước tiên, chúng ta hãy định nghĩa một số tiện ích để thực hiện lệnh gọi đến API Hoàn tất trò chuyện và để duy trì và theo dõi trạng thái cuộc trò chuyện.
@retry(wait=wait_random_exponential(multiplier=1, max=40), stop=stop_after_attempt(3))
def chat_completion_request(messages, tools=None, tool_choice=None, model=GPT_MODEL): try: response = client.chat.completions.create( model=model, messages=messages, tools=tools, tool_choice=tool_choice, ) return response except Exception as e: print("Unable to generate ChatCompletion response") print(f"Exception: {e}") return edef pretty_print_conversation(messages): role_to_color = { "system": "red", "user": "green", "assistant": "blue", "function": "magenta", } for message in messages: if message["role"] == "system": print(colored(f"system: {message['content']}\n", role_to_color[message["role"]])) elif message["role"] == "user": print(colored(f"user: {message['content']}\n", role_to_color[message["role"]])) elif message["role"] == "assistant" and message.get("function_call"): print(colored(f"assistant: {message['function_call']}\n", role_to_color[message["role"]])) elif message["role"] == "assistant" and not message.get("function_call"): print(colored(f"assistant: {message['content']}\n", role_to_color[message["role"]])) elif message["role"] == "function": print(colored(f"function ({message['name']}): {message['content']}\n", role_to_color[message["role"]]))Các khái niệm cơ bản
Hãy tạo một số thông số kỹ thuật hàm để giao tiếp với API thời tiết giả định. Chúng ta sẽ chuyển thông số kỹ thuật hàm này đến API Hoàn thành trò chuyện để tạo ra các đối số hàm tuân thủ thông số kỹ thuật.
tools = [ { "type": "function", "function": { "name": "get_current_weather", "description": "Get the current weather", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA", }, "format": { "type": "string", "enum": ["celsius", "fahrenheit"], "description": "The temperature unit to use. Infer this from the users location.", }, }, "required": ["location", "format"], }, } }, { "type": "function", "function": { "name": "get_n_day_weather_forecast", "description": "Get an N-day weather forecast", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA", }, "format": { "type": "string", "enum": ["celsius", "fahrenheit"], "description": "The temperature unit to use. Infer this from the users location.", }, "num_days": { "type": "integer", "description": "The number of days to forecast", } }, "required": ["location", "format", "num_days"] }, } },
]Nếu chúng ta hỏi mô hình về thời tiết hiện tại, nó sẽ phản hồi bằng một số câu hỏi làm rõ.
messages = []
messages.append({"role": "system", "content": "Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous."})
messages.append({"role": "user", "content": "What's the weather like today"})
chat_response = chat_completion_request( messages, tools=tools
)
assistant_message = chat_response.choices[0].message
messages.append(assistant_message)
assistant_messageChatCompletionMessage(content='Chắc chắn rồi, bạn có thể cung cấp cho tôi tên thành phố và tiểu bang của bạn không?', role='assistant', function_call=None, tool_calls=None)Sau khi chúng ta cung cấp thông tin còn thiếu, nó sẽ tạo ra các đối số hàm thích hợp cho chúng ta.
messages.append({"role": "user", "content": "I'm in Glasgow, Scotland."})
chat_response = chat_completion_request( messages, tools=tools
)
assistant_message = chat_response.choices[0].message
messages.append(assistant_message)
assistant_messageChatCompletionMessage(nội dung=Không có, vai trò='trợ lý', function_call=Không có, tool_calls=[ChatCompletionMessageToolCallBằng cách nhắc nhở theo cách khác, chúng ta có thể khiến nó nhắm tới chức năng khác mà chúng ta đã chỉ định.
messages = []
messages.append({"role": "system", "content": "Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous."})
messages.append({"role": "user", "content": "what is the weather going to be like in Glasgow, Scotland over the next x days"})
chat_response = chat_completion_request( messages, tools=tools
)
assistant_message = chat_response.choices[0].message
messages.append(assistant_message)
assistant_messageChatCompletionMessage(content='Để cung cấp cho bạn dự báo thời tiết cho Glasgow, Scotland, bạn vui lòng chỉ rõ sốMột lần nữa, mô hình yêu cầu chúng ta làm rõ vì nó chưa có đủ thông tin. Trong trường hợp này, nó đã biết vị trí dự báo, nhưng cần biết cần bao nhiêu ngày trong dự báo.
messages.append({"role": "user", "content": "5 days"})
chat_response = chat_completion_request( messages, tools=tools
)
chat_response.choices[0]Lựa chọn(finish_reason='tool_calls', index=0, logprobs=None, message=ChatCompletionMessage(content=None, role='assistant', function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_34PBraFdNN6KR95uD5rHF8Aw', function=Function(arguments='{"location":"Glasgow, Scotland","format":"celsius","num_days":5}', name='get_n_day_weather_forecast'), type='function')]))Buộc sử dụng các chức năng cụ thể hoặc không sử dụng chức năng nào
Chúng ta có thể buộc mô hình sử dụng một hàm cụ thể, ví dụ get_n_day_weather_forecast bằng cách sử dụng đối số function_call. Bằng cách đó, chúng ta buộc mô hình đưa ra các giả định về cách sử dụng nó.
# in this cell we force the model to use get_n_day_weather_forecast
messages = []
messages.append({"role": "system", "content": "Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous."})
messages.append({"role": "user", "content": "Give me a weather report for Toronto, Canada."})
chat_response = chat_completion_request( messages, tools=tools, tool_choice={"type": "function", "function": {"name": "get_n_day_weather_forecast"}}
)
chat_response.choices[0].messageChatCompletionMessage(nội dung=Không có, vai trò='trợ lý', hàm_gọi=Không có, công cụ_gọi=[ChatCompletionMessageToolCall(id='call_FImGxrLowOAOszCaaQqQWmEN', hàm=Hàm(đối số='{"vị trí":"Toronto, Canada","format":"celsius","num_days":7}', tên='get_n_day_weather_forecast'), loại='hàm')])# if we don't force the model to use get_n_day_weather_forecast it may not
messages = []
messages.append({"role": "system", "content": "Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous."})
messages.append({"role": "user", "content": "Give me a weather report for Toronto, Canada."})
chat_response = chat_completion_request( messages, tools=tools
)
chat_response.choices[0].messageChatCompletionMessage(nội dung=Không có, vai trò='trợ lý', hàm_gọi=Không có, công cụ_gọi=[ChatCompletionMessageToolCall(id='call_n84kYFqjNFDPNGDEnjnrd2KC', hàm=Hàm(đối số='{"vị trí": "Toronto, Canada", "format": "celsius"}', tên='get_current_weather'), loại='hàm'), ChatCompletionMessageToolCall(id='call_AEs3AFhJc9pn42hWSbHTaIDh', hàm=Hàm(đối số='{"vị trí": "Toronto, Canada", "format": "celsius", "num_days": 3}', tên='get_n_day_weather_forecast'), loại='hàm')])Chúng ta cũng có thể buộc mô hình không sử dụng bất kỳ hàm nào. Bằng cách đó, chúng ta ngăn không cho mô hình tạo ra lệnh gọi hàm phù hợp.
messages = []
messages.append({"role": "system", "content": "Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous."})
messages.append({"role": "user", "content": "Give me the current weather (use Celcius) for Toronto, Canada."})
chat_response = chat_completion_request( messages, tools=tools, tool_choice="none"
)
chat_response.choices[0].messageChatCompletionMessage(content="Chắc chắn rồi, tôi sẽ lấy thông tin thời tiết hiện tại ở Toronto, Canada theo độ C.", role='assistant', function_call=None, tool_calls=None)Gọi hàm song song
Các mô hình mới hơn như gpt-4o hoặc gpt-3.5-turbo có thể gọi nhiều chức năng trong một lượt.
messages = []
messages.append({"role": "system", "content": "Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous."})
messages.append({"role": "user", "content": "what is the weather going to be like in San Francisco and Glasgow over the next 4 days"})
chat_response = chat_completion_request( messages, tools=tools, model=GPT_MODEL
)
assistant_message = chat_response.choices[0].message.tool_calls
assistant_message[ChatCompletionMessageToolCall(id='call_ObhLiJwaHwc3U1KyB4Pdpx8y', function=Function(arguments='{"location": "San Francisco, CA", "format": "fahrenheit", "num_days": 4}', name='get_n_day_weather_forecast'), type='function'), ChatCompletionMessageToolCall(id='call_5YRgeZ0MGBMFKE3hZiLouwg7', function=Function(arguments='{"location": "Glasgow, SCT", "format": "celsius", "num_days": 4}', name='get_n_day_weather_forecast'), type='function')]Cách gọi hàm với các đối số được tạo bởi mô hình
Trong ví dụ tiếp theo, chúng tôi sẽ trình bày cách thực hiện các hàm có đầu vào được tạo bởi mô hình và sử dụng điều này để triển khai một tác nhân có thể trả lời các câu hỏi cho chúng tôi về cơ sở dữ liệu. Để đơn giản, chúng tôi sẽ sử dụng cơ sở dữ liệu mẫu Chinook .
Lưu ý: Việc tạo SQL có thể có rủi ro cao trong môi trường sản xuất vì các mô hình không hoàn toàn đáng tin cậy trong việc tạo SQL chính xác.
Chỉ định một hàm để thực hiện các truy vấn SQL
Trước tiên, hãy định nghĩa một số hàm tiện ích hữu ích để trích xuất dữ liệu từ cơ sở dữ liệu SQLite.
import sqlite3
conn = sqlite3.connect("data/Chinook.db")
print("Opened database successfully")Đã mở cơ sở dữ liệu thành côngdef get_table_names(conn): """Return a list of table names.""" table_names = [] tables = conn.execute("SELECT name FROM sqlite_master WHERE type='table';") for table in tables.fetchall(): table_names.append(table[0]) return table_names
def get_column_names(conn, table_name): """Return a list of column names.""" column_names = [] columns = conn.execute(f"PRAGMA table_info('{table_name}');").fetchall() for col in columns: column_names.append(col[1]) return column_names
def get_database_info(conn): """Return a list of dicts containing the table name and columns for each table in the database.""" table_dicts = [] for table_name in get_table_names(conn): columns_names = get_column_names(conn, table_name) table_dicts.append({"table_name": table_name, "column_names": columns_names}) return table_dictsBây giờ có thể sử dụng các hàm tiện ích này để trích xuất biểu diễn của lược đồ cơ sở dữ liệu.
database_schema_dict = get_database_info(conn)
database_schema_string = "\n".join( [ f"Table: {table['table_name']}\nColumns: {', '.join(table['column_names'])}" for table in database_schema_dict ]
)Như trước đây, chúng ta sẽ định nghĩa một đặc tả hàm cho hàm mà chúng ta muốn API tạo đối số. Lưu ý rằng chúng ta đang chèn lược đồ cơ sở dữ liệu vào đặc tả hàm. Điều này sẽ quan trọng để mô hình biết.
tools = [ { "type": "function", "function": { "name": "ask_database", "description": "Use this function to answer user questions about music. Input should be a fully formed SQL query.", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": f""" SQL query extracting info to answer the user's question. SQL should be written using this database schema: {database_schema_string} The query should be returned in plain text, not in JSON. """, } }, "required": ["query"], }, } }
]Thực hiện các truy vấn SQL
Bây giờ chúng ta hãy triển khai hàm thực sự sẽ thực hiện các truy vấn trên cơ sở dữ liệu.
def ask_database(conn, query): """Function to query SQLite database with a provided SQL query.""" try: results = str(conn.execute(query).fetchall()) except Exception as e: results = f"query failed with error: {e}" return resultsCác bước để gọi hàm bằng API Hoàn thành trò chuyện:
Bước 1 : Nhắc mô hình với nội dung có thể dẫn đến việc mô hình chọn một công cụ để sử dụng. Mô tả về các công cụ như tên hàm và chữ ký được xác định trong danh sách 'Công cụ' và được chuyển đến mô hình trong lệnh gọi API. Nếu được chọn, tên hàm và các tham số sẽ được bao gồm trong phản hồi.
Bước 2 : Kiểm tra theo chương trình nếu mô hình muốn gọi một hàm. Nếu đúng, tiến hành đến bước 3.
Bước 3 : Trích xuất tên hàm và các tham số từ phản hồi, gọi hàm có tham số. Thêm kết quả vào tin nhắn.
Bước 4 : Gọi API hoàn thành trò chuyện với danh sách tin nhắn để nhận phản hồi.
# Step #1: Prompt with content that may result in function call. In this case the model can identify the information requested by the user is potentially available in the database schema passed to the model in Tools description.
messages = [{ "role":"user", "content": "What is the name of the album with the most tracks?"
}]
response = client.chat.completions.create( model='gpt-4o', messages=messages, tools= tools, tool_choice="auto"
)
# Append the message to messages list
response_message = response.choices[0].message
messages.append(response_message)
print(response_message)ChatCompletionMessage(content=None, role='assistant', function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_wDN8uLjq2ofuU6rVx1k8Gw0e', function=Function(arguments='{"query":"SELECT Album.Title, COUNT(Track.TrackId) AS TrackCount FROM Album INNER JOIN Track ON Album.AlbumId = Track.AlbumId GROUP BY Album.Title ORDER BY TrackCount DESC LIMIT 1;"}', name='ask_database'), type='function')])# Step 2: determine if the response from the model includes a tool call.
tool_calls = response_message.tool_calls
if tool_calls: # If true the model will return the name of the tool / function to call and the argument(s) tool_call_id = tool_calls[0].id tool_function_name = tool_calls[0].function.name tool_query_string = json.loads(tool_calls[0].function.arguments)['query'] # Step 3: Call the function and retrieve results. Append the results to the messages list. if tool_function_name == 'ask_database': results = ask_database(conn, tool_query_string) messages.append({ "role":"tool", "tool_call_id":tool_call_id, "name": tool_function_name, "content":results }) # Step 4: Invoke the chat completions API with the function response appended to the messages list # Note that messages with role 'tool' must be a response to a preceding message with 'tool_calls' model_response_with_function_call = client.chat.completions.create( model="gpt-4o", messages=messages, ) # get a new response from the model where it can see the function response print(model_response_with_function_call.choices[0].message.content) else: print(f"Error: function {tool_function_name} does not exist")
else: # Model did not identify a function to call, result can be returned to the user print(response_message.content) Album có nhiều bài hát nhất có tựa đề "Greatest Hits", bao gồm 57 bài hát.Các bước tiếp theo
Xem sổ tay khác của chúng tôi hướng dẫn cách sử dụng API Hoàn thành trò chuyện và các hàm để truy xuất kiến thức nhằm tương tác theo kiểu đàm thoại với cơ sở kiến thức.
Xem thêm: mua tài khoản ChatGPT Plus để viết code không còn là công việc khó khăn

Cách đổi Mật khẩu Chat GPT - Hướng dẫn đổi Pass Chat GPT 100% Thành công
Hướng dẫn Cách đăng nhập Chat GPT Nhanh nhất | Có hỗ trợ Miễn phí qua Teamview-Ultraview
Chat GPT Plus là gì? So sánh Chat GPT Plus với Chat GPT Miễn phí
Chat GPT bị giới hạn giải thích vì sao và cách khắc phục
Chat GPT là gì ? Cách đăng Ký Chat GPT Miễn Phí tại Việt Nam