반응형
블로그 이미지
개발자로서 현장에서 일하면서 새로 접하는 기술들이나 알게된 정보 등을 정리하기 위한 블로그입니다. 운 좋게 미국에서 큰 회사들의 프로젝트에서 컬설턴트로 일하고 있어서 새로운 기술들을 접할 기회가 많이 있습니다. 미국의 IT 프로젝트에서 사용되는 툴들에 대해 많은 분들과 정보를 공유하고 싶습니다.
솔웅

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함

카테고리

Chat GPT Plugin - Plugins in production

2023. 4. 4. 21:58 | Posted by 솔웅


반응형

Production - OpenAI API

 

OpenAI API

An API for accessing new AI models developed by OpenAI

platform.openai.com

 

 

Rate limits

Consider implementing rate limiting on the API endpoints you expose. While the current scale is limited, ChatGPT is widely used and you should expect a high volume of requests. You can monitor the number of requests and set limits accordingly.

 

노출하는 API 엔드포인트에서 rate limiting을 구현하는 것을 고려하십시오. 현재 규모는 제한되어 있지만 ChatGPT는 널리 사용되며 많은 양의 요청을 예상해야 합니다. 요청 수를 모니터링하고 그에 따라 제한을 설정할 수 있습니다.

 

Updating your plugin

After deploying your plugin to production, you might want to make changes to the ai-plugin.json manifest file. Currently, manifest files must be manually updated by going through the "Develop your own plugin" flow in the plugin store each time you make a change to the file.

 

플러그인을 프로덕션에 배포한 후 ai-plugin.json 매니페스트 파일을 변경할 수 있습니다. 현재 매니페스트 파일은 파일을 변경할 때마다 플러그인 스토어에서 "Develop your own plugin" flow 를  통해 수동으로 업데이트해야 합니다.

 

ChatGPT will automatically fetch the latest OpenAPI spec each time a request is made.

 

ChatGPT는 요청이 있을 때마다 최신 OpenAPI 사양을 자동으로 가져옵니다.

 

Plugin terms

In order to register a plugin, you must agree to the Plugin Terms.

 

플러그인을 등록하려면 Plugin Terms에 동의해야 합니다.

 

Domain verification and security

To ensure that plugins can only perform actions on resources that they control, OpenAI enforces requirements on the plugin's manifest and API specifications.

 

플러그인이 제어하는 리소스에서만 작업을 수행할 수 있도록 OpenAI는 플러그인의 매니페스트 및 API 사양에 대한 요구 사항을 적용합니다.

 

 

Defining the plugin's root domain

The manifest file defines information shown to the user (like logo and contact information) as well as a URL where the plugin's OpenAPI spec is hosted. When the manifest is fetched, the plugin's root domain is established following these rules:

 

매니페스트 파일은 사용자에게 표시되는 정보(예: 로고 및 연락처 정보)와 플러그인의 OpenAPI 사양이 호스팅되는 URL을 정의합니다. 매니페스트를 가져오면 다음 규칙에 따라 플러그인의 루트 도메인이 설정됩니다.

 

  • If the domain has www. as a subdomain, then the root domain will strip out www. from the domain that hosts the manifest.
  • Subdomain 으로서 도메인에 www. 가 있으면 루트 도메인은 매니페스트를 호스트하는 도메인으로부터 www.를 제거할 것입니다.
  • Otherwise, the root domain is the same as the domain that hosts the manifest.
  • 그렇지 않으면 루트 도메인은 매니페스트를 호스트하는 도메인과 같습니다.

Note on redirects: If there are any redirects in resolving the manifest, only child subdomain redirects are allowed. The only exception is following a redirect from a www subdomain to one without the www.

 

리디렉션에 대한 참고 사항: 매니페스트를 확인하는 데 리디렉션이 있는 경우 child subdomain 리디렉션만 허용됩니다. 유일한 예외는 www 하위 도메인에서 www가 없는 도메인으로 리디렉션하는 경우입니다.

 

Examples of what the root domain looks like:

 

루트 도메인의 예는 다음과 같습니다.

 

 

Manifest validation

Specific fields in the manifest itself must satisfy the following requirements:

 

매니페스트 자체의 특정 필드는 다음 요구 사항을 충족해야 합니다.

 

  • api.url - the URL provided to the OpenAPI spec must be hosted at the same level or a subdomain of the root domain.
  • api.url - OpenAPI 사양에 제공된 URL은 동일한 수준 또는 루트 도메인의 하위 도메인에서 호스팅되어야 합니다.
  • legal_info - The second-level domain of the URL provided must be the same as the second-level domain of the root domain.
  • legal_info - 제공된 URL의 2단계 도메인은 루트 도메인의 2단계 도메인과 동일해야 합니다.
  • contact_info - The second-level domain of the email address should be the same as the second-level domain of the root domain.
  • contact_info - 이메일 주소의 2차 도메인은 루트 도메인의 2차 도메인과 동일해야 합니다.

 

Resolving the API spec

The api.url field in the manifest provides a link to an OpenAPI spec that defines APIs that the plugin can call into. OpenAPI allows specifying multiple server base URLs. The following logic is used to select the server URL:

 

매니페스트의 api.url 필드는 플러그인이 호출할 수 있는 API를 정의하는 OpenAPI 사양에 대한 링크를 제공합니다. OpenAPI를 사용하면 여러 server base URLs을 지정할 수 있습니다. 다음 논리는 서버 URL을 선택하는 데 사용됩니다.

 

  • Iterate through the list of server URLs
  • 서버 URL 목록을 반복합니다.
  • Use the first server URL that is either an exact match of the root domain or a subdomain of the root domain
  • 루트 도메인 또는 루트 도메인의 하위 도메인과 정확히 일치하는 첫 번째 서버 URL을 사용하십시오.
  • If neither cases above apply, then default to the domain where the API spec is hosted. For example, if the spec is hosted on api.example.com, then api.example.com will be used as the base URL for the routes in the OpenAPI spec.
  • 위의 두 경우 모두 적용되지 않는 경우 API 사양이 호스팅되는 도메인으로 기본 설정됩니다. 예를 들어 사양이 api.example.com에서 호스팅되는 경우 api.example.com은 OpenAPI 사양의 경로에 대한 기본 URL로 사용됩니다.

Note: Please avoid using redirects for hosting the API spec and any API endpoints, as it is not guaranteed that redirects will always be followed.

 

참고: 리디렉션이 항상 뒤따른다는 보장이 없으므로 API 사양 및 API 엔드포인트를 호스팅하기 위해 리디렉션을 사용하지 마십시오.

 

Use TLS and HTTPS

All traffic with the plugin (e.g., fetching the ai-plugin.json file, the OpenAPI spec, API calls) must use TLS 1.2 or later on port 443 with a valid public certificate.

 

플러그인이 있는 모든 트래픽(예: ai-plugin.json 파일 가져오기, OpenAPI 사양, API 호출)은 유효한 공개 인증서가 있는 포트 443에서 TLS 1.2 이상을 사용해야 합니다.

 

IP egress ranges

ChatGPT will call your plugin from an IP address in the CIDR block 23.102.140.112/28. You may wish to explicitly allowlist these IP addresses.

 

ChatGPT는 CIDR 블록 23.102.140.112/28의 IP 주소에서 플러그인을 호출합니다. 이러한 IP 주소를 명시적으로 허용 목록에 추가할 수 있습니다.

 

Separately, OpenAI's web browsing plugin crawls websites from a different IP address block: 23.98.142.176/28.

 

이와 별도로 OpenAI의 웹 브라우징 플러그인은 다른 IP 주소 블록(23.98.142.176/28)에서 웹사이트를 크롤링합니다.

 

 

FAQ

How is plugin data used?

Plugins connect ChatGPT to external apps. If a user enables a plugin, ChatGPT may send parts of their conversation and their country or state to your plugin.

 

플러그인은 ChatGPT를 외부 앱에 연결합니다. 사용자가 플러그인을 활성화하면 ChatGPT는 대화의 일부와 국가 또는 주를 플러그인으로 보낼 수 있습니다.

 

What happens if a request to my API fails?

If an API request fails, the model might retry the request up to 10 times before letting the user know it cannot get a response from that plugin.

 

API 요청이 실패하면 모델은 해당 플러그인에서 응답을 받을 수 없음을 사용자에게 알리기 전에 요청을 최대 10번 재시도할 수 있습니다.

 

Can I invite people to try my plugin?

Yes, all unverified plugins can be installed by up to 15 users. At launch, only other developers with access will be able to install the plugin. We plan to expand access over time and will eventually roll out a process to submit your plugin for review before being made available to all users.

 

예, 확인되지 않은 모든 플러그인은 최대 15명의 사용자가 설치할 수 있습니다. 출시 시 액세스 권한이 있는 다른 개발자만 플러그인을 설치할 수 있습니다. 우리는 시간이 지남에 따라 액세스를 확장할 계획이며 궁극적으로 모든 사용자가 사용할 수 있게 되기 전에 검토를 위해 플러그인을 제출하는 프로세스를 출시할 것입니다.

 

 

반응형

Chat GPT Plugin - Example plugins

2023. 4. 4. 02:54 | Posted by 솔웅


반응형

