Skip to main content
This page documents all publicly exposed functions and types in the Raysurfer SDK. Every type is defined down to primitive fields.

High-Level Client

RaysurferClient

Drop-in replacement for Claude Agent SDK’s ClaudeSDKClient.
from raysurfer import RaysurferClient
from claude_agent_sdk import ClaudeAgentOptions

options = ClaudeAgentOptions(
    allowed_tools=["Read", "Write", "Bash"],
    system_prompt="You are a helpful assistant.",
)

async with RaysurferClient(options) as client:
    await client.query("Your task here")
    async for msg in client.response():
        print(msg)

Constructor Parameters

PythonRaysurferClient(options, workspace_id=None, debug=False):
ParameterTypeDescription
optionsClaudeAgentOptionsStandard Claude Agent SDK options
workspace_idstringWorkspace ID for per-customer isolation (Pro or Enterprise)
debugbooleanEnable debug logging
TypeScriptnew RaysurferClient(options) where options is a single object:
ParameterTypeDescription
allowedToolsstring[]Allowed Claude tools
systemPromptstringSystem prompt
modelstringClaude model ID
workspaceIdstringWorkspace ID for per-customer isolation (Pro or Enterprise)
debugbooleanEnable debug logging

Methods

MethodDescription
query(prompt)Send a query with automatic cache retrieval
response()Async generator yielding response messages (Python only)

Low-Level API Client

RaySurfer / AsyncRaySurfer

from raysurfer import RaySurfer, AsyncRaySurfer

# Sync client
client = RaySurfer(api_key="your_api_key")

# Async client
async with AsyncRaySurfer(api_key="your_api_key") as client:
    result = await client.search(task="Fetch GitHub repos")

Constructor Options

OptionTypeDescription
api_key / apiKeystringYour Raysurfer API key
base_url / baseUrlstringAPI base URL (optional)
timeoutnumberRequest timeout in seconds/ms
organization_id / organizationIdstringOrganization ID for team/enterprise namespacing
workspace_id / workspaceIdstringWorkspace ID for per-customer namespacing (Pro or Enterprise)
snips_desired / snipsDesired"company" | "client"Scope of private snippets
public_snips / publicSnipsbooleanInclude community public snippets

Search for cached code snippets by task description.
result = client.search(
    task="Fetch GitHub trending repos",
    top_k=5,
    min_verdict_score=0.3,
    prefer_complete=True,
)

for match in result.matches:
    print(f"{match.code_block.name}: {match.score}")
    print(f"  File: {match.filename}")
    print(f"  Source: {match.code_block.source[:80]}...")

Parameters

ParameterTypeDefaultDescription
taskstringrequiredNatural language task description (any length)
top_k / topKnumber5Maximum number of results
min_verdict_score / minVerdictScorenumber0.3Minimum quality score filter
prefer_complete / preferCompletebooleanfalsePrefer longer/more complete implementations
input_schema / inputSchemaobjectnullOptional input schema filter

Returns: SearchResponse

Queries can be any length, but shorter queries (under 200 characters) give the best accuracy and speed. Longer queries are automatically rephrased into multiple shorter searches and merged, which adds latency and may reduce precision.
LLM prompt augmentation: The legacy convenience method get_code_files() / getCodeFiles() wraps search() and returns an add_to_llm_prompt string. Use search() directly for full control over results.

upload

Upload a code file from an execution for future reuse.
from raysurfer.types import FileWritten

file = FileWritten(path="fetch_repos.py", content="def fetch(): ...")

# Let Raysurfer AI vote (default behavior)
result = client.upload(
    task="Fetch GitHub trending repos",
    file_written=file,
    succeeded=True,
    execution_logs="Fetched 10 trending repos successfully",
)

# Or provide your own vote (AI voting is automatically skipped)
result = client.upload(
    task="Fetch GitHub trending repos",
    file_written=file,
    succeeded=True,
    user_vote=1,  # 1 = thumbs up, -1 = thumbs down
)

print(f"Stored {result.code_blocks_stored} code blocks")

Parameters

ParameterTypeDefaultDescription
taskstringrequiredThe task that was executed
file_written / fileWrittenFileWrittenrequiredThe file created during execution
succeededbooleanrequiredWhether the task completed successfully
use_raysurfer_ai_voting / useRaysurferAiVotingbooleantrueLet Raysurfer AI vote on stored blocks. Ignored when user_vote is provided.
user_vote / userVoteint | nullnullUser-provided vote: 1 for thumbs up, -1 for thumbs down. When provided, AI voting is automatically skipped.
vote_source / voteSource"ai" | "human" | nullnullExplicitly sets the vote source. When omitted, user_vote defaults to "human" and AI voting defaults to "ai".
vote_count / voteCountint | null1Number of votes to apply. Useful for pre-seeding community votes.
execution_logs / executionLogsstring | nullnullCaptured stdout/stderr for vote context
dependenciesdict[str, str] / Record<string, string>nullPackage dependencies with versions (e.g., {"pandas": "2.1.0"})

