---
title: OpenGradientToolkit
---

이 노트북은 OpenGradient toolkit을 사용하여 tool을 구축하는 방법을 보여줍니다. 이 toolkit은 사용자가 [OpenGradient network](https://www.opengradient.ai/)의 model과 workflow를 기반으로 커스텀 tool을 생성할 수 있는 기능을 제공합니다.

## Setup

OpenGradient network에 액세스하려면 OpenGradient API key가 있는지 확인하세요. 이미 API key가 있는 경우 환경 변수를 설정하기만 하면 됩니다:

```python
!export OPENGRADIENT_PRIVATE_KEY="your-api-key"
새 API key를 설정해야 하는 경우 opengradient SDK를 다운로드하고 지침에 따라 새 구성을 초기화하세요.
!pip install opengradient
!opengradient config init

Installation

이 toolkit은 langchain-opengradient package에 있습니다:
pip install -qU langchain-opengradient

Instantiation

이제 이전의 API key로 toolkit을 인스턴스화할 수 있습니다.
from langchain_opengradient import OpenGradientToolkit

toolkit = OpenGradientToolkit(
    # Not required if you have already set the environment variable OPENGRADIENT_PRIVATE_KEY
    private_key="your-api-key"
)

자체 tool 구축하기

OpenGradientToolkit은 커스텀 tool을 생성하기 위한 두 가지 주요 method를 제공합니다:

1. ML model을 실행하는 tool 생성

OpenGradient model hub에 배포된 ML model을 활용하는 tool을 생성할 수 있습니다. 사용자가 생성한 model은 OpenGradient SDK를 통해 model hub에 업로드, 추론 및 공유할 수 있습니다.
import opengradient as og
from pydantic import BaseModel, Field


# Example 1: Simple tool with no input schema
def price_data_provider():
    """Function that provides input data to the model."""
    return {
        "open_high_low_close": [
            [2535.79, 2535.79, 2505.37, 2515.36],
            [2515.37, 2516.37, 2497.27, 2506.94],
            [2506.94, 2515, 2506.35, 2508.77],
            [2508.77, 2519, 2507.55, 2518.79],
            [2518.79, 2522.1, 2513.79, 2517.92],
            [2517.92, 2521.4, 2514.65, 2518.13],
            [2518.13, 2525.4, 2517.2, 2522.6],
            [2522.59, 2528.81, 2519.49, 2526.12],
            [2526.12, 2530, 2524.11, 2529.99],
            [2529.99, 2530.66, 2525.29, 2526],
        ]
    }


def format_volatility(inference_result):
    """Function that formats the model output."""
    return format(float(inference_result.model_output["Y"].item()), ".3%")


# Create the tool
volatility_tool = toolkit.create_run_model_tool(
    model_cid="QmRhcpDXfYCKsimTmJYrAVM4Bbvck59Zb2onj3MHv9Kw5N",
    tool_name="eth_volatility",
    model_input_provider=price_data_provider,
    model_output_formatter=format_volatility,
    tool_description="Generates volatility measurement for ETH/USDT trading pair",
    inference_mode=og.InferenceMode.VANILLA,
)


# Example 2: Tool with input schema from the agent
class TokenInputSchema(BaseModel):
    token: str = Field(description="Token name (ethereum or bitcoin)")


def token_data_provider(**inputs):
    """Dynamic function that changes behavior based on agent input."""
    token = inputs.get("token")
    if token == "bitcoin":
        return {"price_series": [100001.1, 100013.2, 100149.2, 99998.1]}
    else:  # ethereum
        return {"price_series": [2010.1, 2012.3, 2020.1, 2019.2]}


# Create the tool with schema
token_tool = toolkit.create_run_model_tool(
    model_cid="QmZdSfHWGJyzBiB2K98egzu3MypPcv4R1ASypUxwZ1MFUG",
    tool_name="token_volatility",
    model_input_provider=token_data_provider,
    model_output_formatter=lambda x: format(float(x.model_output["std"].item()), ".3%"),
    tool_input_schema=TokenInputSchema,
    tool_description="Measures return volatility for a specified token",
)

# Add tools to the toolkit
toolkit.add_tool(volatility_tool)
toolkit.add_tool(token_tool)

2. workflow 결과를 읽는 tool 생성

Read workflow는 라이브 oracle 데이터와 함께 smart-contract에 저장된 model을 정기적으로 실행하는 예약된 추론입니다. 이에 대한 자세한 내용은 여기에서 확인할 수 있습니다. workflow smart contract의 결과를 읽는 tool을 생성할 수 있습니다:
# Create a tool to read from a workflow
forecast_tool = toolkit.create_read_workflow_tool(
    workflow_contract_address="0x58826c6dc9A608238d9d57a65bDd50EcaE27FE99",
    tool_name="ETH_Price_Forecast",
    tool_description="Reads latest forecast for ETH price from deployed workflow",
    output_formatter=lambda x: f"Price change forecast: {format(float(x.numbers['regression_output'].item()), '.2%')}",
)

# Add the tool to the toolkit
toolkit.add_tool(forecast_tool)

Tools

내장된 get_tools() method를 사용하여 OpenGradient toolkit 내에서 사용 가능한 tool 목록을 확인하세요.
tools = toolkit.get_tools()

# View tools
for tool in tools:
    print(tool)

agent 내에서 사용하기

다음은 LangChain agent와 함께 OpenGradient tool을 사용하는 방법입니다:
from langchain_openai import ChatOpenAI
from langchain.agents import create_agent


# Initialize LLM
model = ChatOpenAI(model="gpt-4o")

# Create tools from the toolkit
tools = toolkit.get_tools()

# Create agent
agent_executor = create_agent(model, tools)

# Example query for the agent
example_query = "What's the current volatility of ETH?"

# Execute the agent
events = agent_executor.stream(
    {"messages": [("user", example_query)]},
    stream_mode="values",
)
for event in events:
    event["messages"][-1].pretty_print()
다음은 모든 것을 함께 사용한 샘플 출력입니다:
================================ Human Message =================================

What's the current volatility of ETH?
================================== Ai Message ==================================
Tool Calls:
  eth_volatility (chatcmpl-tool-d66ab9ee8f2c40e5a2634d90c7aeb17d)
 Call ID: chatcmpl-tool-d66ab9ee8f2c40e5a2634d90c7aeb17d
  Args:
================================= Tool Message =================================
Name: eth_volatility

0.038%
================================== Ai Message ==================================

The current volatility of the ETH/USDT trading pair is 0.038%.

API reference

자세한 내용은 Github page를 참조하세요.

---

<Callout icon="pen-to-square" iconType="regular">
    [Edit the source of this page on GitHub.](https://github.com/langchain-ai/docs/edit/main/src/oss/python/integrations/tools/opengradient_toolkit.mdx)
</Callout>
<Tip icon="terminal" iconType="regular">
    [Connect these docs programmatically](/use-these-docs) to Claude, VSCode, and more via MCP for    real-time answers.
</Tip>
I