Examples - OpenAI API

 

OpenAI API

An API for accessing new AI models developed by OpenAI

platform.openai.com

 

 

To get started building, we are making available a set of simple plugins that cover different authentication schemas and use cases. From our simple no authentication todo list plugin to the more powerful retrieval plugin, these examples provide a glimpse into what we hope to make possible with plugins.

 

building을 시작하기 위해 다양한 인증 스키마 및 사용 사례를 다루는 간단한 플러그인 세트를 제공하고 있습니다. 단순한 no authentication todo list  플러그인에서 더 강력한 검색 플러그인에 이르기까지 이 예제는 플러그인으로 가능하게 하고자 하는 것을 엿볼 수 있는 기회를 제공합니다.

 

During development, you can run the plugin locally on your computer or through a cloud development environment like GitHub Codespaces, Replit, or CodeSandbox.

 

개발 중에 플러그인을 컴퓨터에서 로컬로 실행하거나 GitHub Codespaces, Replit 또는 CodeSandbox와 같은 클라우드 개발 환경을 통해 실행할 수 있습니다.

 

 

Learn how to build a simple todo list plugin with no auth

 

To start, define an ai-plugin.json file with the following fields:

 

시작하려면 다음 필드를 사용하여 ai-plugin.json 파일을 정의합니다.

 

{
  "schema_version": "v1",
  "name_for_human": "TODO Plugin (no auth)",
  "name_for_model": "todo",
  "description_for_human": "Plugin for managing a TODO list, you can add, remove and view your TODOs.",
  "description_for_model": "Plugin for managing a TODO list, you can add, remove and view your TODOs.",
  "auth": {
    "type": "none"
  },
  "api": {
    "type": "openapi",
    "url": "PLUGIN_HOSTNAME/openapi.yaml",
    "is_user_authenticated": false
  },
  "logo_url": "PLUGIN_HOSTNAME/logo.png",
  "contact_email": "support@example.com",
  "legal_info_url": "https://example.com/legal"
}

 

Note the PLUGIN_HOSTNAME should be the actual hostname of your plugin server.

 

PLUGIN_HOSTNAME은 플러그인 서버의 실제 호스트 이름이어야 합니다.

 

Next, we can define the API endpoints to create, delete, and fetch todo list items for a specific user.

 

다음으로 특정 사용자에 대한 할 일 목록 항목을 생성, 삭제 및 가져오기 위해 API 끝점을 정의할 수 있습니다.

 

import json

import quart
import quart_cors
from quart import request

# Note: Setting CORS to allow chat.openapi.com is required for ChatGPT to access your plugin
app = quart_cors.cors(quart.Quart(__name__), allow_origin="https://chat.openai.com")

_TODOS = {}


@app.post("/todos/<string:username>")
async def add_todo(username):
    request = await quart.request.get_json(force=True)
    if username not in _TODOS:
        _TODOS[username] = []
    _TODOS[username].append(request["todo"])
    return quart.Response(response='OK', status=200)


@app.get("/todos/<string:username>")
async def get_todos(username):
    return quart.Response(response=json.dumps(_TODOS.get(username, [])), status=200)


@app.delete("/todos/<string:username>")
async def delete_todo(username):
    request = await quart.request.get_json(force=True)
    todo_idx = request["todo_idx"]
    if 0 <= todo_idx < len(_TODOS[username]):
        _TODOS[username].pop(todo_idx)
    return quart.Response(response='OK', status=200)


@app.get("/logo.png")
async def plugin_logo():
    filename = 'logo.png'
    return await quart.send_file(filename, mimetype='image/png')


@app.get("/.well-known/ai-plugin.json")
async def plugin_manifest():
    host = request.headers['Host']
    with open("ai-plugin.json") as f:
        text = f.read()
        # This is a trick we do to populate the PLUGIN_HOSTNAME constant in the manifest
        text = text.replace("PLUGIN_HOSTNAME", f"https://{host}")
        return quart.Response(text, mimetype="text/json")


@app.get("/openapi.yaml")
async def openapi_spec():
    host = request.headers['Host']
    with open("openapi.yaml") as f:
        text = f.read()
        # This is a trick we do to populate the PLUGIN_HOSTNAME constant in the OpenAPI spec
        text = text.replace("PLUGIN_HOSTNAME", f"https://{host}")
        return quart.Response(text, mimetype="text/yaml")


def main():
    app.run(debug=True, host="0.0.0.0", port=5002)


if __name__ == "__main__":
    main()

 

Last, we need to set up and define a OpenAPI specification to match the endpoints defined on our local or remote server. You do not need to expose the full functionality of your API via the specification and can instead choose to let ChatGPT have access to only certain functionality.

 

마지막으로 로컬 또는 원격 서버에 정의된 엔드포인트와 일치하도록 OpenAPI 사양을 설정하고 정의해야 합니다. 사양을 통해 API의 전체 기능을 노출할 필요는 없으며 대신 ChatGPT가 특정 기능에만 액세스하도록 선택할 수 있습니다.

 

There are also many tools that will automatically turn your server definition code into an OpenAPI specification so you don’t need to do it manually. In the case of the Python code above, the OpenAPI specification will look like:

 

서버 정의 코드를 OpenAPI 사양으로 자동 변환하여 수동으로 수행할 필요가 없도록 하는 많은 도구도 있습니다. 위 Python 코드의 경우 OpenAPI 사양은 다음과 같습니다.

 

openapi: 3.0.1
info:
  title: TODO Plugin
  description: A plugin that allows the user to create and manage a TODO list using ChatGPT. If you do not know the user's username, ask them first before making queries to the plugin. Otherwise, use the username "global".
  version: 'v1'
servers:
  - url: PLUGIN_HOSTNAME
paths:
  /todos/{username}:
    get:
      operationId: getTodos
      summary: Get the list of todos
      parameters:
      - in: path
        name: username
        schema:
            type: string
        required: true
        description: The name of the user.
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/getTodosResponse'
    post:
      operationId: addTodo
      summary: Add a todo to the list
      parameters:
      - in: path
        name: username
        schema:
            type: string
        required: true
        description: The name of the user.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/addTodoRequest'
      responses:
        "200":
          description: OK
    delete:
      operationId: deleteTodo
      summary: Delete a todo from the list
      parameters:
      - in: path
        name: username
        schema:
            type: string
        required: true
        description: The name of the user.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/deleteTodoRequest'
      responses:
        "200":
          description: OK

components:
  schemas:
    getTodosResponse:
      type: object
      properties:
        todos:
          type: array
          items:
            type: string
          description: The list of todos.
    addTodoRequest:
      type: object
      required:
      - todo
      properties:
        todo:
          type: string
          description: The todo to add to the list.
          required: true
    deleteTodoRequest:
      type: object
      required:
      - todo_idx
      properties:
        todo_idx:
          type: integer
          description: The index of the todo to delete.
          required: true

 

Learn how to build a simple todo list plugin with service level auth

 

To start, define an ai-plugin.json file with the following fields:

 

시작하려면 다음 필드를 사용하여 ai-plugin.json 파일을 정의합니다.

 

{
  "schema_version": "v1",
  "name_for_human": "TODO Plugin (service level auth)",
  "name_for_model": "todo",
  "description_for_human": "Plugin for managing a TODO list, you can add, remove and view your TODOs.",
  "description_for_model": "Plugin for managing a TODO list, you can add, remove and view your TODOs.",
  "auth": {
    "type": "service_http",
    "authorization_type": "bearer",
    "verification_tokens": {
      "openai": "758e9ef7984b415688972d749f8aa58e"
    }
  },
   "api": {
    "type": "openapi",
    "url": "https://example.com/openapi.yaml",
    "is_user_authenticated": false
  },
  "logo_url": "https://example.com/logo.png",
  "contact_email": "support@example.com",
  "legal_info_url": "https://example.com/legal"
}

 

Notice that the verification token is required for service level authentication plugins. The token is generated during the plugin installation process in the ChatGPT web UI.

 

서비스 수준 인증 플러그인에는 확인 토큰이 필요합니다. 토큰은 ChatGPT 웹 UI에서 플러그인 설치 프로세스 중에 생성됩니다.

 

Next, we can define the API endpoints to create, delete, and fetch todo list items for a specific user. The endpoints also check that the user is authenticated.

 

다음으로 특정 사용자에 대한 할 일 목록 항목을 생성, 삭제 및 가져오기 위해 API 끝점을 정의할 수 있습니다. 끝점은 또한 사용자가 인증되었는지 확인합니다.

 

import json

import quart
import quart_cors
from quart import request

# Note: Setting CORS to allow chat.openapi.com is required for ChatGPT to access your plugin
app = quart_cors.cors(quart.Quart(__name__), allow_origin="https://chat.openai.com")

_SERVICE_AUTH_KEY = "REPLACE_ME"
_TODOS = {}


def assert_auth_header(req):
    assert req.headers.get(
        "Authorization", None) == f"Bearer {_SERVICE_AUTH_KEY}"


@app.post("/todos/<string:username>")
async def add_todo(username):
    assert_auth_header(quart.request)
    request = await quart.request.get_json(force=True)
    if username not in _TODOS:
        _TODOS[username] = []
    _TODOS[username].append(request["todo"])
    return quart.Response(response='OK', status=200)


