다음과 같이 최신 버전을 설치하십시오.
pip install operagents
# or use poetry
poetry add operagents
# or use pdm
pdm add operagents
# or use uv
uv pip install operagents에이전트는 오페라 장면에서 캐릭터 역할을하고 소품을 사용할 수있는 인간 또는 언어 모델입니다. 에이전트는 관찰하고 행동하여 다른 사람과 의사 소통 할 수 있습니다. 모든 에이전트에는 장기 / 단기 정보를 저장하기 위해 응답 및 자체 메모리를 생성하는 백엔드 (예 : 사용자, OpenAI API)가 있습니다.
장면은 여러 캐릭터를 포함하는 오페라의 일부입니다. 모든 장면에는 전체 세션 프로세스를 제어 할 수있는 흐름과 감독이 있습니다. 장면은 또한 장면이 시작되기 전에 초기화 작업을 수행 할 준비 섹션을 가질 수 있습니다.
캐릭터는 장면에서 역할입니다. 모든 캐릭터에는 이름, 설명 및 소품 목록이 있습니다. 장면이 시작되면 에이전트는 캐릭터 역할을하고 다른 사람과 의사 소통합니다.
흐름은 현장에서 캐릭터의 순서를 제어하는 데 사용됩니다.
감독은 현재 장면을 종료할지 여부와 다음에 플레이 할 장면을 결정하는 데 사용됩니다.
소품은 에이전트가 연기를 개선하기 위해 사용할 수있는 도구입니다. 에이전트는 소품을 사용하여 외부 정보를 얻을 수 있습니다.
타임 라인은 세션 프로세스를 관리하기위한 오페라의 주요 런타임 구성 요소입니다. 현재 세션을 실행하고 세션간에 전환합니다. 타임 라인은 또한 오페라의 글로벌 정보를 기록하며 모든 에이전트가 공유 할 수 있습니다.
세션은 한 번의 장면 실행을 나타냅니다. 고유 식별자와 해당 장면이 포함되어 있습니다.
Operagents를 사용하는 일반적인 방법은 구성 파일을 작성하고 operagents 명령 줄 도구로 오페라를 실행하는 것입니다.
다음 기본 내용으로 config.yaml 파일을 만듭니다.
# yaml-language-server: $schema=https://operagents.yyydl.top/schemas/config.schema.json
agents :
opening_scene : " "
scenes : 첫 번째 줄은 Yaml Language Server에게 지정된 URL의 스키마를 사용하도록 지시하는 주석입니다. 이렇게하면 편집기에서 자동 완성 및 유효성 검사가 가능합니다.
스키마는 사용중인 Operagents 프레임 워크의 버전과 관련이 있습니다. URL은 형식 https://operagents.yyydl.top/schemas/config-<version>.schema.json <version> 0.0.1 . 버전이 지정되지 않으면 최신 (마스터) 버전이 사용됩니다.
에이전트 및 장면 구성을 작성하기 전에 템플릿 구성에 대해 배워야합니다.
오페라 인들은 템플릿을 사용하여 언어 모델의 컨텍스트 입력을 생성합니다. 템플릿은 Jinja 형식의 문자열입니다. 제공된 컨텍스트 변수와 함께 Jinja2 구문을 사용하여 언어 모델에 대한 입력을 제어 할 수 있습니다.
템플릿 구성은 다음 형식 일 수 있습니다.
간단한 문자열 템플릿
user_template : |-
{# some jinja template #}사용자 정의 기능이있는 템플릿
user_template :
content : |-
{# some jinja template #}
custom_functions :
function_name : module_name:function_name 템플릿에서 사용자 정의 함수를 사용하려면 사용자 정의 함수 이름 및 해당 모듈 경로의 사전 인 custom_functions 키를 DOT 표기법 형식으로 제공해야합니다.
agents 섹션은 에이전트 사전이며, 여기서 키는 에이전트 이름이고 값은 에이전트의 구성입니다.
에이전트는 장면에서 캐릭터 역할을하고 다른 사람의 메시지에 응답해야합니다. 따라서 에이전트 구성의 첫 번째 부분은 Backend Config이며 언어 모델 또는 사용자와 통신하는 데 사용됩니다. backend 키를 사용하여 백엔드 유형 및 해당 구성을 지정할 수 있습니다.
agents :
Mike :
backend :
# user as the backend (a.k.a human-agent)
type : user
John :
backend :
# openai api as the backend
type : openai
model : gpt-3.5-turbo
temperature : 0.5
api_key :
base_url :
max_retries : 2
tool_choice :
type : auto
prop_validation_error_template : |-
{# some jinja template #} 또한 Backend Abstract 클래스를 구현하는 사용자 정의 백엔드 클래스의 객체 경로를 제공하여 백엔드를 사용자 정의 할 수도 있습니다. :
agents :
Mike :
backend :
type : custom
path : module_name:CustomBackend
custom_config : value # module_name.py
from typing import Self
from operagents . prop import Prop
from operagents . timeline import Timeline
from operagents . config import CustomBackendConfig
from operagents . backend import Backend , Message , GenerateResponse , GeneratePropUsage
class CustomBackend ( Backend ):
@ classmethod
def from_config ( cls , config : CustomBackendConfig ) -> Self :
return cls ()
@ overload
async def generate (
self ,
timeline : Timeline ,
messages : list [ Message ],
props : None = None ,
) -> AsyncGenerator [ GenerateResponse , None ]: ...
@ overload
async def generate (
self ,
timeline : Timeline ,
messages : list [ Message ],
props : list [ Prop ],
) -> AsyncGenerator [ GenerateResponse | GeneratePropUsage , None ]: ...
async def generate (
self , timeline : Timeline , messages : list [ Message ], props : list [ Prop ] | None = None
) -> AsyncGenerator [ GenerateResponse | GeneratePropUsage , None ]:
yield GenerateResponse ( content = "" ) 에이전트 구성의 다음 부분은 언어 모델의 컨텍스트 입력을 생성하는 데 사용되는 시스템/사용자 템플릿입니다. system_template / user_template 키를 사용하여 시스템 / 사용자 템플릿을 지정할 수 있습니다. 다음은 템플릿 구성의 예입니다.
agents :
John :
system_template : |-
Your name is {{ agent.name }}.
Current scene is {{ timeline.current_scene.name }}.
{% if timeline.current_scene.description -%}
{{ timeline.current_scene.description }}
{%- endif -%}
You are acting as {{ timeline.current_character.name }}.
{% if timeline.current_character.description -%}
{{ timeline.current_character.description }}
{%- endif -%}
Please continue the conversation on behalf of {{ agent.name }}({{ timeline.current_character.name }}) based on your known information and make your answer appear as natural and coherent as possible.
Please answer directly what you want to say and keep your reply as concise as possible.
user_template : |-
{% for event in timeline.past_events(agent) -%}
{% if event.type_ == "session_act" -%}
{{ event.character.agent_name }}({{ event.character.name }}): {{ event.content }}
{%- endif %}
{%- endfor %} 에이전트 구성의 또 다른 부분은 세션 요약 시스템/사용자 템플릿으로, 장면 세션의 요약을 생성하는 데 사용됩니다. session_summary_system_template / session_summary_user_template 키를 사용하여 세션 요약 시스템 / 사용자 템플릿을 지정할 수 있습니다. 다음은 템플릿 구성의 예입니다.
agents :
John :
session_summary_system_template : |-
Your name is {{ agent.name }}.
Your task is to summarize the historical dialogue records according to the current scene, and summarize the most important information.
session_summary_user_template : |-
{% for event in agent.memory.get_memory_for_session(session_id) -%}
{% if event.type_ == "observe" -%}
{{ event.content }}
{%- elif event.type_ == "act" -%}
{{ agent.name }}({{ event.character.name }}): {{ event.content }}
{%- endif %}
{%- endfor %}
{% for event in timeline.session_past_events(agent, session_id) -%}
{% if event.type_ == "session_act" -%}
{{ event.character.agent_name }}({{ event.character.name }}): {{ event.content }}
{%- endif %}
{%- endfor %} opening_scene 키는 오페라의 시작 장면을 지정하는 데 사용됩니다. 값은 오프닝 장면의 이름입니다.
opening_scene : " Introduction " scenes 섹션은 장면 사전으로, 키는 장면 이름이고 값은 장면 구성입니다.
오페라는 여러 장면으로 구성되며 각 장면에는 여러 캐릭터가 있습니다. 먼저 이름, 설명 (선택 사항) 및 장면의 문자를 정의해야합니다.
scenes :
talking :
description : " The scene is about two people talking. "
characters :
user :
agent_name : " Mike "
ai assistant :
agent_name : " John "
description : |-
You are a helpful assistant.
props : [] 장면의 캐릭터는 캐릭터 역할을하는 에이전트의 이름 인 agent_name 키를 정의해야합니다. description 키 (선택 사항)을 사용하여 에이전트 템플릿의 문자를 설명 할 수 있습니다. props 키 (선택 사항)를 사용하여 문자의 소품을 정의하고 자세한 내용은 소품 구성을 참조하십시오.
장면의 Flow 캐릭터의 연기 순서를 제어하도록 설계되었습니다. Flow 의 유형과 매개 변수를 지정할 수 있습니다.
order 유형
order 유형은 캐릭터 연기 순서를 사전 정의하는 데 사용됩니다. 캐릭터는 장면이 끝날 때까지 순서 목록을 순환합니다.
scenes :
talking :
flow :
type : order
order :
- user
- ai assistant model 유형
model 유형은 다음 문자를 예측하기 위해 모델을 지정하는 데 사용됩니다. 이 모델은 현재 컨텍스트를 기반으로 다음 문자를 예측합니다.
scenes :
talking :
flow :
type : model
backend :
type : openai
model : gpt-3.5-turbo
temperature : 0.5
system_template : " "
user_template : " "
allowed_characters : # optional, the characters allowed to act
- user
- ai assistant
begin_character : user # optional, the first character to act
fallback_character : ai assistant # optional, the fallback character when the model fails to predict user 유형
user 유형을 통해 사람은 다음 문자를 선택할 수 있습니다.
scenes :
talking :
flow :
type : user custom 유형
custom 유형을 사용하면 문자 연기 순서를 제어하기 위해 사용자 정의 흐름 클래스를 정의 할 수 있습니다.
scenes :
talking :
flow :
type : custom
path : module_name:CustomFlow
custom_config : value # module_name.py
from typing import Self
from operagents . flow import Flow
from operagents . timeline import Timeline
from operagents . character import Character
from operagents . config import CustomFlowConfig
class CustomFlow ( Flow ):
@ classmethod
def from_config ( cls , config : CustomFlowConfig ) -> Self :
return cls ()
async def begin ( self , timeline : Timeline ) -> Character :
return ""
async def next ( self , timeline : Timeline ) -> Character :
return "" 장면의 Director 다음 장면을 제어하는 데 사용됩니다. 감독의 유형과 매개 변수를 지정할 수 있습니다.
model 유형
model 유형은 다음 장면을 재생하기 위해 모델을 지정하는 데 사용됩니다. 마감 깃발이 발견되지 않거나 장면 이름이 발견되지 않으면 Curent 장면이 계속 재생됩니다.
scenes :
talking :
director :
type : model
backend :
type : openai
model : gpt-3.5-turbo
temperature : 0.5
system_template : " "
user_template : " "
allowed_scenes : # optional, the next scenes allowed to play
- walking
- running
finish_flag : " finish " # optional, the finish flag to end the opera user 유형
user 유형을 통해 사람은 다음 장면을 선택할 수 있습니다.
scenes :
talking :
director :
type : user never 입력하지 마십시오
never 감독은 현재 장면을 끝내지 않습니다. 단일 장면이 있고 Prop 으로 오페라를 종료하려는 경우 유용합니다.
scenes :
talking :
director :
type : never custom 유형
custom 유형을 사용하면 다음 장면을 제어하기 위해 사용자 정의 감독 클래스를 정의 할 수 있습니다.
scenes :
talking :
director :
type : custom
path : module_name:CustomDirector
custom_config : value # module_name.py
from typing import Self
from operagents . scene import Scene
from operagents . director import Director
from operagents . timeline import Timeline
from operagents . config import CustomDirectorConfig
class CustomDirector ( Director ):
@ classmethod
def from_config ( cls , config : CustomDirectorConfig ) -> Self :
return cls ()
async def next_scene ( self , timeline : Timeline ) -> Scene | None :
return None 장면의 prepare 섹션은 장면이 시작되기 전에 준비 단계를 정의하는 데 사용됩니다. 여기에서 몇 가지 초기화 작업을 수행 할 수 있습니다.
preface 유형
장면이 시작되기 전에 캐릭터가 무언가를 말할 수 있습니다.
scenes :
talking :
prepare :
- type : preface
character_name : ai assistant
content : |-
Hello, I am John, your AI assistant. How can I help you today? function 유형
장면이 시작되기 전에 function 유형이 사용자 정의 기능을 호출합니다.
scenes :
talking :
prepare :
- type : function
function : module_name:function_name 사용자 정의 함수는 operagents.timeline.Timeline 의 유형 매개 변수를받습니다.
# module_name.py
from operagents . timeline import Timeline
async def function_name ( timeline : Timeline ) -> None :
pass custom 유형
장면이 시작되기 전에 custom 유형이 사용자 정의 준비 클래스를 호출합니다.
scenes :
talking :
prepare :
- type : custom
path : module_name:CustomPrepare
custom_config : value # module_name.py
from typing import Self
from operagents . timeline import Timeline
from operagents . scene . prepare import ScenePrepare
from operagents . config import CustomScenePrepareConfig
class CustomScenePrepare ( ScenePrepare ):
@ classmethod
def from_config ( cls , config : CustomScenePrepareConfig ) -> Self :
return cls ()
async def prepare ( self , timeline : Timeline ) -> None :
pass 장면의 캐릭터는 소품을 사용하여 행동을 향상시킬 수 있습니다. props 섹션은 소품 목록이며, 각 소품은 소품 유형 및 소품 구성이있는 사전입니다.
function 소품
소품이 사용될 때 function 소품이 사용자 정의 기능을 호출합니다.
scenes :
talking :
characters :
ai assistant :
props :
- type : function
function : module_name:function_name
exception_template : |-
{# some jinja template #} 사용자 정의 함수에는 pydantic.BaseModel 유형의 인수 또는 하나의 주장이 없어야합니다.
from pydantic import Field , BaseModel
from datetime import datetime , timezone
async def current_time () -> str :
"""Get the current real world time."""
return datetime . now ( timezone . utc ). astimezone (). isoformat ()
class Args ( BaseModel ):
name : str = Field ( description = "The name" )
async def greet ( args : Args ) -> str :
"""Greet the name."""
return f"Hello, { args . name } !" 기능의 이름과 문서는 소품의 이름과 설명으로 사용됩니다. Pydantic의 Field 에서 Args에 대한 설명을 제공 할 수도 있습니다. 예외 템플릿은 함수가 오류가 발생할 때 응답을 렌더링하는 데 사용됩니다.
custom 소품
소품이 사용될 때 custom 소품이 사용자 정의 소품 클래스를 호출합니다.
scenes :
talking :
characters :
ai assistant :
props :
- type : custom
path : module_name:CustomProp
custom_config : value # module_name.py
from typing import Any , Self
from pydantic import BaseModel
from operagents . prop import Prop
from operagents . config import CustomPropConfig
class CustomProp ( Prop ):
"""The description of the prop"""
params : BaseModel | None
"""The parameters of the prop"""
@ classmethod
def from_config ( cls , config : CustomPropConfig ) -> Self :
return cls ()
async def call ( self , params : BaseModel | None ) -> Any :
return "" Hooks를 사용하면 특정 타임 라인 이벤트가 발생할 때 사용자 정의 코드를 실행할 수 있습니다. hooks 섹션은 후크 목록이며, 각 후크는 후크 유형과 후크 구성이있는 사전입니다. 기본적으로 Operagents는 hooks 섹션을 변경하지 않는 한 summary 후크를 활성화합니다.
summary 후크
summary 후크는 에이전트에게 전화하여 세션이 종료 될 때 세션을 요약합니다. 요약 할 에이전트 이름을 선택적으로 지정할 수 있습니다.
hooks :
- type : summary
agent_names :
- Mike
- John custom 후크
특정 타임 라인 이벤트가 발생하면 custom 후크가 사용자 정의 후크 클래스를 호출합니다.
hooks :
- type : custom
path : module_name:CustomHook
custom_config : value # module_name.py
from typing import Self
from operagents . hook import Hook
from operagents . timeline import Timeline
from operagents . config import CustomHookConfig
from operagents . timeline . event import (
TimelineEventEnd ,
TimelineEventStart ,
TimelineEventSessionAct ,
TimelineEventSessionEnd ,
TimelineEventSessionStart ,
)
class CustomHook ( Hook ):
@ classmethod
def from_config ( cls , config : CustomHookConfig ) -> Self :
return cls ()
async def on_timeline_start (
self , timeline : Timeline , event : TimelineEventStart
):
"""Called when the timeline is started."""
pass
async def on_timeline_end (
self , timeline : Timeline , event : TimelineEventEnd
):
"""Called when the timeline is ended."""
pass
async def on_timeline_session_start (
self , timeline : Timeline , event : TimelineEventSessionStart
):
"""Called when a session is started."""
pass
async def on_timeline_session_end (
self , timeline : Timeline , event : TimelineEventSessionEnd
):
"""Called when a session is ended."""
pass
async def on_timeline_session_act (
self , timeline : Timeline , event : TimelineEventSessionAct
):
"""Called when a character acts in a session."""
pass 후크 클래스에는 on_timeline_<event_type> 형식의 메소드가 포함될 수 있으며, 여기서 <event_type> 는 타임 라인 이벤트의 유형입니다.
오페라 인들은 오페라를 쉽게 실행하기위한 명령 줄 도구를 제공합니다. 다음 명령으로 오페라를 실행할 수 있습니다.
operagents run config.yaml 디버그 로그를 보려면 --log-level 옵션을 설정할 수 있습니다.
operagents run --log-level DEBUG config.yaml 더 많은 명령과 옵션을 운영 operagents --help 실행하여 찾을 수 있습니다.
프로그래밍 방식으로 오페라를 실행하려면 opera.run 함수를 사용할 수 있습니다.
import asyncio
from pathlib import Path
import yaml
from operagents . opera import Opera
from operagents . log import setup_logging
from operagents . config import OperagentsConfig
async def main ():
# if you want to setup the default logging for operagents
setup_logging ( "INFO" )
# load the opera from config file
opera = Opera . from_config (
OperagentsConfig . model_validate (
yaml . safe_load ( Path ( "./config.yaml" ). read_text ( encoding = "utf-8" ))
)
)
finish_state = await opera . run ()
if __name__ == "__main__" :
asyncio . run ( main ()) cd examples/chatbot
env OPENAI_API_KEY=sk-xxx OPENAI_BASE_URL=https://api.openai.com/v1 operagents run --log-level DEBUG config.yamlCodespaces (Dev Container)에서 개방 :
또는 개발 환경을 로컬로 설치하십시오.
poetry install && poetry run pre-commit install