|
| 1 | +from typing import Dict, Any, List, Optional, AsyncIterator |
| 2 | + |
| 3 | +from jupyter_ai.personas.base_persona import BasePersona, PersonaDefaults |
| 4 | +from jupyterlab_chat.models import Message |
| 5 | + |
| 6 | +from claude_code_sdk import ( |
| 7 | + query, ClaudeCodeOptions, |
| 8 | + Message, SystemMessage, AssistantMessage, ResultMessage, |
| 9 | + TextBlock, ToolUseBlock |
| 10 | +) |
| 11 | + |
| 12 | + |
| 13 | +OMIT_INPUT_ARGS = ['content'] |
| 14 | + |
| 15 | +TOOL_PARAM_MAPPING = { |
| 16 | + 'Task': 'description', |
| 17 | + 'Bash': 'command', |
| 18 | + 'Glob': 'pattern', |
| 19 | + 'Grep': 'pattern', |
| 20 | + 'LS': 'path', |
| 21 | + 'Read': 'file_path', |
| 22 | + 'Edit': 'file_path', |
| 23 | + 'MultiEdit': 'file_path', |
| 24 | + 'Write': 'file_path', |
| 25 | + 'NotebookRead': 'notebook_path', |
| 26 | + 'NotebookWrite': 'notebook_path', |
| 27 | + 'WebFetch': 'url', |
| 28 | + 'WebSearch': 'query', |
| 29 | +} |
| 30 | + |
| 31 | +PROMPT_TEMPLATE = """ |
| 32 | +{{body}} |
| 33 | +
|
| 34 | +The user has selected the following files as attachements: |
| 35 | +
|
| 36 | +
|
| 37 | +""" |
| 38 | + |
| 39 | +def input_dict_to_str(d: Dict[str, Any]) -> str: |
| 40 | + """Convert input dictionary to string representation, omitting specified args.""" |
| 41 | + args = [] |
| 42 | + for k, v in d.items(): |
| 43 | + if k not in OMIT_INPUT_ARGS: |
| 44 | + args.append(f"{k}={v}") |
| 45 | + return ', '.join(args) |
| 46 | + |
| 47 | + |
| 48 | +def tool_to_str(block: ToolUseBlock, persona_instance=None) -> str: |
| 49 | + """Convert a ToolUseBlock to its string representation.""" |
| 50 | + results = [] |
| 51 | + |
| 52 | + if block.name == 'TodoWrite': |
| 53 | + block_id = block.id if hasattr(block, 'id') else str(hash(str(block.input))) |
| 54 | + |
| 55 | + if persona_instance and block_id in persona_instance._printed_todowrite_blocks: |
| 56 | + return "" |
| 57 | + |
| 58 | + if persona_instance: |
| 59 | + persona_instance._printed_todowrite_blocks.add(block_id) |
| 60 | + |
| 61 | + todos = block.input.get('todos', []) |
| 62 | + results.append('TodoWrite()') |
| 63 | + for todo in todos: |
| 64 | + content = todo.get('content') |
| 65 | + if content: |
| 66 | + results.append(f"* {content}") |
| 67 | + elif block.name in TOOL_PARAM_MAPPING: |
| 68 | + param_key = TOOL_PARAM_MAPPING[block.name] |
| 69 | + param_value = block.input.get(param_key, '') |
| 70 | + results.append(f"🛠️ {block.name}({param_value})") |
| 71 | + else: |
| 72 | + results.append(f"🛠️ {block.name}({input_dict_to_str(block.input)})") |
| 73 | + |
| 74 | + return '\n'.join(results) |
| 75 | + |
| 76 | + |
| 77 | +def claude_message_to_str(message, persona_instance=None) -> Optional[str]: |
| 78 | + """Convert a Claude Message to a string by extracting text content.""" |
| 79 | + text_parts = [] |
| 80 | + for block in message.content: |
| 81 | + if isinstance(block, TextBlock): |
| 82 | + text_parts.append(block.text) |
| 83 | + elif isinstance(block, ToolUseBlock): |
| 84 | + tool_str = tool_to_str(block, persona_instance) |
| 85 | + if tool_str: |
| 86 | + text_parts.append(tool_str) |
| 87 | + else: |
| 88 | + text_parts.append(str(block)) |
| 89 | + return '\n'.join(text_parts) if text_parts else None |
| 90 | + |
| 91 | + |
| 92 | +class ClaudeCodePersona(BasePersona): |
| 93 | + """Claude Code persona for Jupyter AI integration.""" |
| 94 | + |
| 95 | + def __init__(self, *args, **kwargs): |
| 96 | + super().__init__(*args, **kwargs) |
| 97 | + self._printed_todowrite_blocks = set() |
| 98 | + |
| 99 | + @property |
| 100 | + def defaults(self) -> PersonaDefaults: |
| 101 | + """Return default configuration for the Claude Code persona.""" |
| 102 | + return PersonaDefaults( |
| 103 | + name="Claude", |
| 104 | + avatar_path="/files/.jupyter/claude.svg", |
| 105 | + description="Claude Code", |
| 106 | + system_prompt="...", |
| 107 | + ) |
| 108 | + |
| 109 | + async def _process_response_message(self, message_iterator) -> AsyncIterator[str]: |
| 110 | + """Process response messages from Claude Code SDK.""" |
| 111 | + async for response_message in message_iterator: |
| 112 | + self.log.info(str(response_message)) |
| 113 | + if isinstance(response_message, AssistantMessage): |
| 114 | + msg_str = claude_message_to_str(response_message, self) |
| 115 | + if msg_str is not None: |
| 116 | + yield msg_str + '\n\n' |
| 117 | + |
| 118 | + def _generate_prompt(self, message: Message) -> str: |
| 119 | + attachment_ids = message.attachments |
| 120 | + if attachment_ids is None: |
| 121 | + return message.body |
| 122 | + attachments = self.ychat.get_attachments() |
| 123 | + msg_attachments = (attachments[aid] for aid in attachment_ids) |
| 124 | + prompt = f"{message.body}\n\n" |
| 125 | + prompt += f"The user has attached the following files and may be referring to them in the above prompt:\n\n" |
| 126 | + for a in msg_attachments: |
| 127 | + if a['type'] == 'file': |
| 128 | + prompt += f"file_path={a['value']}" |
| 129 | + elif a['type'] == 'notebook': |
| 130 | + cells = list(c['id'] for c in a['cells']) |
| 131 | + # Claude Code's notebook tools only understand a single cell_id |
| 132 | + prompt += f"notebook_path={a['value']} cell_id={cells[0]}" |
| 133 | + self.log.info(prompt) |
| 134 | + return prompt |
| 135 | + |
| 136 | + async def process_message(self, message: Message) -> None: |
| 137 | + """Process incoming message and stream Claude Code response.""" |
| 138 | + self._printed_todowrite_blocks.clear() |
| 139 | + async_gen = None |
| 140 | + prompt = self._generate_prompt(message) |
| 141 | + try: |
| 142 | + async_gen = query( |
| 143 | + prompt=prompt, |
| 144 | + options=ClaudeCodeOptions( |
| 145 | + max_turns=20, |
| 146 | + cwd=self.get_workspace_dir(), |
| 147 | + permission_mode='bypassPermissions' |
| 148 | + ) |
| 149 | + ) |
| 150 | + await self.stream_message(self._process_response_message(async_gen)) |
| 151 | + except Exception as e: |
| 152 | + self.log.error(f"Error in process_message: {e}") |
| 153 | + await self.send_message(f"Sorry, I have had an internal error while working on that: {e}") |
| 154 | + finally: |
| 155 | + if async_gen is not None: |
| 156 | + await async_gen.aclose() |
0 commit comments