@app.get("/todos/<string:username>")
async def get_todos(username):
    assert_auth_header(quart.request)
    return quart.Response(response=json.dumps(_TODOS.get(username, [])), status=200)


@app.delete("/todos/<string:username>")
async def delete_todo(username):
    assert_auth_header(quart.request)
    request = await quart.request.get_json(force=True)
    todo_idx = request["todo_idx"]
    if 0 <= todo_idx < len(_TODOS[username]):
        _TODOS[username].pop(todo_idx)
    return quart.Response(response='OK', status=200)


@app.get("/logo.png")
async def plugin_logo():
    filename = 'logo.png'
    return await quart.send_file(filename, mimetype='image/png')


@app.get("/.well-known/ai-plugin.json")
async def plugin_manifest():
    host = request.headers['Host']
    with open("ai-plugin.json") as f:
        text = f.read()
        return quart.Response(text, mimetype="text/json")


@app.get("/openapi.yaml")
async def openapi_spec():
    host = request.headers['Host']
    with open("openapi.yaml") as f:
        text = f.read()
        return quart.Response(text, mimetype="text/yaml")


def main():
    app.run(debug=True, host="0.0.0.0", port=5002)


if __name__ == "__main__":
    main()

 

Last, we need to set up and define a OpenAPI specification to match the endpoints defined on our local or remote server. In general, the OpenAPI specification would look the same regardless of the authentication method. Using an automatic OpenAPI generator will reduce the chance of errors when creating your OpenAPI specification so it is worth exploring the options.

 

마지막으로 로컬 또는 원격 서버에 정의된 엔드포인트와 일치하도록 OpenAPI 사양을 설정하고 정의해야 합니다. 일반적으로 OpenAPI 사양은 인증 방법에 관계없이 동일하게 보입니다. 자동 OpenAPI 생성기를 사용하면 OpenAPI 사양을 생성할 때 오류 가능성이 줄어들므로 옵션을 탐색해 볼 가치가 있습니다.

 

openapi: 3.0.1
info:
  title: TODO Plugin
  description: A plugin that allows the user to create and manage a TODO list using ChatGPT. If you do not know the user's username, ask them first before making queries to the plugin. Otherwise, use the username "global".
  version: 'v1'
servers:
  - url: https://example.com
paths:
  /todos/{username}:
    get:
      operationId: getTodos
      summary: Get the list of todos
      parameters:
      - in: path
        name: username
        schema:
            type: string
        required: true
        description: The name of the user.
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/getTodosResponse'
    post:
      operationId: addTodo
      summary: Add a todo to the list
      parameters:
      - in: path
        name: username
        schema:
            type: string
        required: true
        description: The name of the user.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/addTodoRequest'
      responses:
        "200":
          description: OK
    delete:
      operationId: deleteTodo
      summary: Delete a todo from the list
      parameters:
      - in: path
        name: username
        schema:
            type: string
        required: true
        description: The name of the user.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/deleteTodoRequest'
      responses:
        "200":
          description: OK

components:
  schemas:
    getTodosResponse:
      type: object
      properties:
        todos:
          type: array
          items:
            type: string
          description: The list of todos.
    addTodoRequest:
      type: object
      required:
      - todo
      properties:
        todo:
          type: string
          description: The todo to add to the list.
          required: true
    deleteTodoRequest:
      type: object
      required:
      - todo_idx
      properties:
        todo_idx:
          type: integer
          description: The index of the todo to delete.
          required: true

 

Learn how to build a simple sports stats plugin

 

This plugin is an example of a simple sports stats API. Please keep in mind our domain policy and usage policies when considering what to build.

 

이 플러그인은 간단한 스포츠 통계 API의 예입니다. 무엇을 구축할지 고려할 때 도메인 정책 및 사용 정책을 염두에 두십시오.

 

To start, define an ai-plugin.json file with the following fields:

 

시작하려면 다음 필드를 사용하여 ai-plugin.json 파일을 정의합니다.

 

{
  "schema_version": "v1",
  "name_for_human": "Sport Stats",
  "name_for_model": "sportStats",
  "description_for_human": "Get current and historical stats for sport players and games.",
  "description_for_model": "Get current and historical stats for sport players and games. Always display results using markdown tables.",
  "auth": {
    "type": "none"
  },
  "api": {
    "type": "openapi",
    "url": "PLUGIN_HOSTNAME/openapi.yaml",
    "is_user_authenticated": false
  },
  "logo_url": "PLUGIN_HOSTNAME/logo.png",
  "contact_email": "support@example.com",
  "legal_info_url": "https://example.com/legal"
}

 

Note the PLUGIN_HOSTNAME should be the actual hostname of your plugin server.

 

PLUGIN_HOSTNAME은 플러그인 서버의 실제 호스트 이름이어야 합니다.

 

Next, we define a mock API for a simple sports service plugin.

 

다음으로 간단한 스포츠 서비스 플러그인을 위한 모의 API를 정의합니다.

 

import json
import requests
import urllib.parse

import quart
import quart_cors
from quart import request

# Note: Setting CORS to allow chat.openapi.com is required for ChatGPT to access your plugin
app = quart_cors.cors(quart.Quart(__name__), allow_origin="https://chat.openai.com")
HOST_URL = "https://example.com"

@app.get("/players")
async def get_players():
    query = request.args.get("query")
    res = requests.get(
        f"{HOST_URL}/api/v1/players?search={query}&page=0&per_page=100")
    body = res.json()
    return quart.Response(response=json.dumps(body), status=200)


@app.get("/teams")
async def get_teams():
    res = requests.get(
        "{HOST_URL}/api/v1/teams?page=0&per_page=100")
    body = res.json()
    return quart.Response(response=json.dumps(body), status=200)


@app.get("/games")
async def get_games():
    query_params = [("page", "0")]
    limit = request.args.get("limit")
    query_params.append(("per_page", limit or "100"))
    start_date = request.args.get("start_date")
    if start_date:
        query_params.append(("start_date", start_date))
    end_date = request.args.get("end_date")
    
    if end_date:
        query_params.append(("end_date", end_date))
    seasons = request.args.getlist("seasons")
    
    for season in seasons:
        query_params.append(("seasons[]", str(season)))
    team_ids = request.args.getlist("team_ids")
    
    for team_id in team_ids:
        query_params.append(("team_ids[]", str(team_id)))

    res = requests.get(
        f"{HOST_URL}/api/v1/games?{urllib.parse.urlencode(query_params)}")
    body = res.json()
    return quart.Response(response=json.dumps(body), status=200)


@app.get("/stats")
async def get_stats():
    query_params = [("page", "0")]
    limit = request.args.get("limit")
    query_params.append(("per_page", limit or "100"))
    start_date = request.args.get("start_date")
    if start_date:
        query_params.append(("start_date", start_date))
    end_date = request.args.get("end_date")
    
    if end_date:
        query_params.append(("end_date", end_date))
    player_ids = request.args.getlist("player_ids")
    
    for player_id in player_ids:
        query_params.append(("player_ids[]", str(player_id)))
    game_ids = request.args.getlist("game_ids")
    
    for game_id in game_ids:
        query_params.append(("game_ids[]", str(game_id)))
    res = requests.get(
        f"{HOST_URL}/api/v1/stats?{urllib.parse.urlencode(query_params)}")
    body = res.json()
    return quart.Response(response=json.dumps(body), status=200)


@app.get("/season_averages")
async def get_season_averages():
    query_params = []
    season = request.args.get("season")
    if season:
        query_params.append(("season", str(season)))
    player_ids = request.args.getlist("player_ids")
    
    for player_id in player_ids:
        query_params.append(("player_ids[]", str(player_id)))
    res = requests.get(
        f"{HOST_URL}/api/v1/season_averages?{urllib.parse.urlencode(query_params)}")
    body = res.json()
    return quart.Response(response=json.dumps(body), status=200)


@app.get("/logo.png")
async def plugin_logo():
    filename = 'logo.png'
    return await quart.send_file(filename, mimetype='image/png')


@app.get("/.well-known/ai-plugin.json")
async def plugin_manifest():
    host = request.headers['Host']
    with open("ai-plugin.json") as f:
        text = f.read()
        # This is a trick we do to populate the PLUGIN_HOSTNAME constant in the manifest
        text = text.replace("PLUGIN_HOSTNAME", f"https://{host}")
        return quart.Response(text, mimetype="text/json")


@app.get("/openapi.yaml")
async def openapi_spec():
    host = request.headers['Host']
    with open("openapi.yaml") as f:
        text = f.read()
        # This is a trick we do to populate the PLUGIN_HOSTNAME constant in the OpenAPI spec
        text = text.replace("PLUGIN_HOSTNAME", f"https://{host}")
        return quart.Response(text, mimetype="text/yaml")


def main():
    app.run(debug=True, host="0.0.0.0", port=5001)


if __name__ == "__main__":
    main()

 

Last, we define our OpenAPI specification:

 

마지막으로 OpenAPI 사양을 정의합니다.

 

openapi: 3.0.1
info:
  title: Sport Stats
  description: Get current and historical stats for sport players and games.
  version: 'v1'
servers:
  - url: PLUGIN_HOSTNAME
