Show HN: Code Claude Code
标题:Show HN: 使用 Code 实现 Claude 代码功能
Navigation Menu
Toggle navigation Sign in
- Product
- GitHub Copilot Write better code with AI
- GitHub Advanced Security Find and fix vulnerabilities
- Actions Automate any workflow
- Codespaces Instant dev environments
- Issues Plan and track work
- Code Review Manage code changes
- Discussions Collaborate outside of code
- Code Search Find more, search less Explore
- Why GitHub
- All features
- Documentation
- GitHub Skills
- Blog
- Solutions By company size
- Resources Topics
- Open Source
- Enterprise
- Pricing
Search or jump to...
Search code, repositories, users, issues, pull requests...
Search Clear Search syntax tips
Provide feedback
We read every piece of feedback, and take your input very seriously. Include my email address so I can be contacted Cancel Submit feedback
Saved searches
Use saved searches to filter your results more quickly
Name Query To see all available qualifiers, see our documentation. Cancel Create saved search Sign in Sign up Appearance settings Reseting focus You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session. Dismiss alert {{ message }} RVCA212 / **codesys ** Public
- Notifications You must be signed in to change notification settings
- Fork 0
- Star 6
6 stars 0 forks Branches Tags Activity Star Notifications You must be signed in to change notification settings
Additional navigation options
RVCA212/codesys
main BranchesTags Go to file Code
Folders and files
Name| Name| Last commit message| Last commit date
---|---|---|---
Latest commit
History
6 Commits
codesys| codesys
examples| examples
.gitignore| .gitignore
README.md| README.md
advanced.py| advanced.py
example.py| example.py
plan_and_execute.py| plan_and_execute.py
pyproject.toml| pyproject.toml
setup.py| setup.py
View all files
Repository files navigation
codesys SDK
一个用于与 Claude CLI 工具交互的 Python SDK。
Installation
pip install codesys
Requirements
- Python 3.8+
- 必须安装 Claude CLI 工具,并且它需要在你的 PATH 环境变量中可用,同时需要设置好你的 API 密钥。
Quick Start
from codesys import Agent
# 使用一个工作目录初始化
agent = Agent(working_dir="/Users/seansullivan/lmsys-sdk/")
# 运行 Claude 并使用 prompt,自动打印流式输出
lines = agent.run("""/init""", stream=True)
Practical Use:
我发现使用这个 SDK 最有效的方法是模仿我实际使用 Claude 代码的工作流程,我发现这种方法非常有效。 工作流程很简单:通过探索代码库来计划任务,然后实现该计划。
#!/usr/bin/env python3
import argparse
import os
from codesys import Agent
# 硬编码的默认值 - 如果需要,可以直接在代码中修改这些值
DEFAULT_WORKING_DIR = os.getcwd() # 默认使用当前工作目录
DEFAULT_USER_MESSAGE = "Your default task message here" # 替换成你的默认消息
def generate_plan(working_dir, user_message):
"""根据用户消息在 plan.md 文件中生成一个计划。"""
prompt = f'''
给定以下任务,在 plan.md 文件中生成一个计划:
<task>
{user_message}
</task>
鉴于这个任务,探索代码库,并创建一个用于实现该任务的计划,保存到 plan.md 文件中。 ultrathink
'''
Agent(working_dir=working_dir).run(prompt, stream=True)
def execute_plan(working_dir):
"""执行 plan.md 中制定的计划。"""
prompt = '''
实现 plan.md 文件中制定的任务: ultrathink
'''
Agent(working_dir=working_dir).run(prompt, stream=True)
def main():
parser = argparse.ArgumentParser(description='根据任务生成并执行计划。')
parser.add_argument('--working-dir', '-w', help='Agent 的工作目录')
parser.add_argument('--message', '-m', help='用于生成计划的任务消息')
args = parser.parse_args()
# 如果提供了命令行参数,则使用命令行参数,否则使用硬编码的默认值
working_dir = args.working_dir if args.working_dir else DEFAULT_WORKING_DIR
user_message = args.message if args.message else DEFAULT_USER_MESSAGE
print(f"Working directory: {working_dir}")
print(f"Generating plan for task: {user_message}")
generate_plan(working_dir, user_message)
print("Executing plan from plan.md")
execute_plan(working_dir)
if __name__ == "__main__":
main()
Features
- 简单的 Claude CLI 工具接口
- 支持所有 Claude CLI 选项
- 自动或手动流式输出
- 可定制的工具访问权限
API Reference
Agent Class
Agent(working_dir=None, allowed_tools=None)
Parameters:
working_dir
(str, optional): Claude 使用的工作目录。默认为当前目录。allowed_tools
(list, optional): 允许 Claude 使用的工具列表。默认为 ["Edit", "Bash", "Write"]。
Methods
run
run(prompt, stream=False, output_format=None, additional_args=None, auto_print=True)
使用指定的 prompt 运行 Claude。 Parameters:
prompt
(str): 发送到 Claude 的 prompt。stream
(bool): 如果为 True,则处理流式输出。如果为 False,则返回完整的输出。output_format
(str, optional): 可选的输出格式(例如,"stream-json")。additional_args
(dict, optional): 传递给 Claude CLI 的其他参数。auto_print
(bool): 如果为 True 并且 stream=True,则自动打印输出。如果为 False,则需要手动处理流式传输。
Returns:
- 如果
stream=False
: 返回作为字符串的完整输出。 - 如果
stream=True
并且auto_print=False
: 返回一个 subprocess.Popen 对象,用于手动流式传输。 - 如果
stream=True
并且auto_print=True
: 自动打印输出,并将收集到的行作为列表返回。
run_with_tools
run_with_tools(prompt, tools, stream=False, auto_print=True)
使用特定的允许工具运行 Claude。 Parameters:
prompt
(str): 发送到 Claude 的 prompt。tools
(list): 允许 Claude 使用的工具列表。stream
(bool): 如果为 True,则处理流式输出。auto_print
(bool): 如果为 True 并且 stream=True,则自动打印输出。
Returns:
- 如果
stream=False
: 返回作为字符串的完整输出。 - 如果
stream=True
并且auto_print=False
: 返回一个 subprocess.Popen 对象。 - 如果
stream=True
并且auto_print=True
: 自动打印输出,并返回收集到的行。
Example: Automatic Streaming
from codesys import Agent
agent = Agent()
# 这将逐行自动打印输出
lines = agent.run("Generate a short story", stream=True)
Example: Manual Streaming with JSON parsing
from codesys import Agent
import json
agent = Agent()
process = agent.run("Generate a short story", stream=True, output_format="stream-json", auto_print=False)
for line in process.stdout:
if line.strip():
try:
data = json.loads(line)
print(data.get("content", ""))
except json.JSONDecodeError:
print(f"Error parsing JSON: {line}")
Examples
from codesys import Agent
# 使用一个工作目录初始化
agent = Agent(working_dir="/Users/seansullivan/lmsys-sdk/")
# 运行 Claude 并使用 prompt,自动打印流式输出
lines = agent.run("create another example of example1_custom_tools.py which shows how to use read only tools. note the source code of the sdk in codesys/agent.py", stream=True)
"""
Example 1: Customizing tools during initialization
This example demonstrates how to initialize an Agent with only specific tools.
"""
from codesys import Agent
# Initialize with only specific tools
restricted_agent = Agent(
working_dir="./",
allowed_tools=["Edit", "Write", "View"] # Only allow editing, writing files and viewing
) # Implementation in agent.py lines 19-39
print(f"Agent initialized with tools: {restricted_agent.allowed_tools}")
from codesys import Agent
# Initialize with default tools
agent = Agent(working_dir="./") # Implementation in agent.py lines 19-39
print(f"Default tools: {agent.allowed_tools}")
# Run with only specific tools for one operation
bash_only_response = agent.run_with_tools(
prompt="List files in the current directory",
tools=["Bash"], # Only allow Bash for this specific run
stream=False
) # Implementation in agent.py lines 132-155
print(f"Tools after run_with_tools: {agent.allowed_tools} # Original tools are restored")
"""
Example 3: Manual handling of streaming output
This example demonstrates how to manually handle streaming output from the agent.
"""
from codesys import Agent
import json
import time
# Initialize an agent
agent = Agent(working_dir="./")
# Get a process for streaming manually
process = agent.run(
prompt="Explain what an LLM Agent is in 3 sentences",
stream=True,
auto_print=False # Don't auto-print, we'll handle the output manually
) # Implementation in agent.py lines 41-96 (stream=True, auto_print=False path)
print("Streaming output manually, processing each line:")
for i, line in enumerate(process.stdout):
# Parse the JSON line
try:
data = json.loads(line)
# Do something with each piece of output
print(f"Line {i+1}: {data.get('content', '')}")
except json.JSONDecodeError:
print(f"Raw line: {line}")
# Simulate processing time
time.sleep(0.1)
# Compare with agent.py lines 98-116 (auto-handling of streaming)
"""
Example 4: Using output formats and additional arguments
This example demonstrates how to use different output formats and pass additional arguments.
"""
from codesys import Agent
# Initialize an agent
agent = Agent(working_dir="./")
# Run with custom output format and additional arguments
response = agent.run(
prompt="What can you tell me about this codebase?",
output_format="json", # Request JSON output
additional_args={
"temperature": 0.7, # Set temperature
"max-tokens": 500, # Limit output tokens
"silent": True # Suppress progress output
}
) # Implementation in agent.py lines 41-70 (output_format handling), 74-80 (additional_args)
print(f"Response type: {type(response)}")
print("First 100 characters of response:", response[:100] if isinstance(response, str) else "Not a string")
License
CodeSYS
About
No description, website, or topics provided.
Resources
Stars
Watchers
Forks
Releases
No releases published
Packages 0
No packages published
Languages
Footer
Footer navigation
You can’t perform that action at this time.