Returns: SubmitExecutionResultResponse

When use_raysurfer_ai_voting is true (the default) and no user_vote is provided, each newly stored code block is automatically evaluated by Raysurfer’s AI. If you provide a user_vote, AI voting is skipped entirely — your vote is applied directly.

upload_bulk_code_snips / uploadBulkCodeSnips

Bulk upload prompts, logs, and code files for sandboxed grading.
from raysurfer.types import FileWritten, LogFile

files = [
    FileWritten(path="app.py", content="def main(): ..."),
    FileWritten(path="utils.py", content="def helper(): ..."),
]

logs = [
    LogFile(path="logs/run.log", content="Task completed", encoding="utf-8"),
]

# Let Raysurfer AI grade each file (default behavior)
result = client.upload_bulk_code_snips(
    prompts=["Build a CLI tool", "Add CSV support"],
    files_written=files,
    log_files=logs,
)

# Or provide your own votes (AI grading is automatically skipped)
result = client.upload_bulk_code_snips(
    prompts=["Build a CLI tool", "Add CSV support"],
    files_written=files,
    log_files=logs,
    user_votes={
        "app.py": 1,     # thumbs up
        "utils.py": -1,  # thumbs down
    },
)

Parameters

ParameterTypeDefaultDescription
promptsstring[]requiredOrdered list of raw user prompts
files_written / filesWrittenFileWritten[]requiredCode files to store and grade
log_files / logFilesLogFile[]nullLog files (any format; use encoding: "base64" for binary)
use_raysurfer_ai_voting / useRaysurferAiVotingbooleantrueLet Raysurfer AI grade and vote on stored blocks. Ignored when user_votes is provided.
user_votes / userVotesdict[str, int] | nullnullDict of filename to vote (1 = thumbs up, -1 = thumbs down). When provided, AI grading is automatically skipped.
vote_source / voteSource"ai" | "human" | nullnullExplicitly sets the vote source. When omitted, user_votes defaults to "human" and AI voting defaults to "ai".
vote_count / voteCountint | null1Number of votes to apply per file. Useful for pre-seeding community votes.

Returns: BulkExecutionResultResponse


delete

Delete a snippet and all its associated data (vectors, retrieval logs, votes).
# Delete by ID
result = client.delete(snippet_id="cb_abc123")

# Or delete by name
result = client.delete(snippet_id="weather_fetcher.py")

print(f"Deleted {result.deleted_count} snippet(s)")

Parameters

ParameterTypeDefaultDescription
snippet_id / snippetIdstringrequiredThe ID or name of the snippet to delete
workspace_id / workspaceIdstringnullOverride client-level workspace ID

Returns: DeleteResponse


vote_code_snip / voteCodeSnip

Vote on whether a cached code snippet was useful. This triggers background voting on the backend.
client.vote_code_snip(
    task="Fetch GitHub trending repos",
    code_block_id="abc123",
    code_block_name="github_fetcher",
    code_block_description="Fetches trending repos",
    succeeded=True,
)

Returns: VoteCodeSnipResponse

Voting is triggered automatically by upload when use_raysurfer_ai_voting is true (the default), and also by the high-level RaysurferClient. Use vote_code_snip directly only for voting on cached blocks after reuse.

Response Types

SearchResponse

Returned by search().
FieldTypeDescription
matchesSearchMatch[]Matching code blocks with scoring
total_found / totalFoundintTotal matches found
cache_hit / cacheHitbooleanWhether results were served from cache

SubmitExecutionResultResponse

Returned by upload().
FieldTypeDescription
successbooleanWhether the operation succeeded
code_blocks_stored / codeBlocksStoredintNumber of code blocks stored
messagestringHuman-readable status message
snippet_name / snippetNamestring | nullName assigned to the stored snippet

BulkExecutionResultResponse

Returned by upload_bulk_code_snips().
FieldTypeDescription
successbooleanWhether the operation succeeded
code_blocks_stored / codeBlocksStoredintNumber of code blocks stored
votes_queued / votesQueuedintNumber of votes queued for AI grading
messagestringHuman-readable status message
status_url / statusUrlstring | nullURL to check grading status (if applicable)

DeleteResponse