paths:
  /players:
    get:
      operationId: getPlayers
      summary: Retrieves all players from all seasons whose names match the query string.
      parameters:
      - in: query
        name: query
        schema:
            type: string
        description: Used to filter players based on their name. For example, ?query=davis will return players that have 'davis' in their first or last name.
      responses:
        "200":
          description: OK
  /teams:
    get:
      operationId: getTeams
      summary: Retrieves all teams for the current season.
      responses:
        "200":
          description: OK
  /games:
    get:
      operationId: getGames
      summary: Retrieves all games that match the filters specified by the args. Display results using markdown tables.
      parameters:
      - in: query
        name: limit
        schema:
            type: string
        description: The max number of results to return.
      - in: query
        name: seasons
        schema:
            type: array
            items:
              type: string
        description: Filter by seasons. Seasons are represented by the year they began. For example, 2018 represents season 2018-2019.
      - in: query
        name: team_ids
        schema:
            type: array
            items:
              type: string
        description: Filter by team ids. Team ids can be determined using the getTeams function.
      - in: query
        name: start_date
        schema:
            type: string
        description: A single date in 'YYYY-MM-DD' format. This is used to select games that occur on or after this date.
      - in: query
        name: end_date
        schema:
            type: string
        description: A single date in 'YYYY-MM-DD' format. This is used to select games that occur on or before this date.
      responses:
        "200":
          description: OK
  /stats:
    get:
      operationId: getStats
      summary: Retrieves stats that match the filters specified by the args. Display results using markdown tables.
      parameters:
      - in: query
        name: limit
        schema:
            type: string
        description: The max number of results to return.
      - in: query
        name: player_ids
        schema:
            type: array
            items:
              type: string
        description: Filter by player ids. Player ids can be determined using the getPlayers function.
      - in: query
        name: game_ids
        schema:
            type: array
            items:
              type: string
        description: Filter by game ids. Game ids can be determined using the getGames function.
      - in: query
        name: start_date
        schema:
            type: string
        description: A single date in 'YYYY-MM-DD' format. This is used to select games that occur on or after this date.
      - in: query
        name: end_date
        schema:
            type: string
        description: A single date in 'YYYY-MM-DD' format. This is used to select games that occur on or before this date.
      responses:
        "200":
          description: OK
  /season_averages:
    get:
      operationId: getSeasonAverages
      summary: Retrieves regular season averages for the given players. Display results using markdown tables.
      parameters:
      - in: query
        name: season
        schema:
            type: string
        description: Defaults to the current season. A season is represented by the year it began. For example, 2018 represents season 2018-2019.
      - in: query
        name: player_ids
        schema:
            type: array
            items:
              type: string
        description: Filter by player ids. Player ids can be determined using the getPlayers function.
      responses:
        "200":
          description: OK

 

Learn how to build a semantic search and retrieval plugin

 

The ChatGPT retrieval plugin is a more fully featured code example. The scope of the plugin is large, so we encourage you to read through the code to see what a more advanced plugin looks like.

 

ChatGPT 검색 플러그인은 더 완전한 기능을 갖춘 코드 예제입니다. 플러그인의 범위는 넓기 때문에 코드를 자세히 읽고 고급 플러그인이 어떻게 생겼는지 확인하는 것이 좋습니다.

 

The retrieval plugin includes:

검색 플러그인에는 다음이 포함됩니다.

  • Support for multiple vector databases providers
  • 여러 벡터 데이터베이스 공급자 지원
  • All 4 different authentication methods
  • 4가지 인증 방법 모두
  • Multiple different API features
  • 다양한 API 기능
반응형

Chat GPT Plugin - Authentication

2023. 4. 4. 00:17 | Posted by 솔웅


반응형

Authentication - OpenAI API

 

OpenAI API

An API for accessing new AI models developed by OpenAI

platform.openai.com

 

Plugin authentication

Plugins offer numerous authentication schemas to accommodate various use cases. To specify the authentication schema for your plugin, use the manifest file. Our plugin domain policy outlines our strategy for addressing domain security issues. For examples of available authentication options, refer to the examples section, which showcases all the different choices.

 

플러그인은 다양한 사용 사례를 수용하기 위해 수많은 인증 스키마를 제공합니다. 플러그인에 대한 인증 스키마를 지정하려면 매니페스트 파일을 사용하십시오. 플러그인 도메인 정책은 도메인 보안 문제를 해결하기 위한 전략을 간략하게 설명합니다. 사용 가능한 인증 옵션의 예는 다양한 선택 사항을 보여주는 examples section을 참조하십시오.

 

No authentication

We support no-auth flow for applications that do not require authentication, where a user is able to send requests directly to your API without any restrictions. This is particularly useful if you have an open API that you want to make available to everyone, as it allows traffic from sources other than just OpenAI plugin requests.

 

사용자가 제한 없이 API에 직접 요청을 보낼 수 있는 인증이 필요하지 않은 애플리케이션에 대해 무인증 흐름을 지원합니다. 이는 OpenAI 플러그인 요청 이외의 소스에서 트래픽을 허용하므로 모든 사람이 사용할 수 있게 하려는 개방형 API가 있는 경우에 특히 유용합니다.

 

"auth": {
  "type": "none"
},

 

 

Service level

If you want to specifically enable OpenAI plugins to work with your API, you can provide a client secret during the plugin installation flow. This means that all traffic from OpenAI plugins will be authenticated but not on a user level. This flow benefits from a simple end user experience but less control from an API perspective.

 

OpenAI 플러그인이 API와 함께 작동하도록 구체적으로 활성화하려는 경우 플러그인 설치 흐름 중에 클라이언트 암호를 제공할 수 있습니다. 이는 OpenAI 플러그인의 모든 트래픽이 인증되지만 사용자 수준에서는 인증되지 않음을 의미합니다. 이 흐름은 단순한 최종 사용자 경험의 이점이 있지만 API 관점에서 제어력이 떨어집니다.

 

  • To start, a developer pastes in their access token (global key)
  • 시작하려면 개발자가 액세스 토큰(글로벌 키)을 붙여넣습니다.
  • Then, they have to add the verification token to their manifest file
  • 그런 다음 매니페스트 파일에 확인 토큰을 추가해야 합니다.
  • We store an encrypted version of the token
  • 암호화된 버전의 토큰을 저장합니다.
  • Users don’t need to do anything when they install the plugin
  • 사용자는 플러그인을 설치할 때 아무 것도 할 필요가 없습니다.
  • Last, we pass it in the Authorization header when making requests to the plugin (“Authorization”: “[Bearer/Basic][user’s token]”)
  • 마지막으로 플러그인에 요청할 때 Authorization 헤더에 전달합니다("Authorization": "[Bearer/Basic][user's token]").
"auth": {
  "type": "service_http",
  "authorization_type": "bearer",
  "verification_tokens": {
    "openai": "cb7cdfb8a57e45bc8ad7dea5bc2f8324"
  }
},

 

User level

Just like how a user might already be using your API, we allow user level authentication through enabling end users to copy and paste their secret API key into the ChatGPT UI during plugin install. While we encrypt the secret key when we store it in our database, we do not recommend this approach given the poor user experience.

 

사용자가 이미 당신의 API를 사용하는 것처럼 최종 사용자가 플러그인 설치 중에 비밀 API 키를 복사하여 ChatGPT UI에 붙여넣을 수 있도록 하여 사용자 수준 인증을 허용합니다. 비밀 키를 데이터베이스에 저장할 때 암호화하지만 사용자 경험이 좋지 않은 경우에는 이 접근 방식을 권장하지 않습니다.

 

  • To start, a user pastes in their access token when installing the plugin
  • 시작하려면 사용자가 플러그인을 설치할 때 액세스 토큰을 붙여넣습니다.
  • We store an encrypted version of the token
  • 암호화된 버전의 토큰을 저장합니다.
  • We then pass it in the Authorization header when making requests to the plugin (“Authorization”: “[Bearer/Basic][user’s token]”)
  • 그런 다음 플러그인에 요청할 때 Authorization 헤더에 전달합니다("Authorization": "[Bearer/Basic][user's token]").
"auth": {
  "type": "user_http",
  "authorization_type": "bearer",
},

 

OAuth

The plugin protocol is compatible with OAuth. A simple example of the OAuth flow we are expecting in the manifest looks like the following:

 

플러그인 프로토콜은 OAuth와 호환됩니다. 매니페스트에서 예상되는 OAuth 흐름의 간단한 예는 다음과 같습니다.

 

  • To start, a developer pastes in their OAuth client id and client secret
  • 시작하려면 개발자가 OAuth 클라이언트 ID와 클라이언트 비밀번호를 붙여넣습니다. 
    • Then they have to add the verification token to their manifest file
    • 그런 다음 매니페스트 파일에 확인 토큰을 추가해야 합니다.
  • We store an encrypted version of the client secret
  • 클라이언트 시크릿의 암호화된 버전을 저장합니다.
  • Users log in through the plugin’s website when they install the plugin
  • 사용자는 플러그인을 설치할 때 플러그인 웹 사이트를 통해 로그인합니다. 
    • That gives us an OAuth access token (and optionally a refresh token) for the user, which we store encrypted
    • 그러면 사용자에 대한 OAuth 액세스 토큰(및 선택적으로 새로 고침 토큰)이 제공되며 암호화되어 저장됩니다.
  • Last, we pass that user’s token in the Authorization header when making requests to the plugin (“Authorization”: “[Bearer/Basic][user’s token]”)
  • 마지막으로 플러그인에 요청을 할 때 Authorization 헤더에 해당 사용자의 토큰을 전달합니다("Authorization": "[Bearer/Basic][user's token]").
