Các công cụ và gọi hàm LangChain (phần 10)

Thực thi gọi hàm trong LangChain (tiếp tục)

3. Khởi tạo hàm động: Khởi tạo các hàm động dựa trên bối cảnh trao đổi trò chuyện hay nhập vào người dùng.

import json
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain
llm = AzureOpenAI(deployment_name=”<Azure deployment name>”, model_name=”<Model name>”)
function_generator_prompt = PromptTemplate(

input_variables=[“context”],
template=”Based on the following context, generate a JSON specification for a function that would be useful: {context}\nEnsure the output is a single, valid JSON object.” # Added instruction for

valid JSON

)
function_generator_chain = LLMChain(llm=llm, prompt=function_generator_prompt)
def generate_dynamic_function(context):

function_spec = function_generator_chain.run(context=context)
try:

# Attempt to parse JSON, handle errors gracefully
return json.loads(function_spec)

except json.JSONDecodeError as e:

print(f”Error decoding JSON: {e}\nRaw output: {function_spec}”) # Print error and raw output for debugging
return None # Or handle the error differently

context = “The user is asking about financial calculations related to mortgages.”
dynamic_function = generate_dynamic_function(context)
Output
{‘functionName’: ‘calculateMortgage’,
‘description’: ‘This function calculates various financial values related to mortgages.’,
‘parameters’: [{‘name’: ‘principal’,
…………
principal and interest.’}}}

Code này tích hợp LangChain với LLM để khởi tạo động một tiêu chuẩn kĩ thuật JSON cho một hàm dựa trên một bối cảnh
đã cho. Nó sử dụng một PromptTemplate để hướng dẫn LLM sinh ra một JSON object hiệu lực và đảm bảo sự mạnh mẽ
bằng cách thử duyệt đầu ra JSON, xử lí các lỗi thanh thoát nếu đầu ra là không hiệu lực. Bối cảnh ví dụ được cung
cấp liên quan đến các tính toán tài chính cho mortgages.
4. Meta- learning cho gọi hàm: Thực thi một hệ thống nơi LLM học cải thiện khả năng gọi hàm của nó theo thời gian.

from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationChain
from langchain.chat_models import ChatOpenAI
# Assuming ‘chat’ is your ChatOpenAI instance
llm = AzureOpenAI(deployment_name=”<Azure deployment name>”, model_name=”<Model name>”)
memory = ConversationBufferMemory()
conversation = ConversationChain(

llm=llm,
memory=memory,
verbose=True

)
def meta_function_caller(query, available_functions):

# 1. Provide context and ask for function choice
conversation.predict(
input=f”Query: {query}\nAvailable functions:
{‘, ‘.join(available_functions)}”
)
# 2. Get the function choice (extract from response if needed)
function_choice_response = conversation.predict(input=”Which function should be called for this query?”)
function_choice = function_choice_response.strip() # Extract and clean the function name
# You might need more sophisticated logic to extract the function name reliably
# 3. Validate function choice (optional but recommended)
if function_choice not in available_functions:

print (f”Warning: Invalid function choice ‘{function_choice}’.”)
# Handle invalid choice, e.g., reprompt or choose a default

return function_choice

query = “What is the stock that I can buy for $1000 over 5 years at 5% annual rate?”
available_functions = [“calculate_compound_interest”, “get_stock_price”, “convert_currency”]
chosen_function = meta_function_caller(query, available_functions)

Code này tạo một hệ thống AI trao đổi trò chuyện sử dụng ConversationChain của LangChain với ghi nhớ. Phương thức
meta_function_caller phân tích một truy vấn, tham vấn mô hình ngôn ngữ để chọn một hàm phù hợp từ các tùy chọn có
sãn, và trả về tên hàm được chọn cho thực thi tiềm tàng.

Chia sẻ