Kani (is)는 도구 사용/기능 호출을 통해 채팅 기반 언어 모델을위한 가볍고 해킹 가능한 프레임 워크입니다.
다른 LM 프레임 워크와 비교할 때 Kani는 의견이 적고 제어 흐름 부분에 비해 더 세밀한 사용자 정의 가능성을 제공하므로 NLP 연구원, 애호가 및 개발자 모두에게 완벽한 선택이됩니다.
Kani는 다음과 같은 모델을 지원하는 다음 모델을 지원하며, 더 많은 정보를 제공 할 수있는 모델 공유 프레임 워크가 있습니다.
호스팅 된 모델
오픈 소스 모델
Kani는 transformers
또는 llama.cpp
통해 얼굴을 안고있는 모든 채팅 모델을 지원합니다!
특히, 다음 기본 모델에 대한 참조 구현과 미세 조정이 있습니다.
애플리케이션에서 이러한 각 모델을 사용하는 방법을 확인하려면 모델 동물원을 확인하십시오!
기여에 관심이 있으십니까? 가이드를 확인하십시오.
Readthedocs에서 문서를 읽으십시오!
Arxiv에서 우리 논문을 읽으십시오!
카니는 3.10 이상의 파이썬이 필요합니다. 모델 별 종속성을 설치하려면 Kani는 다양한 추가 기능 ( pip install
의 라이브러리 이름 후 괄호)을 사용합니다. 설치할 여분의 추가를 결정하려면 모델 테이블을 참조하거나 [all]
추가를 사용하여 모든 것을 설치하십시오.
# for OpenAI models
$ pip install " kani[openai] "
# for Hugging Face models
$ pip install " kani[huggingface] " torch
# or install everything:
$ pip install " kani[all] "
최신 변경 및 새로운 모델의 경우 GIT main
브랜치에서 개발 버전을 설치할 수도 있습니다.
$ pip install " kani[all] @ git+https://github.com/zhudotexe/kani.git@main "
카니는 3.10 이상의 파이썬이 필요합니다.
먼저 라이브러리를 설치하십시오. 이 빠른 스타트에서는 Kani가 모델에 대한 정보를 제공하지만 OpenAI 엔진을 사용할 것입니다.
$ pip install " kani[openai] "
그런 다음 Kani를 사용하여 Chatgpt를 백엔드로 사용하여 간단한 챗봇을 만듭니다.
# import the library
import asyncio
from kani import Kani , chat_in_terminal
from kani . engines . openai import OpenAIEngine
# Replace this with your OpenAI API key: https://platform.openai.com/account/api-keys
api_key = "sk-..."
# kani uses an Engine to interact with the language model. You can specify other model
# parameters here, like temperature=0.7.
engine = OpenAIEngine ( api_key , model = "gpt-4o-mini" )
# The kani manages the chat state, prompting, and function calling. Here, we only give
# it the engine to call ChatGPT, but you can specify other parameters like
# system_prompt="You are..." here.
ai = Kani ( engine )
# kani comes with a utility to interact with a kani through your terminal...
chat_in_terminal ( ai )
# or you can use kani programmatically in an async function!
async def main ():
resp = await ai . chat_round ( "What is the airspeed velocity of an unladen swallow?" )
print ( resp . text )
asyncio . run ( main ())
Kani는 작업 채팅 모델을 짧게 설정하는 동시에 모든 프롬프트, 기능 호출 및 기본 언어 모델에 대해 프로그래머에게 깊은 사용자 정의 가능성을 제공합니다.
기능 호출 언어 모델은 해당 문서를 기반으로 제공하는 기능을 호출 할 때를 선택할 수있는 기능을 제공합니다.
Kani를 사용하면 Python에 함수를 작성하여 @ai_function
Decorator라는 한 줄의 코드로 모델에 노출 할 수 있습니다.
# import the library
import asyncio
from typing import Annotated
from kani import AIParam , Kani , ai_function , chat_in_terminal , ChatRole
from kani . engines . openai import OpenAIEngine
# set up the engine as above
api_key = "sk-..."
engine = OpenAIEngine ( api_key , model = "gpt-4o-mini" )
# subclass Kani to add AI functions
class MyKani ( Kani ):
# Adding the annotation to a method exposes it to the AI
@ ai_function ()
def get_weather (
self ,
# and you can provide extra documentation about specific parameters
location : Annotated [ str , AIParam ( desc = "The city and state, e.g. San Francisco, CA" )],
):
"""Get the current weather in a given location."""
# In this example, we mock the return, but you could call a real weather API
return f"Weather in { location } : Sunny, 72 degrees fahrenheit."
ai = MyKani ( engine )
# the terminal utility allows you to test function calls...
chat_in_terminal ( ai )
# and you can track multiple rounds programmatically.
async def main ():
async for msg in ai . full_round ( "What's the weather in Tokyo?" ):
print ( msg . role , msg . text )
asyncio . run ( main ())
Kani는 코드 작성에 집중할 수 있도록 방법에 도달 할 때까지 기능 통화가 유효하다는 것을 보장합니다. 자세한 내용은 문서 호출 기능을 확인하십시오.
Kani는 기능 호출이있을 때에도 기본 언어 모델 토큰별로의 스트리밍 응답을 지원합니다. 스트리밍은 chat_round
및 full_round
메소드의 드롭 인 슈퍼 세트로 설계되었으므로 코드를 깨진 상태로 두지 않고도 점차적으로 리팩터링 할 수 있습니다.
async def stream_chat ():
stream = ai . chat_round_stream ( "What does kani mean?" )
async for token in stream :
print ( token , end = "" )
print ()
msg = await stream . message () # or `await stream`
async def stream_with_function_calling ():
async for stream in ai . full_round_stream ( "What's the weather in Tokyo?" ):
async for token in stream :
print ( token , end = "" )
print ()
msg = await stream . message ()
Langchain 및 Simpleaichat와 같은 언어 모델의 기존 프레임 워크는 의견 및/또는 헤비급 - 후드 아래에서 개발자의 프롬프트를 편집하고 학습하기가 어려우며 코드베이스에 많은 유지 관리 팽의를 추가하지 않고는 사용자 정의하기가 어렵습니다.
우리는 Kani를보다 유연하고 단순하며 강력한 대안으로 만들었습니다. 프레임 워크 사이의 좋은 비유는 Kani가 플라스크 (또는 Fastapi)가 장고에있는 것처럼 랑케인이라고 말하는 것입니다.
Kani는 학술 연구원에서 산업 전문가, 애호가, 취미에 이르기까지 모든 사람에게 적합합니다.
자신의 프롬프트 포장지, 기능 호출 등을 사용하여 Kani를 사용자 정의하는 방법에 대해 자세히 알아 보려면 문서를 읽으십시오!
또는이 저장소의 실습 예를 살펴보십시오.
카니가 행동하는 것을보고 싶습니까? 4 비트 Quantization을 사용하여 모델을 수축시키기 위해 GitHub 액션에 대한 테스트 스위트의 일부로 LLAMA V2를 실행합니다.
https://github.com/zhudotexe/kani/actions/workflows/pytest.yml?query=branch%3amain+is%3asuccess
Llama의 출력을 보려면 최신 빌드를 클릭하십시오!
핵심 개발 팀은 펜실베니아 대학교의 컴퓨터 및 정보 과학과에서 3 명의 박사 학위를 받았습니다. 우리는 Chris Callison-Burch 교수의 실험실 회원으로 NLP의 미래를 발전시키기 위해 노력하고 있습니다.
우리는 연구에 적극적으로 Kani를 사용하고 현대 NLP 관행으로 최신 상태를 유지하는 것을 목표로합니다.
Kani를 사용하는 경우 다음과 같이 인용하십시오.
@inproceedings{zhu-etal-2023-kani,
title = "Kani: A Lightweight and Highly Hackable Framework for Building Language Model Applications",
author = "Zhu, Andrew and
Dugan, Liam and
Hwang, Alyssa and
Callison-Burch, Chris",
editor = "Tan, Liling and
Milajevs, Dmitrijs and
Chauhan, Geeticka and
Gwinnup, Jeremy and
Rippeth, Elijah",
booktitle = "Proceedings of the 3rd Workshop for Natural Language Processing Open Source Software (NLP-OSS 2023)",
month = dec,
year = "2023",
address = "Singapore",
publisher = "Association for Computational Linguistics",
url = "https://aclanthology.org/2023.nlposs-1.8",
doi = "10.18653/v1/2023.nlposs-1.8",
pages = "65--77",
}
우리는 논문과 카니 저장소의 내용에 대한 테스트와 자세한 피드백에 대해 Chris Callison-Burch 실험실 회원들에게 감사의 말씀을 전합니다. 또한, 우리는 그의 초기 프로젝트에 대한 열정적 인 지원에 대해 Henry Zhu (첫 번째 저자와 관련이 없음)에게 감사의 말씀을 전합니다.
이 연구는 공군 연구 연구소 (Contract FA8750-23-C-0507), IARPA Hiatus 프로그램 (계약 2022-22072200005) 및 NSF (Award 1928631)가 부분적으로 지원하는 작업을 기반으로합니다. 공개 릴리스, 배포 무제한 승인. 여기에 포함 된 견해와 결론은 저자의 견해와 결론이며, IARPA, NSF 또는 미국 정부의 표현 또는 묵시적 정책을 반드시 표현하는 것으로 해석되어서는 안됩니다.