"auth": {
  "type": "oauth",
  "client_url": "https://my_server.com/authorize",
  "scope": "",
  "authorization_url": "https://my_server.com/token",
  "authorization_content_type": "application/json",
  "verification_tokens": {
    "openai": "abc123456"
  }
},

 

 

To better understand the URL structure for OAuth, here is a short description of the fields:

OAuth의 URL 구조를 더 잘 이해할 수 있도록 다음은 필드에 대한 간단한 설명입니다.

  • When you set up your plugin with ChatGPT, you will be asked to provide your OAuth client_id and client_secret
  • ChatGPT로 플러그인을 설정할 때 OAuth client_id 및 client_secret을 제공하라는 메시지가 표시됩니다.
  • When a user logs into the plugin, ChatGPT will direct the user’s browser to "[client_url]?response_type=code&client_id=[client_id]&scope=[scope]&redirect_uri=https%3A%2F%2Fchat.openai.com%2Faip%2F[plugin_id]%2Foauth%2Fcallback"
  • 사용자가 플러그인에 로그인 할 때 챗GPT는 사용자의 브라우저를 이 페이지로 이동 시킬 겁니다. -> [client_url]?response_type=code&client_id=[client_id]&scope=[scope]&redirect_uri=https%3A%2F%2Fchat.openai.com%2Faip%2F[plugin_id]%2Foauth%2Fcallback
  • After your plugin redirects back to the given redirect_uri, ChatGPT will complete the OAuth flow by making a POST request to authorization_url with content type authorization_content_type and parameters { “grant_type”: “authorization_code”, “client_id”: [client_id], “client_secret”: [client_secret], “code”: [the code that was returned with the redirect], “redirect_uri”: [the same redirect uri as before] }
  • 플로그인이 주어진 redirect_uri 로 다시 redirection 된 후 챗GPT는 콘텐츠 요형  authorization_content_type 콘텐츠 유형 과 기타 파라미터들과 함께 authorization_url로 POST request를 만듦으로서 OAuth 흐름을 완료 하게 될 겁니다. 이때 사용되는 파라미터들은 다음과 같습니다. - authorization_content_type and parameters { “grant_type”: “authorization_code”, “client_id”: [client_id], “client_secret”: [client_secret], “code”: [the code that was returned with the redirect], “redirect_uri”: [the same redirect uri as before] }
반응형

Chat GPT Plugin - Getting started

2023. 3. 27. 22:17 | Posted by 솔웅


반응형

Getting Started - OpenAI API

 

OpenAI API

An API for accessing new AI models developed by OpenAI

platform.openai.com

 

Creating a plugin takes three steps:

플러그인 생성에는 세 단계가 필요합니다.

  • Build an API
  • API 빌드
  • Document the API in the OpenAPI yaml or JSON format
  • OpenAPI yaml 또는 JSON 형식으로 API 문서화
  • Create a JSON manifest file that will define relevant metadata for the plugin
  • 플러그인에 대한 관련 메타데이터를 정의할 JSON 매니페스트 파일을 생성합니다.

The focus of the rest of this section will be creating a to-do list plugin by defining the OpenAPI specification along with the manifest file.

이 섹션의 나머지 부분에서는 매니페스트 파일과 함께 OpenAPI 사양을 정의하여 to-do list 플러그인을 만드는 데 초점을 맞춥니다.

 

 

Plugin manifest

Every plugin requires a ai-plugin.json file, which needs to be hosted on the API’s domain.

모든 플러그인에는 API 도메인에서 호스팅되어야 하는 ai-plugin.json 파일이 필요합니다. 

 

For example, a company called example.com would make the plugin JSON file accessible via an https://example.com domain since that is where their API is hosted.

예를 들어 example.com이라는 회사는 API가 호스팅되는 https://example.com 도메인을 통해 플러그인 JSON 파일에 액세스할 수 있도록 합니다.

 

When you install the plugin via the ChatGPT UI, on the backend we look for a file located at /.well-known/ai-plugin.json.

ChatGPT UI를 통해 플러그인을 설치하면 백엔드에서 /.well-known/ai-plugin.json에 있는 파일을 찾습니다. 

 

The /.well-known folder is required and must exist on your domain in order for ChatGPT to connect with your plugin.

/.well-known 폴더가 필요하며 ChatGPT가 플러그인과 연결하려면 도메인에 있어야 합니다.

 

If there is no file found, the plugin cannot be installed. For local development, you can use HTTP but if you are pointing to a remote server, HTTPS is required.

파일이 없으면 플러그인을 설치할 수 없습니다. 로컬 개발의 경우 HTTP를 사용할 수 있지만 원격 서버를 가리키는 경우 HTTPS가 필요합니다.

 

The minimal definition of the required ai-plugin.json file will look like the following:

필요한 ai-plugin.json 파일의 최소 정의는 다음과 같습니다.

 

{
  "schema_version": "v1",
  "name_for_human": "TODO Plugin",
  "name_for_model": "todo",
  "description_for_human": "Plugin for managing a TODO list. You can add, remove and view your TODOs.",
  "description_for_model": "Plugin for managing a TODO list. You can add, remove and view your TODOs.",
  "auth": {
    "type": "none"
  },
  "api": {
    "type": "openapi",
    "url": "http://localhost:3333/openapi.yaml",
    "is_user_authenticated": false
  },
  "logo_url": "http://localhost:3333/logo.png",
  "contact_email": "support@example.com",
  "legal_info_url": "http://www.example.com/legal"
}

 

If you want to see all of the possible options for the plugin file, you can refer to the definition below.

플러그인 파일에 대해 가능한 모든 옵션을 보려면 아래 정의를 참조하십시오.

 

FIELD                      TYPE                   DESCRIPTION / OPTIONS

schema_version String Manifest schema version
name_for_model String Name the model will used to target the plugin
name_for_human String Human-readable name, such as the full company name
description_for_model String Description better tailored to the model, such as token context length considerations or keyword usage for improved plugin prompting.
description_for_human String Human-readable description of the plugin
auth ManifestAuth Authentication schema
api Object API specification
logo_url String URL used to fetch the plugin's logo
contact_email String Email contact for safety/moderation reachout, support, and deactivation
legal_info_url String Redirect URL for users to view plugin information
HttpAuthorizationType HttpAuthorizationType "bearer" or "basic"
ManifestAuthType ManifestAuthType "none", "user_http", "service_http", or "oauth"
interface BaseManifestAuth BaseManifestAuth type: ManifestAuthType; instructions: string;
ManifestNoAuth ManifestNoAuth No authentication required: BaseManifestAuth & { type: 'none', }
ManifestAuth ManifestAuth ManifestNoAuth, ManifestServiceHttpAuth, ManifestUserHttpAuth, ManifestOAuthAuth

 

The following are examples with different authentication methods:

다음은 인증 방법이 다른 예입니다.

 

# App-level API keys
type ManifestServiceHttpAuth  = BaseManifestAuth & {
  type: 'service_http';
  authorization_type: HttpAuthorizationType;
  verification_tokens: {
    [service: string]?: string;
  };
}

# User-level HTTP authentication
type ManifestUserHttpAuth  = BaseManifestAuth & {
  type: 'user_http';
  authorization_type: HttpAuthorizationType;
}

type ManifestOAuthAuth  = BaseManifestAuth & {
  type: 'oauth';

  # OAuth URL where a user is directed to for the OAuth authentication flow to begin.
  client_url: string;

  # OAuth scopes required to accomplish operations on the user's behalf.
  scope: string;

  # Endpoint used to exchange OAuth code with access token.
  authorization_url: string;

  # When exchanging OAuth code with access token, the expected header 'content-type'. For example: 'content-type: application/json'
  authorization_content_type: string;

  # When registering the OAuth client ID and secrets, the plugin service will surface a unique token. 
  verification_tokens: {
    [service: string]?: string;
  };
}

 

There are also some limits to the length of certain field in the manifest file that are subject to change over time:

시간이 지나면서 변경될 수 있는 매니페스트 파일의 특정 필드 길이에도 몇 가지 제한이 있습니다.

  • 50 character max forname_for_human
  • name_for_human에 대해 최대 50자
  • 50 character max for name_for_model
  • name_for_model은 최대 50자
  • 120 character max for description_for_human
  • description_for_human은 최대 120자
  • 8000 character max just for description_for_model (will decrease over time)
  • description_for_model의 경우 최대 8000자(시간이 지남에 따라 감소)

Separately, we also have a 100k character limit (will decrease over time) on the API response body length which is also subject to change.

이와는 별도로 API 응답 본문 길이에 대한 100,000자 제한(시간이 지남에 따라 줄어듦)도 변경될 수 있습니다.

 

OpenAPI definition

 

The next step is to build the OpenAPI specification to document the API.

