cleaned up code

This commit is contained in:
nicole pardal 2025-09-23 21:34:22 -07:00 committed by ParthSareen
parent 91593f8a35
commit 01eb25a71c
2 changed files with 27 additions and 48 deletions

View File

@ -9,10 +9,7 @@ from ollama import Client
def main() -> None:
api_key = os.getenv('OLLAMA_API_KEY')
if not api_key:
raise RuntimeError('OLLAMA_API_KEY is required to run this example')
client = Client(host='https://ollama.com', headers={'Authorization': f'Bearer {api_key}'})
client = Client()
browser = Browser(initial_state=None, client=client)
# Tool schemas
@ -65,7 +62,7 @@ def main() -> None:
def browser_search(query: str, topn: int = 10) -> str:
return browser.search(query=query, topn=topn)['pageText']
def browser_open(id: int | str = -1, cursor: int = -1, loc: int = -1, num_lines: int = -1) -> str:
def browser_open(id: int | str | None = None, cursor: int = -1, loc: int = -1, num_lines: int = -1) -> str:
return browser.open(id=id, cursor=cursor, loc=loc, num_lines=num_lines)['pageText']
def browser_find(pattern: str, cursor: int = -1, **_: Any) -> str:
@ -76,9 +73,11 @@ def main() -> None:
'browser.open': browser_open,
'browser.find': browser_find,
}
query = 'What is Ollama.com?'
print('Prompt:', query, '\n')
messages: List[Dict[str, Any]] = [{'role': 'user', 'content': query}]
messages: List[Dict[str, Any]] = [{'role': 'user', 'content': 'When did Ollama announce the new engine?'}]
print('----- Prompt:', messages[0]['content'], '\n')
while True:
resp = client.chat(
@ -88,11 +87,11 @@ def main() -> None:
think=True,
)
if getattr(resp.message, 'thinking', None):
if resp.message.thinking:
print('Thinking:\n========\n')
print(resp.message.thinking + '\n')
if getattr(resp.message, 'content', None):
if resp.message.content:
print('Response:\n========\n')
print(resp.message.content + '\n')

View File

@ -117,15 +117,8 @@ class Browser:
def _join_lines_with_numbers(self, lines: List[str]) -> str:
result = []
had_zero = False
for i, line in enumerate(lines):
if i == 0:
result.append('L0:')
had_zero = True
if had_zero:
result.append(f'L{i + 1}: {line}')
else:
result.append(f'L{i}: {line}')
result.append(f'L{i}: {line}')
return '\n'.join(result)
def _wrap_lines(self, text: str, width: int = 80) -> List[str]:
@ -182,18 +175,9 @@ class Browser:
if num_lines <= 0:
txt = self._join_lines_with_numbers(lines[loc:])
data = self.state.get_data()
if len(txt) > data.view_tokens:
max_chars_per_token = 128
upper_bound = min((data.view_tokens + 1) * max_chars_per_token, len(txt))
segment = txt[:upper_bound]
approx_tokens = len(segment) / 4
if approx_tokens > data.view_tokens:
end_idx = min(data.view_tokens * 4, len(txt))
num_lines = segment[:end_idx].count('\n') + 1
else:
num_lines = total_lines
else:
num_lines = total_lines
chars_per_token = 4
max_chars = min(data.view_tokens * chars_per_token, len(txt))
num_lines = txt[:max_chars].count('\n') + 1
return min(loc + num_lines, total_lines)
def _display_page(self, page: Page, cursor: int, loc: int, num_lines: int) -> str:
@ -214,15 +198,8 @@ class Browser:
header += f'**viewing lines [{loc} - {end_loc - 1}] of {total_lines - 1}**\n\n'
body_lines = []
had_zero = False
for i in range(loc, end_loc):
if i == 0:
body_lines.append('L0:')
had_zero = True
if had_zero:
body_lines.append(f'L{i + 1}: {page.lines[i]}')
else:
body_lines.append(f'L{i}: {page.lines[i]}')
body_lines.append(f'L{i}: {page.lines[i]}')
return header + '\n'.join(body_lines)
@ -240,7 +217,6 @@ class Browser:
tb = []
tb.append('')
tb.append('URL: ')
tb.append('# Search Results')
tb.append('')
@ -415,15 +391,6 @@ class Browser:
state = self.get_state()
page: Optional[Page] = None
if cursor >= 0:
if cursor >= len(state.page_stack):
cursor = max(0, len(state.page_stack) - 1)
page = self._page_from_stack(state.page_stack[cursor])
else:
if state.page_stack:
page = self._page_from_stack(state.page_stack[-1])
if isinstance(id, str):
url = id
if url in state.url_to_page:
@ -450,6 +417,19 @@ class Browser:
page_text = self._display_page(new_page, cursor, loc, num_lines)
return {'state': self.get_state(), 'pageText': cap_tool_content(page_text)}
# Resolve current page from stack only if needed (int id or no id)
page: Optional[Page] = None
if cursor >= 0:
if state.page_stack:
if cursor >= len(state.page_stack):
cursor = max(0, len(state.page_stack) - 1)
page = self._page_from_stack(state.page_stack[cursor])
else:
page = None
else:
if state.page_stack:
page = self._page_from_stack(state.page_stack[-1])
if isinstance(id, int):
if not page:
raise RuntimeError('No current page to resolve link from')