How to Create Plugins From Scratch in Coze: CoinGecko
2024-10-24 02:0:12 Author: hackernoon.com(查看原文) 阅读量:2 收藏

Ps. This tutorial is for the #AI Chatbot Design under the #AI-chatbot writing contest by Coze and HackerNoon!

In a perfect world, your application would be all things for everyone and would be able to deliver every function for every user—Unfortunately, no app is as powerful as that, so plugins are pretty important.

Plugins help bridge the gap between your application and the rest of the technological ecosystem by seamlessly extending your applications' functionality and capability. The best part is that plugins do this without inherently affecting your application source code. This tutorial will teach you how to create Plugins from scratch in Coze.

But first, let's try to understand what Plugins are.

What Is a Plug-in?

Plugins are software add-ons that enhance the capabilities of your application or programs without rewriting or changing the original code. Plugins often achieve this by integrating into your application’s codebase via an application programming interface (API) or any other integration points the core program offers. The process is usually seamless.

For you, the developer, plugins allow you to provide your users with more customization, data, and functionalities that will improve their experience without reinvesting the wheel. For the users, this means a better experience while on the app.

What Is Coze?

Coze is a platform that allows users to build, customize, and deploy AI bots using a low-code/no-code approach via social platforms. Thus, it is pretty much democratizing the entire AI chatbot process for everyone. The platform also comes with tools, plugins, multi-agent mode, and knowledge and memory features that help you customize and extend the functionality of their AI bots.

Coze Home page

Like other platforms, Coze offers various official Plugins tailored to diverse industries. These Plugins, such as GPT4V, CapCut, Doc Reader, and X, cater to specific needs across multiple categories, including news & reading, photography, lifestyle, science, education, and finance.

Additionally, users can submit custom Plugins. In this tutorial, you will build one for CoinGecko, a cryptocurrency data aggregator platform that allows users to track various coin stats, from crypto prices to market cap and trading volume.

Check out the official Coze user guide to learn more about Coze.

How Do You Build a CoinGecko plug-in in Coze?

In Coze, you can build Plugins in various ways. Some of these ways are:

  • Importing an existing API service.
  • Importing JSON or YAML files.
  • Via code parser.
  • Via the Coze IDE.
  • Adding tools to a plugin.

In this guide, you will explore the Coze IDE route to build the CoinGecko plugin. The Coze IDE is a web-based integrated development environment that allows you to build in Node.js or Python.

Prerequisites

To follow along with this tutorial, you will need the following:

  • A Coze account.
  • A CoinGecko developer account. A free account will do, as you need basic access to their API.

Building a Coze Plugin via the Coze IDE

Follow these steps to build your CoinGecko plug-in.

  1. Log in to Coze.com, and visit your team space within the workspace panel.

  2. Click the Plugins tab, and click Create Plug-in. Alternatively, you can visit the agent's Develop page and create Plugins.

  3. Give your Plugin a name, description, and an icon (optional).

  4. Select Cloud Plugin - Create in Coze IDE under the Plugin Tool creation method dropdown.

  5. Select Python as your language of choice under IDE runtime.

  6. Click Confirm to be redirected to the Plugin page to create your tool.

    Create a Coze plugin

    Building a Tool for Your Coze Plugin

    Next, you need to create your Plugin tool.

  7. Click Create tool in IDE on the Plugin page.

  8. Give your tool a name and description.

  9. Click Confirm to be redirected to the Coze IDE page, where you can code your tool.

Coding Your Coze Plugin

  1. Click the + icon on the Packages panel on your left to add dependencies. Here, you need to install the requests package so we can send HTTP.

    Installing any package there allows it to be used by just any tool in your plugin.

  2. Visit the CoinGecko developer's dashboard to get your CoinGecko API key.

  3. Within the Code tab, write your code based on the template provided by Coze. It is important that you don't delete or modify the handler method, as this would cause a failure. The base URL was gotten from the authentication docs.

from runtime import Args
import requests

API_KEY = "****" 
BASE_URL = "https://api.coingecko.com/api/v3" 