다음 단계는 OpenAPI 사양을 빌드하여 API를 문서화하는 것입니다.

 

The model in ChatGPT does not know anything about your API other than what is defined in the OpenAPI specification and manifest file.

ChatGPT의 모델은 OpenAPI 사양 및 매니페스트 파일에 정의된 것 외에는 API에 대해 아무것도 모릅니다.

 

This means that if you have an extensive API, you need not expose all functionality to the model and can choose specific endpoints.

즉, 광범위한 API가 있는 경우 모든 기능을 모델에 노출할 필요가 없으며 특정 엔드포인트를 선택할 수 있습니다.

 

For example, if you had a social media API, you might want to have the model access content from the site through a GET request but prevent the model from being able to comment on users posts in order to reduce the chance of spam.

예를 들어 소셜 미디어 API가 있는 경우 모델이 GET 요청을 통해 사이트의 콘텐츠에 액세스하도록 할 수 있지만 스팸 가능성을 줄이기 위해 모델이 사용자 게시물에 댓글을 달 수 없도록 할 수 있습니다.

 

The OpenAPI specification is the wrapper that sits on top of your API. A basic OpenAPI specification will look like the following:

OpenAPI 사양은 API 위에 있는 래퍼입니다. 기본 OpenAPI 사양은 다음과 같습니다.

 

openapi: 3.0.1
info:
  title: TODO Plugin
  description: A plugin that allows the user to create and manage a TODO list using ChatGPT.
  version: 'v1'
servers:
  - url: http://localhost:3333
paths:
  /todos:
    get:
      operationId: getTodos
      summary: Get the list of todos
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/getTodosResponse'
components:
  schemas:
    getTodosResponse:
      type: object
      properties:
        todos:
          type: array
          items:
            type: string
          description: The list of todos.

 

We start by defining the specification version, the title, description, and version number.

먼저 사양 버전, 제목, 설명 및 버전 번호를 정의합니다.

 

When a query is run in ChatGPT, it will look at the description that is defined in the info section to determine if the plugin is relevant for the user query.

ChatGPT에서 쿼리가 실행되면 정보 섹션에 정의된 설명을 보고 플러그인이 사용자 쿼리와 관련이 있는지 확인합니다.

 

You can read more about prompting in the writing descriptions section.

writing descriptions  섹션에서 프롬프트에 대한 자세한 내용을 읽을 수 있습니다.

 

Keep in mind the following limits in your OpenAPI specification, which are subject to change:

변경될 수 있는 OpenAPI 사양의 다음 제한에 유의하세요.

  • 200 characters max for each API endpoint description/summary field in API specification
  • API 사양의 API 엔드포인트 설명/요약 필드당 최대 200자
  • 200 characters max for each API param description field in API specification
  • API 사양의 각 API 매개변수 설명 필드에 대해 최대 200자

Since we are running this example locally, we want to set the server to point to your local host URL. The rest of the OpenAPI specification follows the traditional OpenAPI format, you can learn more about OpenAPI formatting through various online resources. There are also many tools that auto generate OpenAPI specifications based on your underlying API code.

 

이 예제를 로컬에서 실행하고 있으므로 로컬 호스트 URL을 가리키도록 서버를 설정하려고 합니다. 나머지 OpenAPI 사양은 기존 OpenAPI 형식을 따르므로 다양한 온라인 리소스를 통해 OpenAPI 형식에 대해 자세히 알아볼 수 있습니다. 기본 API 코드를 기반으로 OpenAPI 사양을 자동으로 생성하는 많은 도구도 있습니다.

 

Running a plugin

Once you have created an API, manifest file, and OpenAPI specification for your API, you are now ready to connect the plugin via the ChatGPT UI. There are two different places your plugin might be running, either locally in a development environment or on a remote server.

 

API, 매니페스트 파일 및 API용 OpenAPI 사양을 생성했으면 이제 ChatGPT UI를 통해 플러그인을 연결할 준비가 된 것입니다. 플러그인은 개발 환경의 로컬 또는 원격 서버의 두 가지 다른 위치에서 실행될 수 있습니다.

 

If you have a local version of your API running, you can point the plugin interface to that local setup. To connect the plugin with ChatGPT, you can navigate to the plugin store and then select “Install an unverified plugin”.

 

실행 중인 API의 로컬 버전이 있는 경우 플러그인 인터페이스가 해당 로컬 설정을 가리킬 수 있습니다. 플러그인을 ChatGPT와 연결하려면 플러그인 스토어로 이동한 다음 "확인되지 않은 플러그인 설치"를 선택하면 됩니다.

 

If the plugin is running on a remote server, you will need to first select “Develop your own plugin” and then “Install an unverified plugin”.

 

플러그인이 원격 서버에서 실행 중인 경우 먼저 "자체 플러그인 개발"을 선택한 다음 "확인되지 않은 플러그인 설치"를 선택해야 합니다.

 

You can simply add the plugin manifest file to the ./well-known path and start testing your API.

 

플러그인 매니페스트 파일을 ./well-known 경로에 추가하고 API 테스트를 시작할 수 있습니다.

 

However, for subsequent changes to your manifest file, you will have to deploy the new changes to your public site which might take a long time. In that case, we suggest setting up a local server to act as a proxy for your API. This allows you to quickly prototype changes to your OpenAPI spec and manifest file.

 

이후에 매니페스트 파일을 변경하려면 새 변경 사항을 공개 사이트에 배포해야 하며 시간이 오래 걸릴 수 있습니다. 이 경우 API의 프록시 역할을 하도록 로컬 서버를 설정하는 것이 좋습니다. 이를 통해 OpenAPI 사양 및 매니페스트 파일에 대한 변경 사항의 프로토타입을 신속하게 만들 수 있습니다.

 

Setup a local proxy of your public API

 

The following Python code is an example of how you can set up a simple proxy of your public facing API.

 

다음 Python 코드는 공용 API의 간단한 프록시를 설정하는 방법의 예입니다.

 

import requests
import os

import yaml
from flask import Flask, jsonify, Response, request, send_from_directory
from flask_cors import CORS

app = Flask(__name__)

PORT = 3333
CORS(app, origins=[f"http://localhost:{PORT}", "https://chat.openai.com"])

api_url = 'https://example'


@app.route('/.well-known/ai-plugin.json')
def serve_manifest():
    return send_from_directory(os.path.dirname(__file__), 'ai-plugin.json')


@app.route('/openapi.yaml')
def serve_openapi_yaml():
    with open(os.path.join(os.path.dirname(__file__), 'openapi.yaml'), 'r') as f:
        yaml_data = f.read()
    yaml_data = yaml.load(yaml_data, Loader=yaml.FullLoader)
    return jsonify(yaml_data)


@app.route('/openapi.json')
def serve_openapi_json():
    return send_from_directory(os.path.dirname(__file__), 'openapi.json')


@app.route('/<path:path>', methods=['GET', 'POST'])
def wrapper(path):

    headers = {
    'Content-Type': 'application/json',
    }

    url = f'{api_url}/{path}'
    print(f'Forwarding call: {request.method} {path} -> {url}')

    if request.method == 'GET':
        response = requests.get(url, headers=headers, params=request.args)
    elif request.method == 'POST':
        print(request.headers)
        response = requests.post(url, headers=headers, params=request.args, json=request.json)
    else:
        raise NotImplementedError(f'Method {request.method} not implemented in wrapper for {path=}')
    return response.content


if __name__ == '__main__':
    app.run(port=PORT)

 

Writing descriptions

 

When a user makes a query that might be a potential request that goes to a plugin, the model looks through the descriptions of the endpoints in the OpenAPI specification along with the description_for_model in the manifest file. Just like with prompting other language models, you will want to test out multiple prompts and descriptions to see what works best.

 

사용자가 플러그인으로 이동하는 잠재적인 요청일 수 있는 쿼리를 만들면 모델은 매니페스트 파일의 description_for_model과 함께 OpenAPI 사양의 엔드포인트 설명을 살펴봅니다. 다른 언어 모델 프롬프트와 마찬가지로 여러 프롬프트와 설명을 테스트하여 무엇이 가장 잘 작동하는지 확인하고 싶을 것입니다.

 

The OpenAPI spec itself is a great place to give the model information about the diverse details of your API – what functions are available, with what parameters, etc. Besides using expressive, informative names for each field, the spec can also contain “description” fields for every attribute. These can be used to provide natural language descriptions of what a function does or what information a query field expects, for example. The model will be able to see these, and they will guide it in using the API. If a field is restricted to only certain values, you can also provide an “enum” with descriptive category names.

 

OpenAPI 사양 자체는 API의 다양한 세부 정보(사용 가능한 기능, 매개변수 등)에 대한 정보를 모델에 제공할 수 있는 좋은 장소입니다. 각 필드에 대해 표현적이고 유익한 이름을 사용하는 것 외에도 사양에는 "설명"도 포함될 수 있습니다. 모든 속성에 대한 필드. 예를 들어 함수가 수행하는 작업 또는 쿼리 필드에 필요한 정보에 대한 자연어 설명을 제공하는 데 사용할 수 있습니다. 모델은 이를 볼 수 있으며 API를 사용하도록 안내합니다. 필드가 특정 값으로만 제한되는 경우 설명 범주 이름과 함께 "enum"을 제공할 수도 있습니다.

 