Returned by delete().
FieldTypeDescription
successbooleanWhether the operation succeeded
deleted_count / deletedCountintNumber of snippets deleted
messagestringHuman-readable status message

VoteCodeSnipResponse

Returned by vote_code_snip().
FieldTypeDescription
successbooleanWhether the operation succeeded
vote_pending / votePendingbooleanWhether the vote is being processed asynchronously
messagestringHuman-readable status message

Data Types

SearchMatch

A single result from search(). Contains a full CodeBlock plus a relevance score.
FieldTypeDescription
code_block / codeBlockCodeBlockThe matched code block with full source and metadata
scorefloatOverall relevance score (0–1)
thumbs_up / thumbsUpintTotal positive votes on this code block
thumbs_down / thumbsDownintTotal negative votes on this code block
filenamestringGenerated filename (e.g., "github_fetcher.py")
languagestringProgramming language (e.g., "python", "typescript")
entrypointstringMain function name to call (e.g., "fetch_repos")
dependenciesdict[str, str] / Record<string, string>Package name to version (e.g., {"httpx": "0.27.0"})

CodeBlock

A stored code block with full metadata. Nested inside SearchMatch.
FieldTypeDescription
idstringUnique identifier (UUID)
namestringHuman-readable name (e.g., "GitHub Trending Fetcher")
descriptionstringWhat the code does
sourcestringThe full source code
entrypointstringMain function/method name
languagestringProgramming language
language_version / languageVersionstring | nullLanguage version (e.g., "3.12")
dependenciesdict[str, str] / Record<string, string>Package name to version (e.g., {"pandas": "2.1.0"})
tagsstring[]Searchable tags (e.g., ["github", "api"])
capabilitiesstring[]What the code can do (e.g., ["http_requests", "json_parsing"])
input_schema / inputSchemaJsonDict / Record<string, JsonValue>JSON schema describing expected inputs
output_schema / outputSchemaJsonDict / Record<string, JsonValue>JSON schema describing outputs
example_queries / exampleQueriesstring[] | nullExample task queries this code is good for
created_at / createdAtstring | nullISO 8601 timestamp of creation
updated_at / updatedAtstring | nullISO 8601 timestamp of last update

Input Types

FileWritten

A file created during agent execution. Used by upload() and upload_bulk_code_snips().
FieldTypeDescription
pathstringFile path (e.g., "fetch_repos.py")
contentstringFull file contents as a string

LogFile

A log file for bulk grading. Used by upload_bulk_code_snips().
FieldTypeDefaultDescription
pathstringrequiredFile path (e.g., "logs/run.log")
contentstringrequiredFile contents (plain text or base64-encoded binary)
encoding"utf-8" | "base64""utf-8"Content encoding. Use "base64" for binary files.
content_type / contentTypestring | nullnullMIME type (e.g., "application/json")

Enums

ExecutionState

Technical execution outcome.
ValueDescription
COMPLETEDExecution finished successfully
ERROREDExecution threw an error
TIMED_OUTExecution exceeded time limit
CANCELLEDExecution was cancelled

AgentVerdict

Agent’s judgment on execution quality.
ValueDescription
THUMBS_UPExecution was useful
THUMBS_DOWNExecution was not useful
PENDINGNot yet evaluated

SnipsDesired

Scope of private snippets for retrieval.
ValueRequired TierDescription
companyPRO or ENTERPRISEOrganization-level snippets
clientPRO or ENTERPRISEClient workspace snippets (requires workspace_id)

Exceptions

Both SDKs include built-in retry logic with exponential backoff for transient failures (429, 5xx, network errors). You don’t need to implement your own retry logic for these cases.

RaySurferError

Base exception for all Raysurfer errors.
PropertyTypeDescription
messagestringError message

APIError

Raised when the API returns an error response. Extends RaySurferError.
PropertyTypeDescription
messagestringError message
status_code / statusCodeintHTTP status code

AuthenticationError

Raised when the API key is invalid or missing. Extends RaySurferError.
PropertyTypeDescription
messagestringError message

CacheUnavailableError

Raised when the cache backend is unreachable or returns an unexpected error. Extends RaySurferError.
PropertyTypeDescription
messagestringError message

RateLimitError

Raised when the API rate limit is exceeded. The SDK automatically retries with exponential backoff before raising this error. Extends RaySurferError.
PropertyTypeDescription
messagestringError message
retry_after / retryAfterint | nullSeconds until rate limit resets

ValidationError

Raised when request validation fails. Extends RaySurferError.
PropertyTypeDescription
messagestringError message
fieldstring | nullThe field that failed validation