Формирование запроса к LLM: В вашем Python-скрипте вы формируете запрос к LLM, включая описание доступных инструментов (функций). Пример:
import requests
import json
LM_STUDIO_API_URL = "http://localhost:1234/v1/chat/completions" # Замените на ваш URL LM Studio
tools = [
{
"type": "function",
"function": {
"name": "search_products",
"description": "Search product catalog",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string"},
"category": {"type": "string", "enum": ["electronics", "clothing", "books"]}
}
}
}
}
]
user_message = "Find me a good laptop."
messages = [{"role": "user", "content": user_message}]
data = {
"model": "YourModelName", # Замените на имя модели, которую вы используете в LM Studio
"messages": messages,
"tools": tools,
"tool_choice": "auto" # Или конкретное имя функции, если хотите заставить LLM использовать именно ее
}
headers = {"Content-Type": "application/json"}
response = requests.post(LM_STUDIO_API_URL, headers=headers, data=json.dumps(data))
if response.status_code == 200:
response_data = response.json()
message = response_data["choices"][0]["message"]
if "tool_calls" in message:
tool_calls = message["tool_calls"]
for tool_call in tool_calls:
function_name = tool_call["function"]["name"]
function_arguments = json.loads(tool_call["function"]["arguments"])
if function_name == "search_products":
query = function_arguments["query"]
category = function_arguments.get("category", None) # Category может быть необязательным
# ВАЖНО: Здесь вызывается ВАША ФУНКЦИЯ search_products!
search_results = search_products(query, category)
# Отправляем результаты обратно в LLM для продолжения беседы
messages.append(message) # Append the LLM's function call message
messages.append(
{
"role": "tool",
"tool_call_id": tool_call["id"],
"content": json.dumps(search_results),
}
)
data["messages"] = messages # Update messages with function results
response = requests.post(LM_STUDIO_API_URL, headers=headers, data=json.dumps(data)) # Send new request
if response.status_code == 200:
final_response_data = response.json()
print(final_response_data["choices"][0]["message"]["content"]) # Print LLM final response
else:
print(message["content"]) # Просто текст от LLM
else:
print(f"Error: {response.status_code} - {response.text}")
# Обязательно реализуйте эту функцию!
def search_products(query: str, category: str = None) -> list:
"""
Имитирует поиск продуктов в каталоге.
"""
print(f"Searching for products with query: '{query}' and category: '{category}'")
# Здесь должна быть реальная логика поиска в вашей базе данных или API
if category == "electronics":
if "laptop" in query.lower():
return [{"name": "Awesome Laptop X100", "price": 1200}, {"name": "Budget Laptop Y50", "price": 500}]
else:
return [{"name": "Generic Electronics Product", "price": 100}]
elif category == "clothing":
return [{"name": "Generic Clothing Item", "price": 50}]
elif category == "books":
return [{"name": "Generic Book", "price": 20}]
else:
return [{"name": "Generic Product", "price": 75}]