The “description_for_model” attribute gives you the freedom to instruct the model on how to use your plugin generally. Overall, the language model behind ChatGPT is highly capable of understanding natural language and following instructions. Therefore, this is a good place to put in general instructions on what your plugin does and how the model should use it properly. Use natural language, preferably in a concise yet descriptive and objective tone. You can look at some of the examples to have an idea of what this should look like. We suggest starting the description_for_model with “Plugin for …” and then enumerating all of the functionality that your API provides.

 

"description_for_model" 속성은 일반적으로 플러그인을 사용하는 방법에 대해 모델에 지시할 수 있는 자유를 제공합니다. 전반적으로 ChatGPT의 언어 모델은 자연어를 이해하고 지침을 따를 수 있는 능력이 뛰어납니다. 따라서 플러그인이 수행하는 작업과 모델이 플러그인을 올바르게 사용하는 방법에 대한 일반적인 지침을 입력하기에 좋은 곳입니다. 간결하면서도 설명적이고 객관적인 어조로 자연어를 사용하는 것이 좋습니다. 몇 가지 예를 보면 이것이 어떤 모습이어야 하는지 알 수 있습니다. “Plugin for …”로 description_for_model을 시작한 다음 API가 제공하는 모든 기능을 열거하는 것이 좋습니다.

 

Best practices

Here are some best practices to follow when writing your description_for_model and descriptions in your OpenAPI specification, as well as when designing your API responses:

 

다음은 OpenAPI 사양에 description_for_model 및 설명을 작성할 때와 API 응답을 디자인할 때 따라야 할 몇 가지 모범 사례입니다.

 

  1. Your descriptions should not attempt to control the mood, personality, or exact responses of ChatGPT. ChatGPT is designed to write appropriate responses to plugins.

    귀하의 설명은 기분, 성격 또는 ChatGPT의 정확한 응답을 제어하려고 시도해서는 안 됩니다. ChatGPT는 플러그인에 적절한 응답을 작성하도록 설계되었습니다.

    나쁜 예
    When the user asks to see their todo list, always respond with "I was able to find your todo list! You have [x] todos: [list the todos here]. I can add more todos if you'd like!"

    좋은 예
    [no instructions needed for this]
  2. Your descriptions should not encourage ChatGPT to use the plugin when the user hasn’t asked for your plugin’s particular category of service.

    설명은 사용자가 플러그인의 특정 서비스 범주를 요청하지 않은 경우에도 ChatGPT가 플러그인을 사용하도록 권장해서는 안 됩니다.

    나쁜 예
    Whenever the user mentions any type of task or plan, ask if they would like to use the TODOs plugin to add something to their todo list.

    좋은 예
  3. The TODO list can add, remove and view the user's TODOs.
  4. Your descriptions should not prescribe specific triggers for ChatGPT to use the plugin. ChatGPT is designed to use your plugin automatically when appropriate.

    귀하의 설명은 ChatGPT가 플러그인을 사용하기 위한 특정 트리거를 규정해서는 안 됩니다. ChatGPT는 필요할 때 플러그인을 자동으로 사용하도록 설계되었습니다.

    나쁜 예
    When the user mentions a task, respond with "Would you like me to add this to your TODO list? Say 'yes' to continue."

    좋은 예
  5. [no instructions needed for this]
  6. Plugin API responses should return raw data instead of natural language responses unless it’s necessary. ChatGPT will provide its own natural language response using the returned data.

    플러그인 API 응답은 필요한 경우가 아니면 자연어 응답 대신 원시 데이터를 반환해야 합니다. ChatGPT는 반환된 데이터를 사용하여 자체 자연어 응답을 제공합니다.

    나쁜 예
    I was able to find your todo list! You have 2 todos: get groceries and walk the dog. I can add more todos if you'd like!

  7. 좋은 예
    { "todos": [ "get groceries", "walk the dog" ] }

Debugging

By default, the chat will not show plugin calls and other information that is not surfaced to the user. In order to get a more complete picture of how the model is interacting with your plugin, you can see the request and response by clicking the down arrow on the plugin name after interacting with the plugin.

 

기본적으로 채팅에는 사용자에게 표시되지 않는 플러그인 호출 및 기타 정보가 표시되지 않습니다. 모델이 플러그인과 상호 작용하는 방식을 보다 완벽하게 파악하기 위해 플러그인과 상호 작용한 후 플러그인 이름에서 아래쪽 화살표를 클릭하여 요청 및 응답을 볼 수 있습니다.

 

A model call to the plugin will usually consist of a message from the model (“Assistant”) containing JSON-like parameters which are sent to the plugin, followed by a response from the plugin (“Tool”), and finally a message from the model utilizing the information returned by the plugin.

 

플러그인에 대한 모델 호출은 일반적으로 플러그인으로 전송되는 JSON과 같은 매개변수를 포함하는 모델("Assistant")의 메시지, 플러그인("Tool")의 응답, 마지막으로 플러그인이 반환한 정보를 활용하는 모델입니다.

 

In some cases, like during plugin installation, errors might be surfaced in the browsers javascript console.

 

플러그인 설치와 같은 경우에 브라우저의 javascript 콘솔에 오류가 표시될 수 있습니다.

 

 

 

반응형

OpenAI API - ChatGPT plugins

2023. 3. 25. 23:24 | Posted by 솔웅


반응형

https://openai.com/blog/chatgpt-plugins

 

ChatGPT plugins

We’ve implemented initial support for plugins in ChatGPT. Plugins are tools designed specifically for language models with safety as a core principle, and help ChatGPT access up-to-date information, run computations, or use third-party services.

openai.com

 

 

 

In line with our iterative deployment philosophy, we are gradually rolling out plugins in ChatGPT so we can study their real-world use, impact, and safety and alignment challenges—all of which we’ll have to get right in order to achieve our mission.

 

우리의 반복적인 배포(iterative deployment) 철학에 따라 우리는 ChatGPT에서 플러그인을 점진적으로 출시하여 실제 사용, 영향, 안전 및 alignment 문제를 연구할 수 있습니다. 이러한 일들을 통해서 우리의 미션을 달성하기 위한 옳은 방향으로 가게 될 것입니다.

 

Users have been asking for plugins since we launched ChatGPT (and many developers are experimenting with similar ideas) because they unlock a vast range of possible use cases. We’re starting with a small set of users and are planning to gradually roll out larger-scale access as we learn more (for plugin developers, ChatGPT users, and after an alpha period, API users who would like to integrate plugins into their products). We’re excited to build a community shaping the future of the human–AI interaction paradigm.

 

사용자는 ChatGPT를 출시한 이후로 플러그인을 요청받아 왔으며 많은 개발자가 유사한 아이디어를 실험하고 있습니다. 가능한 사용 사례가 광범위하기 때문입니다. 우리는 소수의 사용자로 시작하여 더 많은 것을 알게 됨에 따라 점진적으로 더 큰 규모의 액세스를 출시할 계획입니다(플러그인 개발자, ChatGPT 사용자 및 알파 기간 이후 플러그인을 제품에 통합하려는 API 사용자). 우리는 앞으로 human-AI 상호 작용 패러다임의 미래를 만들어 나갈 커뮤니티를 건설해 나가는데 대해 아주 exciting합니다.

 

Plugin developers who have been invited off our waitlist can use our documentation to build a plugin for ChatGPT, which then lists the enabled plugins in the prompt shown to the language model as well as documentation to instruct the model how to use each. The first plugins have been created by Expedia, FiscalNote, Instacart, KAYAK, Klarna, Milo, OpenTable, Shopify, Slack, Speak, Wolfram, and Zapier.

 

대기자 명단에서 선택 돼 나온 플러그인 개발자는 문서를 사용하여 ChatGPT용 플러그인을 빌드할 수 있습니다. 그런 다음 언어 모델에 표시되는 프롬프트에 활성화된 플러그인을 나열하고 모델에 각 사용 방법을 지시하는 문서를 나열합니다. 첫 번째 플러그인은 Expedia, FiscalNote, Instacart, KAYAK, Klarna, Milo, OpenTable, Shopify, Slack, Speak, Wolfram 및 Zapier에서 만들었습니다.

 

 

반응형


반응형

https://platform.openai.com/docs/plugins/introduction

 

OpenAI API

An API for accessing new AI models developed by OpenAI

platform.openai.com

 

Chat Plugins 

Limited Alpha

Learn how to build a plugin that allows ChatGPT to intelligently call your API.

 

ChatGPT가 API를 지능적으로 call 할 수 있도록 하는 플러그인을 빌드하는 방법을 알아보세요.

 

Introduction

OpenAI plugins connect ChatGPT to third-party applications. These plugins enable ChatGPT to interact with APIs defined by developers, enhancing ChatGPT's capabilities and allowing it to perform a wide range of actions.

 

