Unity 카탈로그 AI 에이전트 도구는 LangChain, LlamaIndex, OpenAI 및 Anthropic 같은 인기 있는 Gen AI 라이브러리에서 사용할 수 있습니다. 이러한 통합은 Unity 카탈로그 도구 거버넌스와 타사 에이전트 제작 프레임워크의 기능을 결합합니다. 다음은 그 예입니다.
- LangChain에서 Unity 카탈로그 함수는 데이터 쿼리 또는 변환과 같은 작업을 수행하는 에이전트 워크플로의 일부가 될 수 있습니다.
- OpenAI 또는 Anthropic 통합에서 함수는 실행 중에 AI 모델에 의해 직접 호출됩니다.
다음 탭에서 프레임워크를 선택하여 Unity 카탈로그 도구를 만들고 해당 프레임워크와 함께 사용합니다. Azure Databricks Notebook 또는 Python 스크립트에서 코드를 실행합니다.
Requirements
- Python 3.10 이상을 설치합니다.
LangChain
Azure Databricks Unity 카탈로그를 사용하여 SQL 및 Python 함수를 LangChain 및 LangGraph 워크플로의 도구로 통합합니다. 이 통합은 Unity 카탈로그의 거버넌스와 LangChain 기능을 결합하여 강력한 LLM 기반 애플리케이션을 빌드합니다.
이 예제에서는 Unity 카탈로그 도구를 만들고, 해당 기능을 테스트하고, 에이전트에 추가합니다.
종속성 설치
Databricks 선택 사항으로 Unity 카탈로그 AI 패키지를 설치하고 LangChain 통합 패키지를 설치합니다.
# Install the Unity Catalog AI integration package with the Databricks extra
%pip install unitycatalog-langchain[databricks]
# Install Databricks Langchain integration package
%pip install databricks-langchain
dbutils.library.restartPython()
Databricks 함수 클라이언트 초기화
Databricks 함수 클라이언트를 초기화합니다.
from unitycatalog.ai.core.base import get_uc_function_client
client = get_uc_function_client()
도구의 논리 정의
도구의 논리를 포함하는 Unity 카탈로그 함수를 만듭니다.
CATALOG = "my_catalog"
SCHEMA = "my_schema"
def add_numbers(number_1: float, number_2: float) -> float:
"""
A function that accepts two floating point numbers adds them,
and returns the resulting sum as a float.
Args:
number_1 (float): The first of the two numbers to add.
number_2 (float): The second of the two numbers to add.
Returns:
float: The sum of the two input numbers.
"""
return number_1 + number_2
function_info = client.create_python_function(
func=add_numbers,
catalog=CATALOG,
schema=SCHEMA,
replace=True
)
기능을 테스트하세요
함수를 테스트하여 예상대로 작동하는지 확인합니다.
result = client.execute_function(
function_name=f"{CATALOG}.{SCHEMA}.add_numbers",
parameters={"number_1": 36939.0, "number_2": 8922.4}
)
result.value # OUTPUT: '45861.4'
UCFunctionToolKit를 사용하여 함수 래핑
에이전트 작성 라이브러리에서 액세스할 수 있도록, 함수를 UCFunctionToolkit로 감쌉니다. 도구 키트는 여러 라이브러리에서 일관성을 보장하고 검색기의 자동 추적과 같은 유용한 기능을 추가합니다.
from databricks_langchain import UCFunctionToolkit
# Create a toolkit with the Unity Catalog function
func_name = f"{CATALOG}.{SCHEMA}.add_numbers"
toolkit = UCFunctionToolkit(function_names=[func_name])
tools = toolkit.tools
에이전트 내에서 도구 사용
LangChain 에이전트에 tools 도구를 추가하려면 UCFunctionToolkit의 속성을 사용하십시오.
이 예제에서는 간결성을 위해 LangChain의 AgentExecutor API를 사용하여 간단한 에이전트를 작성합니다. 프로덕션 워크로드의 경우 AI 에이전트 작성에 표시된 에이전트 작성 워크플로 를 사용하여 Databricks Apps에 배포합니다.
from langchain.agents import AgentExecutor, create_tool_calling_agent
from langchain.prompts import ChatPromptTemplate
from databricks_langchain import (
ChatDatabricks,
UCFunctionToolkit,
)
import mlflow
# Initialize the LLM (replace with your LLM of choice, if desired)
LLM_ENDPOINT_NAME = "databricks-meta-llama-3-3-70b-instruct"
llm = ChatDatabricks(endpoint=LLM_ENDPOINT_NAME, temperature=0.1)
# Define the prompt
prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"You are a helpful assistant. Make sure to use tools for additional functionality.",
),
("placeholder", "{chat_history}"),
("human", "{input}"),
("placeholder", "{agent_scratchpad}"),
]
)
# Enable automatic tracing
mlflow.langchain.autolog()
# Define the agent, specifying the tools from the toolkit above
agent = create_tool_calling_agent(llm, tools, prompt)
# Create the agent executor
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
agent_executor.invoke({"input": "What is 36939.0 + 8922.4?"})
LlamaIndex
Azure Databricks Unity 카탈로그를 사용하여 SQL 및 Python 함수를 LlamaIndex 워크플로의 도구로 통합합니다. 이 통합은 Unity 카탈로그 거버넌스와 LlamaIndex의 기능을 결합하여 LLM에 대한 큰 데이터 세트를 인덱싱하고 쿼리합니다.
LlamaIndex용 Databricks Unity 카탈로그 통합 패키지를 설치합니다.
%pip install unitycatalog-llamaindex[databricks] dbutils.library.restartPython()Unity 카탈로그 함수 클라이언트의 인스턴스를 만듭니다.
from unitycatalog.ai.core.base import get_uc_function_client client = get_uc_function_client()Python으로 작성된 Unity 카탈로그 함수를 만듭니다.
CATALOG = "your_catalog" SCHEMA = "your_schema" func_name = f"{CATALOG}.{SCHEMA}.code_function" def code_function(code: str) -> str: """ Runs Python code. Args: code (str): The Python code to run. Returns: str: The result of running the Python code. """ import sys from io import StringIO stdout = StringIO() sys.stdout = stdout exec(code) return stdout.getvalue() client.create_python_function( func=code_function, catalog=CATALOG, schema=SCHEMA, replace=True )Unity 카탈로그 함수의 인스턴스를 도구 키트로 만들고 실행하여 도구가 제대로 작동하는지 확인합니다.
from unitycatalog.ai.llama_index.toolkit import UCFunctionToolkit import mlflow # Enable traces mlflow.llama_index.autolog() # Create a UCFunctionToolkit that includes the UC function toolkit = UCFunctionToolkit(function_names=[func_name]) # Fetch the tools stored in the toolkit tools = toolkit.tools python_exec_tool = tools[0] # Run the tool directly result = python_exec_tool.call(code="print(1 + 1)") print(result) # Outputs: {"format": "SCALAR", "value": "2\n"}LlamaIndex 도구 컬렉션의 일부로 Unity 카탈로그 함수를 정의하여 LlamaIndex ReActAgent에서 도구를 사용합니다. 그런 다음, LlamaIndex 도구 컬렉션을 호출하여 에이전트가 제대로 작동하는지 확인합니다.
from llama_index.llms.openai import OpenAI from llama_index.core.agent import ReActAgent llm = OpenAI() agent = ReActAgent.from_tools(tools, llm=llm, verbose=True) agent.chat("Please run the following python code: `print(1 + 1)`")
OpenAI
Azure Databricks Unity 카탈로그를 사용하여 SQL 및 Python 함수를 OpenAI 워크플로의 도구로 통합합니다. 이 통합은 Unity 카탈로그의 거버넌스와 OpenAI를 결합하여 강력한 세대 AI 앱을 만듭니다.
OpenAI용 Databricks Unity 카탈로그 통합 패키지를 설치합니다.
%pip install unitycatalog-openai[databricks] %pip install mlflow -U dbutils.library.restartPython()Unity 카탈로그 함수 클라이언트의 인스턴스를 만듭니다.
from unitycatalog.ai.core.base import get_uc_function_client client = get_uc_function_client()Python으로 작성된 Unity 카탈로그 함수를 만듭니다.
CATALOG = "your_catalog" SCHEMA = "your_schema" func_name = f"{CATALOG}.{SCHEMA}.code_function" def code_function(code: str) -> str: """ Runs Python code. Args: code (str): The python code to run. Returns: str: The result of running the Python code. """ import sys from io import StringIO stdout = StringIO() sys.stdout = stdout exec(code) return stdout.getvalue() client.create_python_function( func=code_function, catalog=CATALOG, schema=SCHEMA, replace=True )Unity 카탈로그 함수의 인스턴스를 도구 키트로 만들고 함수를 실행하여 도구가 제대로 작동하는지 확인합니다.
from unitycatalog.ai.openai.toolkit import UCFunctionToolkit import mlflow # Enable tracing mlflow.openai.autolog() # Create a UCFunctionToolkit that includes the UC function toolkit = UCFunctionToolkit(function_names=[func_name]) # Fetch the tools stored in the toolkit tools = toolkit.tools client.execute_function = tools[0]도구와 함께 OpenAI 모델에 요청을 제출합니다.
import openai messages = [ { "role": "system", "content": "You are a helpful customer support assistant. Use the supplied tools to assist the user.", }, {"role": "user", "content": "What is the result of 2**10?"}, ] response = openai.chat.completions.create( model="gpt-4o-mini", messages=messages, tools=tools, ) # check the model response print(response)OpenAI가 응답을 반환한 후 Unity 카탈로그 함수 호출을 호출하여 OpenAI에 응답 응답을 다시 생성합니다.
import json # OpenAI sends only a single request per tool call tool_call = response.choices[0].message.tool_calls[0] # Extract arguments that the Unity Catalog function needs to run arguments = json.loads(tool_call.function.arguments) # Run the function based on the arguments result = client.execute_function(func_name, arguments) print(result.value)응답이 반환되면 OpenAI에 대한 후속 호출에 대한 응답 페이로드를 생성할 수 있습니다.
# Create a message containing the result of the function call function_call_result_message = { "role": "tool", "content": json.dumps({"content": result.value}), "tool_call_id": tool_call.id, } assistant_message = response.choices[0].message.to_dict() completion_payload = { "model": "gpt-4o-mini", "messages": [*messages, assistant_message, function_call_result_message], } # Generate final response openai.chat.completions.create( model=completion_payload["model"], messages=completion_payload["messages"] )
Utilities
도구 응답을 ucai-openai 만드는 프로세스를 간소화하기 위해 패키지에는 OpenAI ChatCompletion 응답 메시지를 변환하여 응답 생성에 사용할 수 있는 유틸리티 generate_tool_call_messages가 있습니다.
from unitycatalog.ai.openai.utils import generate_tool_call_messages
messages = generate_tool_call_messages(response=response, client=client)
print(messages)
메모
응답에 다중 선택 항목이 포함된 경우 generate_tool_call_messages 호출할 때 choice_index 인수를 전달하여 사용할 선택 항목을 선택할 수 있습니다. 현재는 다중 선택 항목 처리를 지원하지 않습니다.
Anthropic
Azure Databricks Unity 카탈로그를 사용하여 SQL 및 Python 함수를 Anthropic SDK LLM 호출의 도구로 통합합니다. 이 통합은 Unity 카탈로그의 거버넌스와 Anthropic 모델을 결합하여 강력한 세대 AI 앱을 만듭니다.
메모
Anthropic 통합하려면 Databricks Runtime 15.0 이상이 필요합니다.
Anthropic용 Databricks Unity 카탈로그 통합 패키지를 설치합니다.
%pip install unitycatalog-anthropic[databricks] dbutils.library.restartPython()Unity 카탈로그 함수 클라이언트의 인스턴스를 만듭니다.
from unitycatalog.ai.core.base import get_uc_function_client client = get_uc_function_client()Python으로 작성된 Unity 카탈로그 함수를 만듭니다.
CATALOG = "your_catalog" SCHEMA = "your_schema" func_name = f"{CATALOG}.{SCHEMA}.weather_function" def weather_function(location: str) -> str: """ Fetches the current weather from a given location in degrees Celsius. Args: location (str): The location to fetch the current weather from. Returns: str: The current temperature for the location provided in Celsius. """ return f"The current temperature for {location} is 24.5 celsius" client.create_python_function( func=weather_function, catalog=CATALOG, schema=SCHEMA, replace=True )Unity 카탈로그 함수의 인스턴스를 도구 키트로 만듭니다.
from unitycatalog.ai.anthropic.toolkit import UCFunctionToolkit # Create an instance of the toolkit toolkit = UCFunctionToolkit(function_names=[func_name], client=client)Anthropic에서 도구 호출을 실행합니다.
import anthropic # Initialize the Anthropic client with your API key anthropic_client = anthropic.Anthropic(api_key="YOUR_ANTHROPIC_API_KEY") # User's question question = [{"role": "user", "content": "What's the weather in New York City?"}] # Make the initial call to Anthropic response = anthropic_client.messages.create( model="claude-3-5-sonnet-20240620", # Specify the model max_tokens=1024, # Use 'max_tokens' instead of 'max_tokens_to_sample' tools=toolkit.tools, messages=question # Provide the conversation history ) # Print the response content print(response)도구 응답을 생성합니다. 도구를 호출해야 하는 경우 Claude 모델의 응답에는 도구 요청 메타데이터 블록이 포함됩니다.
from unitycatalog.ai.anthropic.utils import generate_tool_call_messages # Call the UC function and construct the required formatted response tool_messages = generate_tool_call_messages( response=response, client=client, conversation_history=question ) # Continue the conversation with Anthropic tool_response = anthropic_client.messages.create( model="claude-3-5-sonnet-20240620", max_tokens=1024, tools=toolkit.tools, messages=tool_messages, ) print(tool_response)
패키지에는 unitycatalog.ai-anthropic Unity 카탈로그 함수에 대한 호출의 구문 분석 및 처리를 간소화하는 메시지 처리기 유틸리티가 포함되어 있습니다. 유틸리티는 다음을 수행합니다.
- 도구 호출 요구 사항을 검색합니다.
- 쿼리에서 도구 호출 정보를 추출합니다.
- Unity 카탈로그 함수에 대한 호출을 수행합니다.
- Unity 카탈로그 함수의 응답을 구문 분석합니다.
- 다음 메시지 형식을 작성하여 Claude와의 대화를 계속합니다.
메모
API에 대한 인수 conversation_history 에 generate_tool_call_messages 전체 대화 기록을 제공해야 합니다. Claude 모델에는 대화의 초기화(원래 사용자 입력 질문) 및 모든 후속 LLM 생성 응답 및 다중 턴 도구 호출 결과가 필요합니다.