avatarLaxfed Paulacy

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

3239

Abstract

span> result.json()

get_huggingface_models_tool = StructuredTool.from_function(get_huggingface_models) models = get_huggingface_models_tool.run({<span class="hljs-string">"query_params"</span>: {<span class="hljs-string">"search"</span>: <span class="hljs-string">"gpt-j"</span>}}) print(models)</pre></div><p id="0b82">Behind the scenes, this infers the <code>args_schema</code> from the function’s signature. This is used to tell the agent that it can provide query parameters to search as well as a path parameter to call other child endpoints.</p><p id="6d21">If you want more control over the tool definition, you can subclass the <code>BaseTool</code> directly. For instance, maybe you want the API key to be loaded automatically from the environment variables. Here's an example of a custom structured tool subclass:</p><div id="d819"><pre><span class="hljs-keyword">from</span> typing <span class="hljs-keyword">import</span> <span class="hljs-type">Optional</span>, <span class="hljs-type">Type</span> <span class="hljs-keyword">import</span> aiohttp <span class="hljs-keyword">import</span> requests <span class="hljs-keyword">from</span> langchain.callbacks.manager <span class="hljs-keyword">import</span> ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) <span class="hljs-keyword">from</span> langchain.tools <span class="hljs-keyword">import</span> BaseTool <span class="hljs-keyword">from</span> pydantic <span class="hljs-keyword">import</span> BaseModel, BaseSettings, Field

<span class="hljs-keyword">class</span> <span class="hljs-title class_">GetHuggingFaceModelsToolSchema</span>(<span class="hljs-title class_ inherited__">BaseModel</span>): path: <span class="hljs-built_in">str</span> = Field(default=<span class="hljs-string">""</span>, description=<span class="hljs-string">"the api path"</span>) query_params: <span class="hljs-type">Optional</span>[<span class="hljs-built_in">dict</span>] = Field( default=<span class="hljs-literal">None</span>, description=<span class="hljs-string">"Optional search parameters"</span> )

<span class="hljs-keyword">class</span> <span class="hljs-title class_">GetHuggingFaceModelsTool</span>(BaseTool, BaseSettings): <span class="hljs-string">"""My custom tool."""</span>

name: <span class="hljs-built_in">str</span> = <span class="hljs-string">"get_huggingface_models"</span>
description: <span class="hljs-built_in">str</span> = <span class="hljs-string">"""Tool that calls GET on &lt;https://huggingface.co/models*&gt; apis. Valid params include "search":"search", "author":"author", "filter":"filter" and "sort":"sort"."""</span>
args_schema: <span class="hljs-type">Type</span>[GetHuggingFaceModelsToolSchema] = GetHuggingFaceModelsToolSchema
base_url: <span class="hljs-built_in">str</span> = <span class="hljs-string">"&lt;https://huggingface.co/api/models&gt;"</span>
api_key: <span class="hljs-built_in">str</span> = Field(..., env=<span class="hljs-string">"HUGGINGFACE_API_KEY"</span>)

<span class="hljs-meta"> @property</span> <span class="hljs-keyword">def</span> <span class="hljs-title function_">_headers</span>(<span class="hljs-params">self</span>) -> <span class="hljs-bu

Options

ilt_in">dict</span>: <span class="hljs-keyword">return</span> {<span class="hljs-string">"authorization"</span>: <span class="hljs-string">f"Bearer <span class="hljs-subst">{self.api_key}</span>"</span>}

<span class="hljs-keyword">def</span> <span class="hljs-title function_">_run</span>(<span class="hljs-params">
    self,
    path: <span class="hljs-built_in">str</span> = <span class="hljs-string">""</span>,
    query_params: <span class="hljs-type">Optional</span>[<span class="hljs-built_in">dict</span>] = <span class="hljs-literal">None</span>,
    run_manager: <span class="hljs-type">Optional</span>[CallbackManagerForToolRun] = <span class="hljs-literal">None</span>,
</span>) -&gt; <span class="hljs-built_in">dict</span>:
    <span class="hljs-string">"""Run the tool"""</span>
    result = requests.get(
        self.base_url + path, params=query_params, headers=self._headers
    )
    <span class="hljs-keyword">return</span> result.json()

<span class="hljs-keyword">async</span> <span class="hljs-keyword">def</span> <span class="hljs-title function_">_arun</span>(<span class="hljs-params">
    self,
    path: <span class="hljs-built_in">str</span> = <span class="hljs-string">""</span>,
    query_params: <span class="hljs-type">Optional</span>[<span class="hljs-built_in">dict</span>] = <span class="hljs-literal">None</span>,
    run_manager: <span class="hljs-type">Optional</span>[AsyncCallbackManagerForToolRun] = <span class="hljs-literal">None</span>,
</span>) -&gt; <span class="hljs-built_in">dict</span>:
    <span class="hljs-string">"""Run the tool asynchronously."""</span>

    <span class="hljs-keyword">async</span> <span class="hljs-keyword">with</span> aiohttp.ClientSession() <span class="hljs-keyword">as</span> session:
        <span class="hljs-keyword">async</span> <span class="hljs-keyword">with</span> session.get(
            self.base_url + path, params=query_params, headers=self._headers
        ) <span class="hljs-keyword">as</span> response:
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> response.json()