OpenAI 플러그인은 ChatGPT를 타사 애플리케이션에 연결합니다. 이러한 플러그인을 통해 ChatGPT는 개발자가 정의한 API와 상호 작용하여 ChatGPT의 기능을 향상하고 광범위한 작업을 수행할 수 있습니다.

 

  • Plugins can allow ChatGPT to do things like:
  • 플러그인을 통해 ChatGPT는 다음과 같은 작업을 수행할 수 있습니다.
  • Retrieve real-time information; e.g., sports scores, stock prices, the latest news, etc.
  • 실시간 정보 검색 예: 스포츠 점수, 주가, 최신 뉴스 등
  • Retrieve knowledge-base information; e.g., company docs, personal notes, etc.
  • 지식 기반 정보를 검색합니다. 예: 회사 문서, 개인 메모 등
  • Perform actions on behalf of the user; e.g., booking a flight, ordering food, etc.
  • 사용자를 대신하여 작업을 수행합니다. 예: 비행기 예약, 음식 주문 등

 

Plugins are in a limited alpha and may not yet be accessible to you. Please join the waitlist to get access. During the alpha, we will be working closely with users and developers to iterate on the plugin system, which may evolve significantly.

 

플러그인은 제한된 알파 상태이며 아직 액세스할 수 없을겁니다. 액세스하려면 대기자 명단에 등록하십시오. 알파 기간 동안 우리는 사용자 및 개발자와 긴밀히 협력하여 크게 발전할 수 있는 플러그인 시스템을 반복할 것입니다.

 

Plugin developers expose one or more API endpoints, accompanied by a standardized manifest file and an OpenAPI specification. These define the plugin's functionality, allowing ChatGPT to consume the files and make calls to the developer-defined APIs.

 

플러그인 개발자는 표준화된 매니페스트 파일 및 OpenAPI 사양과 함께 하나 이상의 API 엔드포인트를 노출합니다. 이들은 플러그인의 기능을 정의하여 ChatGPT가 파일을 사용하고 개발자 정의 API를 호출할 수 있도록 합니다.

 

The AI model acts as an intelligent API caller. Given an API spec and a natural-language description of when to use the API, the model proactively calls the API to perform actions. For instance, if a user asks, "Where should I stay in Paris for a couple nights?", the model may choose to call a hotel reservation plugin API, receive the API response, and generate a user-facing answer combining the API data and its natural language capabilities.

 

AI 모델은 지능형 API 호출자 역할을 합니다. API 사양과 API 사용 시기에 대한 자연어 설명이 주어지면 모델은 사전에 API를 호출하여 작업을 수행합니다. 예를 들어 사용자가 "파리에서 며칠 밤을 묵어야 합니까?"라고 묻는 경우 모델은 호텔 예약 플러그인 API를 호출하고 API 응답을 수신하고 API 데이터를 결합한 사용자 대면 답변을 생성하도록 선택할 수 있습니다. 그리고 ChatGPT의 자연 언어 기능으로 이를 처리 할 것입니다.

 

Over time, we anticipate the system will evolve to accommodate more advanced use cases.

 

시간이 지남에 따라 시스템이 고급 사용 사례를 수용하도록 발전할 것으로 예상합니다.

 

Plugin flow

To build a plugin, it is important to understand the end-to-end flow.

 

플러그인을 구축하려면 end-to-end 흐름을 이해하는 것이 중요합니다.

 

  1. Create a manifest file and host it at yourdomain.com/.well-known/ai-plugin.json
    매니페스트 파일을 만들고 yourdomain.com/.well-known/ai-plugin.json에서 호스트합니다. 
    • The file includes metadata about your plugin (name, logo, etc.), details about authentication required (type of auth, OAuth URLs, etc.), and an OpenAPI spec for the endpoints you want to expose.
    • 이 파일에는 플러그인에 대한 메타데이터(이름, 로고 등), 필요한 인증에 대한 세부 정보(인증 유형, OAuth URL 등), 노출하려는 엔드포인트에 대한 OpenAPI 사양이 포함됩니다.
    • The model will see the OpenAPI description fields, which can be used to provide a natural language description for the different fields.
    • 모델은 다양한 필드에 대한 자연어 설명을 제공하는 데 사용할 수 있는 OpenAPI 설명 필드를 볼 수 있습니다.
    • We suggest exposing only 1-2 endpoints in the beginning with a minimum number of parameters to minimize the length of the text. The plugin description, API requests, and API responses are all inserted into the conversation with ChatGPT. This counts against the context limit of the model.
    • 텍스트 길이를 최소화하기 위해 최소한의 매개변수로 처음에 1-2개의 endpoint만 노출하는 것이 좋습니다. 플러그인 설명, API 요청 및 API 응답은 모두 ChatGPT와의 대화에 삽입됩니다. 이는 모델의 컨텍스트 제한에 포함됩니다.

 

  1. Register your plugin in the ChatGPT UI
    • Select the plugin model from the top drop down, then select “Plugins”, “Plugin Store”, and finally “Install an unverified plugin” or “Develop your own plugin”.
    • 상단 드롭다운에서 플러그인 모델을 선택한 다음 "플러그인", "플러그인 스토어"를 선택하고 마지막으로 "확인되지 않은 플러그인 설치" 또는 "자체 플러그인 개발"을 선택합니다.
    • If authentication is required, provide an OAuth 2 client_id and client_secret or an API key 
    • 인증이 필요한 경우 OAuth 2 client_id 및 client_secret 또는 API 키를 제공하십시오.

 

  1. Users activate your plugin
    사용자가 플러그인을 활성화합니다. 
    • Users must manually activate your plugin in the ChatGPT UI. (ChatGPT will not use your plugin by default.)
    • 사용자는 ChatGPT UI에서 플러그인을 수동으로 활성화해야 합니다. (ChatGPT는 기본적으로 플러그인을 사용하지 않습니다.)
    • During the alpha, plugin developers will be able to share their plugin with 15 additional users (only other developers can install unverified plugins currently). Overtime we will roll out a way to submit your plugin for review to be exposed to all of ChatGPT’s user base.
    • 알파 기간 동안 플러그인 개발자는 15명의 추가 사용자와 플러그인을 공유할 수 있습니다(현재 다른 개발자만 확인되지 않은 플러그인을 설치할 수 있음). 시간이 지나면 모든 ChatGPT 사용자 기반에 노출될 검토를 위해 플러그인을 제출하는 방법을 출시할 것입니다.
    • If auth is required, users will be redirected via OAuth to your plugin; you can optionally create new accounts here as well.
    • 인증이 필요한 경우 사용자는 OAuth를 통해 플러그인으로 리디렉션됩니다. 선택적으로 여기에서 새 계정을 만들 수도 있습니다.
    • In the future, we hope to build features to help users discover useful & popular plugins.
    • 앞으로는 사용자가 유용하고 인기 있는 플러그인을 찾는 데 도움이 되는 기능을 구축할 수 있기를 바랍니다.

 

  1. Users begin a conversation
    • OpenAI will inject a compact description of your plugin in a message to ChatGPT, invisible to end users. This will include the plugin description, endpoints, and examples.
    • OpenAI는 최종 사용자에게 보이지 않는 ChatGPT 메시지에 플러그인에 대한 간략한 설명을 삽입합니다. 여기에는 플러그인 설명, 끝점 및 예제가 포함됩니다.
    • When a user asks a relevant question, the model may choose to invoke an API call from your plugin if it seems relevant; for POST requests, we require that developers build a user confirmation flow.
    • 사용자가 관련 질문을 할 때 모델은 관련이 있다고 판단되면 플러그인에서 API call을 호출하도록 선택할 수 있습니다. POST 요청의 경우 개발자가 사용자 확인 흐름을 구축해야 합니다.
    • The model will incorporate the API results into its response to the user.
    • 모델은 API 결과를 사용자에 대한 응답에 통합합니다.
    • The model might include links returned from API calls in its response. These will be displayed as rich previews (using the OpenGraph protocol, where we pull the site_name, title, description, image, and url fields)"
    • 모델은 응답에 API 호출에서 반환된 링크를 포함할 수 있습니다. 풍부한 미리보기로 표시됩니다(Site_name, 제목, 설명, 이미지 및 URL 필드를 가져오는 OpenGraph 프로토콜 사용)"

 

Currently, we will be sending the user’s country and state in the Plugin conversation header (if you are in California for example, it would look like {"openai-subdivision-1-iso-code": "US-CA"}. For further data sources, users will have to opt in via a consent screen. This is useful for shopping, restaurants, weather, and more. You can read more in our developer terms of use.

 

현재 플러그인 대화 헤더에 사용자의 국가와 주를 보낼 예정입니다(예를 들어 캘리포니아에 있는 경우 {"openai-subdivision-1-iso-code": "US-CA"}와 같이 표시됨). 추가 데이터 소스를 사용하려면 사용자가 동의 화면을 통해 선택해야 합니다. 이것은 쇼핑, 레스토랑, 날씨 등에 유용합니다. 개발자 사용 약관에서 자세한 내용을 읽을 수 있습니다.

 

반응형

'Open AI > CHAT PLUGINS' 카테고리의 다른 글

Chat GPT Plugin - Plugin policies  (0) 2023.04.04
Chat GPT Plugin - Plugins in production  (0) 2023.04.04
Chat GPT Plugin - Example plugins  (0) 2023.04.04
Chat GPT Plugin - Authentication  (0) 2023.04.04
Chat GPT Plugin - Getting started  (0) 2023.03.27
이전 1 다음