본문 바로가기
WIKI 기술 지식 베이스

Python SDK

원문 보기 위키 갱신

AgentFS Python SDK는 영속 저장소를 갖춘 AI 에이전트를 만들기 위한 비동기 인터페이스를 제공해요.

출처: 문서

본문

설치

pip install agentfs-sdk

빠른 시작

import asyncio
from agentfs_sdk import AgentFS, AgentFSOptions

async def main():
    # Open an agent filesystem
    agent = await AgentFS.open(AgentFSOptions(id='my-agent'))

    # Use key-value store
    await agent.kv.set('config', {'debug': True})
    config = await agent.kv.get('config')

    # Use filesystem
    await agent.fs.write_file('/notes.txt', 'Hello, AgentFS!')
    content = await agent.fs.read_file('/notes.txt')

    # Track tool calls
    call_id = await agent.tools.start('search', {'query': 'Python'})
    await agent.tools.success(call_id, {'results': ['result1']})

    await agent.close()

asyncio.run(main())

파일시스템 열기

에이전트 ID로 열기

.agentfs/{id}.db에 데이터베이스를 만들어요:

agent = await AgentFS.open(AgentFSOptions(id='my-agent'))

경로로 열기

사용자 지정 데이터베이스 경로를 지정하기:

agent = await AgentFS.open(AgentFSOptions(path='./data/mydb.db'))

컨텍스트 매니저

데이터베이스를 자동으로 닫아줘요:

async with await AgentFS.open(AgentFSOptions(id='my-agent')) as agent:
    await agent.kv.set('key', 'value')
    # Database is closed when exiting

키-값 저장소

JSON 직렬화를 지원하는 간단한 키-값 저장소예요.

값 설정하기

await agent.kv.set('user:123', {'name': 'Alice', 'age': 30})
await agent.kv.set('counter', 42)
await agent.kv.set('active', True)

값 가져오기

user = await agent.kv.get('user:123')
# Returns None if key doesn't exist

키 나열하기

# List all keys with prefix
keys = await agent.kv.list('user:')
# Returns: ['user:123', 'user:456', ...]

키 삭제하기

await agent.kv.delete('user:123')

파일시스템

POSIX 스타일의 파일시스템 작업이에요.

파일 쓰기

부모 디렉터리를 자동으로 만들어 줘요:

await agent.fs.write_file('/data/config.json', '{"key": "value"}')

# Write bytes
await agent.fs.write_file('/data/image.png', image_bytes)

파일 읽기

# Read as string (default)
content = await agent.fs.read_file('/data/config.json')

# Read as bytes
data = await agent.fs.read_file('/data/image.png', encoding=None)

디렉터리 나열하기

entries = await agent.fs.readdir('/data')
# Returns: ['config.json', 'image.png', ...]

파일 통계 조회하기

stats = await agent.fs.stat('/data/config.json')
print(f"Size: {stats.size} bytes")
print(f"Modified: {stats.mtime}")
print(f"Is file: {stats.is_file()}")
print(f"Is directory: {stats.is_dir()}")

파일 삭제하기

await agent.fs.delete_file('/data/config.json')

디렉터리 만들기

await agent.fs.mkdir('/data/subdir')

도구 호출

디버깅과 감사를 위해 도구/함수 호출을 기록하고 분석해요.

시작과 완료

# Start a tool call
call_id = await agent.tools.start('search', {'query': 'Python'})

# ... perform the operation ...

# Mark as successful
await agent.tools.success(call_id, {'results': ['result1', 'result2']})

# Or mark as failed
await agent.tools.error(call_id, 'Connection timeout')

완료된 호출 기록하기

시작과 종료 시각을 알고 있다면:

await agent.tools.record(
    name='search',
    started_at=1234567890.0,
    completed_at=1234567892.0,
    parameters={'query': 'Python'},
    result={'results': ['result1']}
)

도구 호출 조회하기

# Get by name
calls = await agent.tools.get_by_name('search', limit=10)

# Get recent calls
recent = await agent.tools.get_recent(since=1234567890.0)

# Get by ID
call = await agent.tools.get(42)

통계 가져오기

stats = await agent.tools.get_stats()
for stat in stats:
    print(f"{stat.name}:")
    print(f"  Total calls: {stat.total_calls}")
    print(f"  Successful: {stat.successful}")
    print(f"  Failed: {stat.failed}")
    print(f"  Avg duration: {stat.avg_duration_ms:.2f}ms")

전체 예제

import asyncio
import time
from agentfs_sdk import AgentFS, AgentFSOptions

async def main():
    async with await AgentFS.open(AgentFSOptions(id='demo-agent')) as agent:
        # Store configuration
        await agent.kv.set('agent:config', {
            'model': 'gpt-4',
            'temperature': 0.7
        })

        # Create a research document
        research = """
        # Research Notes

        ## Topic: AgentFS

        AgentFS provides persistent storage for AI agents.
        """

        await agent.fs.write_file('/research/agentfs.md', research)

        # Track a simulated tool call
        call_id = await agent.tools.start('web_search', {
            'query': 'AgentFS documentation'
        })

        # Simulate some work
        await asyncio.sleep(0.1)

        await agent.tools.success(call_id, {
            'results_count': 5,
            'top_result': 'https://docs.turso.tech/agentfs'
        })

        # List what we created
        files = await agent.fs.readdir('/research')
        print(f"Files: {files}")

        # Get tool stats
        stats = await agent.tools.get_stats()
        for stat in stats:
            print(f"{stat.name}: {stat.total_calls} calls")

asyncio.run(main())

API 참조

AgentFS

메서드 설명
AgentFS.open(options) 에이전트 파일시스템 열기 또는 생성
agent.close() 데이터베이스 연결 닫기
agent.kv 키-값 저장소 인터페이스
agent.fs 파일시스템 인터페이스
agent.tools 도구 호출 인터페이스

AgentFSOptions

속성 타입 설명
id str 에이전트 식별자 (.agentfs/{id}.db 생성)
path str 사용자 지정 데이터베이스 경로

KvStore

메서드 설명
set(key, value) 값 저장
get(key) 값 조회
delete(key) 키 삭제
list(prefix) 접두어로 키 나열

Filesystem

메서드 설명
write_file(path, content) 파일 내용 쓰기
read_file(path, encoding) 파일 내용 읽기
readdir(path) 디렉터리 항목 나열
stat(path) 파일 메타데이터 조회
delete_file(path) 파일 삭제
mkdir(path) 디렉터리 생성

ToolCalls

메서드 설명
start(name, params) 호출 추적 시작
success(id, result) 호출을 성공으로 표시
error(id, message) 호출을 실패로 표시
record(...) 완료된 호출 기록
get(id) ID로 호출 조회
get_by_name(name, limit) 도구 이름으로 조회
get_recent(since) 최근 호출 조회
get_stats() 사용 통계 조회

더 알아보기 (Learn more)