get_models_tool = GetHuggingFaceModelsTool() models = get_models_tool.run({<span class="hljs-string">"query_params"</span>: {<span class="hljs-string">"search"</span>: <span class="hljs-string">"gpt-j"</span>}}) <span class="hljs-built_in">print</span>(models)</pre></div><div id="f251" class="link-block"> <a href="https://readmedium.com/langchain-parallel-function-calling-extraction-for-structured-data-extraction-7df941ef45e8"> <div> <div> <h2>LANGCHAIN — Parallel Function Calling Extraction for Structured Data Extraction</h2> <div><h3>Technology offers us a unique opportunity, though rarely welcome, to practice patience. — Allan Lokos.</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*nu7ZXSdSXeo6aCLEJYoZpg.jpeg)"></div> </div> </div> </a> </div></article></body>

LANGCHAIN — Structured Tools

Digital design is like painting, except the paint never dries. — Neville Brody

Structured Tools are an exciting new feature in LangChain that enable more complex, multi-faceted interactions between language models and tools, making it easier to build innovative, adaptable, and powerful applications. In this article, we’ll explore what structured tools are, how to implement your own, and how to use them with the new StructuredChatAgent.

What is a “Structured Tool”?

A structured tool represents an action an agent can take. It wraps any function you provide to let an agent easily interface with it. A Structured Tool object is defined by its name, description, args_schema, and _run and _arun functions.

Let’s dive into an example of how to implement a structured tool. Suppose you wanted a tool to interact with Hugging Face models via the requests library. You can create a structured tool using the following code:

import requests
from langchain.tools.base import StructuredTool

API_KEY = "<MY-API-KEY>"

def get_huggingface_models(
    path: Optional[str] = None, query_params: Optional[dict] = None
) -> dict:
    """Tool that calls GET on <https://huggingface.co/models*> apis. Valid params include "search":"search", "author":"author", "filter":"filter" and "sort":"sort"."""
    base_url = "<https://huggingface.co/api/models>"
    headers = {"authorization": f"Bearer {API_KEY}"}
    result = requests.get(base_url + (path or ""), params=query_params, headers=headers)
    return result.json()

get_huggingface_models_tool = StructuredTool.from_function(get_huggingface_models)
models = get_huggingface_models_tool.run({"query_params": {"search": "gpt-j"}})
print(models)

Behind the scenes, this infers the args_schema from the function’s signature. This is used to tell the agent that it can provide query parameters to search as well as a path parameter to call other child endpoints.

If you want more control over the tool definition, you can subclass the BaseTool directly. For instance, maybe you want the API key to be loaded automatically from the environment variables. Here's an example of a custom structured tool subclass:

from typing import Optional, Type
import aiohttp
import requests
from langchain.callbacks.manager import (
    AsyncCallbackManagerForToolRun,
    CallbackManagerForToolRun,
)
from langchain.tools import BaseTool
from pydantic import BaseModel, BaseSettings, Field

class GetHuggingFaceModelsToolSchema(BaseModel):
    path: str = Field(default="", description="the api path")
    query_params: Optional[dict] = Field(
        default=None, description="Optional search parameters"
    )

class GetHuggingFaceModelsTool(BaseTool, BaseSettings):
    """My custom tool."""
    
    name: str = "get_huggingface_models"
    description: str = """Tool that calls GET on <https://huggingface.co/models*> apis. Valid params include "search":"search", "author":"author", "filter":"filter" and "sort":"sort"."""
    args_schema: Type[GetHuggingFaceModelsToolSchema] = GetHuggingFaceModelsToolSchema
    base_url: str = "<https://huggingface.co/api/models>"
    api_key: str = Field(..., env="HUGGINGFACE_API_KEY")

    @property
    def _headers(self) -> dict:
        return {"authorization": f"Bearer {self.api_key}"}

    def _run(
        self,
        path: str = "",
        query_params: Optional[dict] = None,
        run_manager: Optional[CallbackManagerForToolRun] = None,
    ) -> dict:
        """Run the tool"""
        result = requests.get(
            self.base_url + path, params=query_params, headers=self._headers
        )
        return result.json()

    async def _arun(
        self,
        path: str = "",
        query_params: Optional[dict] = None,
        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,
    ) -> dict:
        """Run the tool asynchronously."""

        async with aiohttp.ClientSession() as session:
            async with session.get(
                self.base_url + path, params=query_params, headers=self._headers
            ) as response:
                return await response.json()

get_models_tool = GetHuggingFaceModelsTool()
models = get_models_tool.run({"query_params": {"search": "gpt-j"}})
print(models)
Langchain
Structured
ChatGPT
Recommended from ReadMedium