AI 봇 - 사용자 지정 도구

:bookmark: 이 가이드는 Discourse AI 플러그인 내에서 사용자 정의 AI 도구를 생성, 구성 및 통합하는 방법을 설명합니다. 이를 통해 관리자는 사용자 정의 JavaScript 함수를 사용하여 봇의 기능을 확장할 수 있습니다.

:person_raising_hand: 필요한 사용자 권한: 관리자

도구(Tools)는 AI 봇이 텍스트 기반 응답을 넘어 특정 작업을 수행하거나 정보를 검색할 때 사용할 수 있는 프로그래밍 가능한 기능입니다. 이러한 도구는 봇이 외부 API와 상호작용하거나 데이터를 조작하거나 추가 기능을 실행하여 기능을 확장할 수 있도록 하는 스크립트 또는 통합입니다.

요약

이 문서에서는 다음 내용을 다룹니다:

  • 새로운 사용자 정의 AI 도구 생성
  • 도구 매개변수 및 스크립트 구성
  • 도구 스크립트에서 사용 가능한 API
  • 사용자 정의 도구를 AI 페르소나와 통합하기
  • 사용자 정의 도구 테스트 및 문제 해결

새로운 사용자 정의 AI 도구 생성

새로운 AI 도구를 생성하려면:

  1. 관리 패널 > 플러그인 > Discourse AI > 도구로 이동하세요.
  2. "새 도구"를 클릭하세요. (옵션을 학습하기 위해 기존 프리셋을 사용할 수 있습니다.)
  3. 다음 필드를 입력하세요:
    • 이름(Name): LLM에게 표시되는 도구의 이름
    • 설명(Description): LLM에게 표시되는 도구의 설명
    • 요약(Summary): 사용자를 돕기 위해 도구가 수행하는 작업의 요약 (세부 정보에 표시됨)
    • 매개변수(Parameters): LLM에게 표시되는 도구가 필요한 입력값 정의
    • 스크립트(Script): 도구를 구동하는 JavaScript 코드
  4. "저장"을 클릭하세요.

도구 스크립트 구성

사용 가능한 API