def get_coin_data(coin_id: str, currency: str = "usd", logger=None):
    endpoint = f"{BASE_URL}/coins/markets"
    params = {
        "vs_currency": currency,
        "ids": coin_id.lower(),  # Convert to lowercase
        "x_cg_demo_api_key": API_KEY
    }
    try:
        response = requests.get(endpoint, params=params)
        response.raise_for_status()  # Raise an exception for bad status codes
        data = response.json()
        if logger:
            logger.info(f"API Response: {data}")
        return data
    except requests.RequestException as e:
        if logger:
            logger.error(f"API Request failed: {str(e)}")
        return {"error": f"API request failed: {str(e)}"}

def handler(args: Args) -> dict:
    args.logger.info(f"Received args: {args}")
    args.logger.info(f"Type of args.input: {type(args.input)}")
    args.logger.info(f"Content of args.input: {args.input}")

    # Handle CustomNamespace object
    if hasattr(args.input, 'coin_id') and hasattr(args.input, 'currency'):
        coin_id = getattr(args.input, 'coin_id', 'bitcoin')
        currency = getattr(args.input, 'currency', 'usd')
    else:
        return {
            "message": f"Error: Invalid input format. Expected CustomNamespace with coin_id and currency attributes. Input: {args.input}",
            "data": None
        }

    args.logger.info(f"Processed input - coin_id: {coin_id}, currency: {currency}")

    try:
        coin_data = get_coin_data(coin_id, currency, args.logger)
        if "error" in coin_data:
            return {
                "message": f"Error: {coin_data['error']}",
                "data": None
            }
        else:
            # Check if we got any data
            if not coin_data:
                return {
                    "message": f"No data found for {coin_id}",
                    "data": None
                }
            
            # Assuming the API returns a list with one item for the specified coin
            coin_info = coin_data[0] if coin_data else {}
            return {
                "message": f"Successfully retrieved data for {coin_id}",
                "data": {
                    "name": coin_info.get("name"),
                    "symbol": coin_info.get("symbol"),
                    "current_price": coin_info.get("current_price"),
                    "market_cap": coin_info.get("market_cap"),
                    "price_change_24h": coin_info.get("price_change_24h")
                }
            }
    except Exception as e:
        args.logger.error(f"An error occurred: {str(e)}")
        return {
            "message": f"An error occurred while processing the request: {str(e)}",
            "data": None
        }

  1. Click the Metadata tab to add metadata for the tool.
  2. Click Edit and Add parameters to add these as input and output parameters to the CoinGecko API tool. These are your parameters:
    • Input parameters: coin_id (string): The ID of the cryptocurrency (e.g., "bitcoin", "ethereum").

    • Input parameters: currency (string): The target currency for market data (e.g., "usd", "eur")

    • Output parameters: message (string): A message indicating the request's status.

    • Output parameters: data (object): Within this data object, use these parameters.

    • Within your data output parameters: name (string): The name of the cryptocurrency.

    • Within your data output parameters: symbol (string): The symbol of the cryptocurrency.

    • Within your data output parameters: current_price (number): The current price in the specified currency.

    • Within your data output parameters: market_cap (number): The market capitalization in the specified currency.

    • Within your data output parameters: price_change_24h (number): The price change in the last 24 hours

      Metabase in Coze

Metadata allows your Coze tool to know what to expect and extract from the users and how to answer the users.

Testing and Publishing Your Coze Plugin

  1. Input your input parameter under the Test Code tab to test, and run your plugin.

  2. Click Run.

  3. View the Output Value to view the response of your tool.

  4. View the logs in the Console panel to see if it was successful or any error.

  5. Click Publish to publish your plugin if the test is successful.

  6. Tick No in the Privacy Collection Statement dialog box, as our plugin does not collect user data. However, if your plugin requires user data, tick Yes.

    Privacy Collection Statement in Coze

  7. Click Publish. Head over to the store and explore this CoinGecko plugin.

    What’s next?

    Plugins are effective ways to integrate and extend the capabilities of your applications without changing your source code. By leveraging Coze plugin features, you can build AI applications and extend their features by integrating with any of Coze's official plugins.

    Can't find the plugin you want? You can now effortlessly create a custom plugin with any API you choose. This makes enhancing your user engagement and extending your application’s features easy. Learn more about the tool by exploring their YouTube.

    If you have read this far, I appreciate it! You can connect with me on Twitter, LinkedIn, or iheifeanyi [at] gmail.com

    Please do drop a like or comment. Thanks! ❤️🚀🙏🏽


文章来源: https://hackernoon.com/how-to-create-plugins-from-scratch-in-coze-coingecko?source=rss
如有侵权请联系:admin#unsafe.sh