最新バージョンをインストールして:
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コマンドラインツールでオペラを実行することです。
次の基本コンテンツを使用してconfig.yamlファイルを作成します。
# yaml-language-server: $schema=https://operagents.yyydl.top/schemas/config.schema.json
agents :
opening_scene : " "
scenes :最初の行は、YAML言語サーバーに指定されたURLのスキーマを使用するように指示するコメントです。これにより、エディターのオートコンプリートと検証が可能になります。
スキーマは、使用しているOperagentsフレームワークのバージョンに関連しています。 URLは、 https://operagents.yyydl.top/schemas/config-<version>.schema.json > 0.0.1の形式です。ここで、 <version>フレームワークのバージョンです。バージョンが指定されていない場合、最新の(マスター)バージョンが使用されます。
エージェントとシーン設定を作成する前に、テンプレートの構成について学ぶ必要があります。
Operagentsはテンプレートを使用して、言語モデルのコンテキスト入力を生成します。テンプレートは、ジンジャ形式の文字列です。 Languationモデルへの入力を制御するために、提供されたコンテキストVaraiblesを備えた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キーを使用して、バックエンドタイプとその構成を指定できます。
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抽象クラスを実装するカスタムバックエンドクラスのオブジェクトパスを提供することにより、バックエンドをカスタマイズすることもできます。
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 Key(オプション)を使用して、キャラクターの小道具を定義できます。詳細については、Prop Configを参照してください。
シーンの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タイプは、再生する次のシーンを予測するためにモデルを指定するために使用されます。仕上げフラグが見つからない場合、またはシーン名が見つからない場合、キュロントシーンは引き続き再生されます。
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の1つのパラメーターを受信します。
# 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の引数も1つの引数もありません。
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 } !"関数の名前とDocstringは、プロップの名前と説明として使用されることに注意してください。また、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セクションはフックのリストで、各フックはフックタイプとフック構成を備えた辞書です。デフォルトでは、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は、オペラを簡単に実行するためのコマンドラインツールを提供します。次のコマンドでオペラを実行できます。
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コンテナ)で開く:
または、開発環境をローカルにインストールします。
poetry install && poetry run pre-commit install