도구 스크립트에서 다음 API에 접근할 수 있습니다:

  1. HTTP 요청:

    http.get(url, options)
    http.post(url, options)
    http.put(url, options)
    http.patch(url, options)
    http.delete(url, options)
    

    이를 사용하여 외부 서비스와 상호작용합니다. options를 사용하여 HTTP 헤더와 본문을 지정할 수 있습니다:

    http.get(url, { headers: { "Authorization": "Bearer key" } })
    http.post(url, { headers: { "Content-Type": "application/json" }, body: { key: "value" } })
    http.patch(url, { headers: { "Authorization": "Bearer key" }, body: "some body" })
    http.delete(url, { headers: { "Authorization": "Bearer key" } })
    http.put(url, { headers: { "Authorization": "Bearer key" }, body: "some body" })
    

    모든 HTTP 메서드는 { status: number, body: string }을 반환합니다.

  2. LLM(언어 모델) 통합:

    llm.truncate(text, length)
    

    구성된 LLM의 토크나이저를 기반으로 텍스트를 지정된 토큰 길이로 잘라냅니다.

    llm.generate(prompt, options)
    

    구성된 LLM을 사용하여 텍스트를 생성합니다. 프롬프트는 간단한 문자열이거나 { messages: [{ type: "system", content: "..." }, { type: "user", content: "..." }] }와 같은 구조화된 객체일 수 있습니다. 옵션에는 JSON 출력을 요청하고 자동으로 파싱하기 위한 json: true를 포함하여 temperature, top_p, max_tokens, stop_sequences가 있습니다.

  3. 사용자 정의 업로드 통합 (RAG)

    index.search(query, { filenames: ["file.pdf"], limit: 10 })
    

    이 도구에 연결된 인덱싱된 RAG 문서 단편을 검색합니다. 관련성 순서대로 Array<{ fragment: string, metadata: string | null }>를 반환합니다. 기본 제한은 10이며, 최대 200입니다.

    index.getFile(filename)
    

    정확한 파일명을 사용하여 업로드된 RAG 파일의 전체 내용을 가져옵니다. 전체 텍스트를 반환하거나, 찾지 못하면 null을 반환합니다.

  4. 업로드 지원

    upload.create(filename, base_64_content)
    

    새로운 업로드를 생성합니다. { id: number, url: string, short_url: string }을 반환합니다.

    upload.getUrl(shortUrl)
    

    짧은 URL(예: upload://12345)을 입력하면 전체 CDN 친화적 URL을 반환합니다.

    upload.getBase64(uploadIdOrShortUrl, maxPixels)
    

    기존 업로드의 base64 인코딩된 내용을 가져옵니다. 업로드 ID(숫자) 또는 짧은 URL(문자열)을 허용합니다. 이미지 자동 리사이징을 위한 선택적 maxPixels 매개변수(기본값: 10,000,000)가 있습니다.

  5. 실행 체인 제어

    chain.setCustomRaw(raw)
    

    봇의 게시글 최종 원본(raw) 내용을 설정하고 도구 실행 체인을 중단합니다. 전체 응답을 직접 생성하는 도구(예: 이미지 생성 도구)에 유용합니다.

  6. 비밀 정보(Secrets) 관리

    secrets.get(alias)
    

    주어진 별칭에 바인딩된 자격 증명 값을 반환합니다. 별칭은 도구의 비밀 계약 구성에서 정의되며 관리 패널의 AI Secrets에 바인딩됩니다. 별칭이 선언되지 않았거나, 바인딩되지 않았거나, 자격 증명이 누락된 경우 오류를 발생시킵니다.

    const apiKey = secrets.get("my_api_key");
    
  7. Discourse 통합

    도구는 Discourse 데이터와 직접 상호작용할 수 있습니다:

    discourse.baseUrl              // 사이트의 기본 URL
    discourse.search(params)       // Discourse 검색 수행
    discourse.getPost(post_id)     // 게시글 세부 정보 가져오기 (원본 내용 포함)
    discourse.getTopic(topic_id)   // 주제 세부 정보 가져오기 (태그, 카테고리 등)
    discourse.getUser(id_or_username)  // 사용자 세부 정보 가져오기
    discourse.createTopic(params)  // 새 주제 생성
    discourse.createPost(params)   // 새 게시글/답글 생성
    discourse.editPost(post_id, raw, options)    // 게시글 내용 편집
    discourse.editTopic(topic_id, updates, options) // 주제 속성 편집 (태그, 카테고리, 가시성)
    discourse.createChatMessage(params) // 채팅 메시지 보내기
    discourse.createStagedUser(params)  // 스테이징된 사용자 생성
    discourse.getAgent(name)       // 다른 AI 에이전트 가져오기 (respondTo 메서드 포함)
    discourse.updateAgent(name, updates) // AI 에이전트 구성 업데이트
    discourse.getCustomField(type, id, key)      // 게시글/주제/사용자의 사용자 정의 필드 읽기
    discourse.setCustomField(type, id, key, value) // 게시글/주제/사용자의 사용자 정의 필드 설정
    
  8. 컨텍스트 객체

    context 객체는 도구가 실행되는 위치에 대한 정보를 제공합니다:

    • 봇 대화 컨텍스트: context.post_id, context.topic_id, context.private_message, context.participants, context.username, context.user_id
    • 채팅 컨텍스트: context.message_id, context.channel_id, context.username
    • 자동화 컨텍스트: context.post_id, context.topic_id, context.username, context.user_id, context.feature_name, context.feature_context
    • 공통 속성: context.site_url, context.site_title, context.site_description

필수 함수

스크립트는 다음을 구현해야 합니다:

  • invoke(params): 도구가 호출될 때 실행되는 주요 함수

선택적으로 다음을 구현할 수 있습니다:

  • details(): 도구 실행을 설명하는 문자열(기본 HTML 포함 가능)을 반환하며, 채팅 인터페이스에 표시됩니다.
  • customSystemMessage(): 프롬프트 조립 시(도구 호출 시에는 아님) 호출됩니다. 시스템 프롬프트에 추가될 문자열을 반환하거나, 건너뛰려면 null/undefined를 반환합니다. context, discourse, index 객체에 접근할 수 있습니다.

예제 스크립트:

function invoke(params) {
  let result = http.get("https://api.example.com/data?query=" + params.query);
  return JSON.parse(result.body);
}

function details() {
  return "Fetched data from Example API";
}

제한 사항 및 보안

  • 실행 시간 초과: 스크립트 처리 시간의 기본 시간 초과는 2000ms입니다. 외부 HTTP 요청(http.*) 및 LLM 호출(llm.generate) 동안 타이머가 일시 정지되므로, 스크립트 자체의 처리 시간만 계산됩니다.
  • 메모리: 최대 10MB V8 힙 제한
  • HTTP 요청: 도구 실행당 최대 20개 요청
  • 샌드박스 환경: 스크립트는 제한된 V8 JavaScript 환경(MiniRacer를 통해)에서 실행됩니다. 브라우저 전역 변수, 호스트 파일 시스템 또는 서버 측 라이브러리에 대한 접근이 없습니다. 네트워크 요청은 Discourse 백엔드를 통해 프록시됩니다.

도구 테스트

LLM이 제공받을 결과가 기대와 일치하는지 확인하기 위해 만든 도구를 테스트해야 합니다.

도구를 AI 페르소나와 통합하기

사용자 정의 도구를 AI 페르소나에 추가하려면:

  1. 관리 패널 > 플러그인 > Discourse AI > 페르소나로 이동하세요.
  2. 기존 페르소나를 편집하거나 새 페르소나를 생성하세요.
  3. “도구” 섹션에서 내장 도구와 함께 사용자 정의 도구가 목록에 표시됩니다.
  4. 페르소나에 추가할 사용자 정의 도구를 선택하세요.

실제 사용 중인 사용자 정의 도구

LLM에 사용자 정의 도구를 제공하면 대화의 질을 높이기 위해 이를 사용할 수 있습니다.

문제 해결

도구가 기대대로 작동하지 않는 경우:

  1. 입력값에 대해 기대하는 대로 작동하는지 확인하기 위해 테스트 인터페이스를 사용하세요.
  2. 그룹이 ai_bot_debugging_allowed_groups에 있는지 확인하세요. 이 그룹의 멤버는 봇 전사(transcripts)에 대한 전체 접근 권한을 가지며,在那里 AI 로그를 볼 수 있습니다.
  3. 예상치 못한 일이 발생하면 https://SITENAME/logs를 방문하여 오류를 확인하세요.

추가 리소스

14개의 좋아요

I’m just getting into building tools for AI personas in Discourse, in part so I can really focus on it; this seems like it’s very useful given how many useful and public APIs there are!

For instance, I’m getting results such as:

Understanding Decision-Making Through Poker Strategies AI

maiki:

Create an infocard for Breath of the Wild.

gpt-4o:

Here is an information card for “The Legend of Zelda: Breath of the Wild”:


Title: The Legend of Zelda: Breath of the Wild
Developer: Nintendo
Publisher: Nintendo
Release Date: March 3, 2017
Platforms: Nintendo Switch, Wii U
Genre: Action-adventure
Mode: Single-player

Synopsis:
Set in a vast open world, players control Link, who awakens from a deep slumber to defeat Calamity Ganon and save the kingdom of Hyrule. The game is praised for its immersive environment, allowing players to explore and interact freely with the world and its systems.

Awards:
The game has won numerous awards, including several Game of the Year accolades, for its innovative design, expansive world, and enchanting gameplay.

More information: Wikidata Entry


“Breath of the Wild” is renowned for redefining open-world games and delivering a captivating experience that encourages exploration and discovery.

maiki:

The same for Animal Crossing: New Horizons.

gpt-4o:

Here is an information card for “Animal Crossing: New Horizons”:


Title: Animal Crossing: New Horizons
Developer: Nintendo
Publisher: Nintendo
Release Date: March 20, 2020
Platform: Nintendo Switch
Genre: Social simulation
Mode: Single-player, Multiplayer

Synopsis:
In this charming social simulation game, players assume the role of a customizable character who relocates to a deserted island after purchasing a package from Tom Nook. The game allows for real-time exploration, resource gathering, crafting, and customization, fostering a communal and relaxing gameplay experience.

Awards:
The game was acclaimed for its creative freedom and timing of release, receiving accolades for Game of the Year and its contributions to social gaming during the global pandemic.

More information: Wikidata Entry


“Animal Crossing: New Horizons” became a cultural phenomenon, celebrated for its engaging social features and stress-relieving gameplay during challenging times.

maiki:

A long way from Chicago

gpt-4o:

Here is an information card for the book “A Long Way from Chicago”:


Title: A Long Way from Chicago
Author: Richard Peck
Publication Year: 1998
Genre: Historical Fiction, Young Adult
ISBN: 978-0141303529

Synopsis:
This Newbery Honor-winning novel is a series of short stories chronicling the annual summer trips of Joey and his sister Mary Alice from Chicago to a rural Illinois town to visit their larger-than-life Grandma Dowdel during the late 1920s and 1930s. Each chapter presents an amusing and poignant episode that imparts life lessons amidst the backdrop of the Great Depression.

Awards:
The book was awarded a Newbery Honor in 1999 and is celebrated for its humor, depth, and portrayal of rural American life during the early 20th century.

More information: Wikidata Entry


This book is appreciated for its nostalgic and heartwarming storytelling, capturing the essence of familial bonds and simpler times.

maiki:

Thinking in Bets

gpt-4o:

I previously found the Wikidata entry for “Thinking in Bets,” but I’m unable to retrieve further specific details directly from Wikidata at the moment. However, here is a brief card based on available information:


Title: Thinking in Bets: Making Smarter Decisions When You Don’t Have All the Facts
Author: Annie Duke
Publication Year: 2018
Genre: Non-fiction, Decision Making, Psychology
ISBN: 978-0735216358

Synopsis:
The book leverages insights from poker to help readers understand decision-making under uncertainty. Annie Duke, blending her experiences as a professional poker player and cognitive psychologist, offers a framework for making smarter decisions, evaluating outcomes, and adopting a probabilistic mindset.

More information: Wikidata Entry


For detailed insights, you might consider checking additional resources or databases pertaining to book publications.


Okay, so that’s fine, but I noticed this description…

…and wonder: should I be building my prompts referring directly to those tools, for efficient use?

My general approach to prompt-writing is to refine over time and then lock onto a pattern of behavior I wish for the AI tooling to adopt. However, if I could add specific instructions on, for instance, when to lookup a Wikidata entity, and when to list all claims of a particular entity (two different APIs), then I feel I could refine the entire workflow to flow as I intend… :star_struck:

4개의 좋아요

Indeed clearly explaining the tool and providing examples in the system prompt is beneficial.

2개의 좋아요

Is it possible in a custom tool to insert the API key and OpenAI project from the admin settings?

1개의 좋아요

You can make rest calls from a custom tool and specify all headers

2개의 좋아요

just realized that lol… sorry for the brainfart

1개의 좋아요

I have uploaded some documents to a persona, it generated the embeddings and now can do semantic search over them. But in some cases, semantic search is not ideal, so I’d like to enhance it and have hybrid search e.g. keep what’s already there and add keyword search. At the moment if I want to do that I should write a custom tool , right?
I know I could simply publish the docs as topics and then it’ll work out of the box with the native Discourse search, but it’s not an option currently.

커스텀 도구를 추가할 때 배열 매개변수를 사용하면 도구 스키마 오류가 발생합니다. 대화 시작 시 오류가 발생하며, 내용은 다음과 같습니다:

{
“error”: {
“code”: 400,
“message”: “* GenerateContentRequest.tools[0].function_declarations[3].parameters.properties[properties].items: missing field.\n”,
“status”: “INVALID_ARGUMENT”
}
}

시도해 본 내용:

  • properties라는 이름의 배열 타입 매개변수를 가진 커스텀 도구를 생성했습니다.
  • 매개변수 목록 UI에서는 items를 지정할 수 없습니다.
  • properties에 대해 items: { type: “string” }가 포함된 전체 도구 JSON을 내보낸 후 가져왔습니다.
  • 가져온 후, 해당 도구가 페르소나에 활성화되는 즉시 오류가 계속 발생합니다. 도구를 제거하면 봇은 정상적으로 작동합니다.

기대하는 동작:

매개변수 목록 UI에서 배열 항목 타입을 정의할 수 있어야 하거나, 가져오기 시 items가 반영되어 스키마가 유효하게 검증되어야 합니다.

혹시 이 문제를 경험하신 분이 계신가요? 알려진 제한 사항이 있거나, 배열 매개변수를 정의하기 위한 필수 UI 경로가 있는 건가요?

1개의 좋아요