Skip to content

Commit 80279e9

Browse files
committed
cleaned up code
1 parent 0ecfb1f commit 80279e9

File tree

2 files changed

+27
-48
lines changed

2 files changed

+27
-48
lines changed

examples/gpt-oss-browser-tool.py

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,7 @@
99

1010

1111
def main() -> None:
12-
api_key = os.getenv('OLLAMA_API_KEY')
13-
if not api_key:
14-
raise RuntimeError('OLLAMA_API_KEY is required to run this example')
15-
client = Client(host='https://ollama.com', headers={'Authorization': f'Bearer {api_key}'})
12+
client = Client()
1613
browser = Browser(initial_state=None, client=client)
1714

1815
# Tool schemas
@@ -65,7 +62,7 @@ def main() -> None:
6562
def browser_search(query: str, topn: int = 10) -> str:
6663
return browser.search(query=query, topn=topn)['pageText']
6764

68-
def browser_open(id: int | str = -1, cursor: int = -1, loc: int = -1, num_lines: int = -1) -> str:
65+
def browser_open(id: int | str | None = None, cursor: int = -1, loc: int = -1, num_lines: int = -1) -> str:
6966
return browser.open(id=id, cursor=cursor, loc=loc, num_lines=num_lines)['pageText']
7067

7168
def browser_find(pattern: str, cursor: int = -1, **_: Any) -> str:
@@ -76,9 +73,11 @@ def browser_find(pattern: str, cursor: int = -1, **_: Any) -> str:
7673
'browser.open': browser_open,
7774
'browser.find': browser_find,
7875
}
76+
query = 'What is Ollama.com?'
77+
print('Prompt:', query, '\n')
78+
79+
messages: List[Dict[str, Any]] = [{'role': 'user', 'content': query}]
7980

80-
messages: List[Dict[str, Any]] = [{'role': 'user', 'content': 'When did Ollama announce the new engine?'}]
81-
print('----- Prompt:', messages[0]['content'], '\n')
8281

8382
while True:
8483
resp = client.chat(
@@ -88,11 +87,11 @@ def browser_find(pattern: str, cursor: int = -1, **_: Any) -> str:
8887
think=True,
8988
)
9089

91-
if getattr(resp.message, 'thinking', None):
90+
if resp.message.thinking:
9291
print('Thinking:\n========\n')
9392
print(resp.message.thinking + '\n')
94-
95-
if getattr(resp.message, 'content', None):
93+
94+
if resp.message.content:
9695
print('Response:\n========\n')
9796
print(resp.message.content + '\n')
9897

examples/gpt_oss_browser_tool_helper.py

Lines changed: 18 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -117,15 +117,8 @@ def _page_from_stack(self, url: str) -> Page:
117117

118118
def _join_lines_with_numbers(self, lines: List[str]) -> str:
119119
result = []
120-
had_zero = False
121120
for i, line in enumerate(lines):
122-
if i == 0:
123-
result.append('L0:')
124-
had_zero = True
125-
if had_zero:
126-
result.append(f'L{i + 1}: {line}')
127-
else:
128-
result.append(f'L{i}: {line}')
121+
result.append(f'L{i}: {line}')
129122
return '\n'.join(result)
130123

131124
def _wrap_lines(self, text: str, width: int = 80) -> List[str]:
@@ -182,18 +175,9 @@ def _get_end_loc(self, loc: int, num_lines: int, total_lines: int, lines: List[s
182175
if num_lines <= 0:
183176
txt = self._join_lines_with_numbers(lines[loc:])
184177
data = self.state.get_data()
185-
if len(txt) > data.view_tokens:
186-
max_chars_per_token = 128
187-
upper_bound = min((data.view_tokens + 1) * max_chars_per_token, len(txt))
188-
segment = txt[:upper_bound]
189-
approx_tokens = len(segment) / 4
190-
if approx_tokens > data.view_tokens:
191-
end_idx = min(data.view_tokens * 4, len(txt))
192-
num_lines = segment[:end_idx].count('\n') + 1
193-
else:
194-
num_lines = total_lines
195-
else:
196-
num_lines = total_lines
178+
chars_per_token = 4
179+
max_chars = min(data.view_tokens * chars_per_token, len(txt))
180+
num_lines = txt[:max_chars].count('\n') + 1
197181
return min(loc + num_lines, total_lines)
198182

199183
def _display_page(self, page: Page, cursor: int, loc: int, num_lines: int) -> str:
@@ -214,15 +198,8 @@ def _display_page(self, page: Page, cursor: int, loc: int, num_lines: int) -> st
214198
header += f'**viewing lines [{loc} - {end_loc - 1}] of {total_lines - 1}**\n\n'
215199

216200
body_lines = []
217-
had_zero = False
218201
for i in range(loc, end_loc):
219-
if i == 0:
220-
body_lines.append('L0:')
221-
had_zero = True
222-
if had_zero:
223-
body_lines.append(f'L{i + 1}: {page.lines[i]}')
224-
else:
225-
body_lines.append(f'L{i}: {page.lines[i]}')
202+
body_lines.append(f'L{i}: {page.lines[i]}')
226203

227204
return header + '\n'.join(body_lines)
228205

@@ -240,7 +217,6 @@ def _build_search_results_page_collection(self, query: str, results: Dict[str, A
240217

241218
tb = []
242219
tb.append('')
243-
tb.append('URL: ')
244220
tb.append('# Search Results')
245221
tb.append('')
246222

@@ -415,15 +391,6 @@ def open(
415391

416392
state = self.get_state()
417393

418-
page: Optional[Page] = None
419-
if cursor >= 0:
420-
if cursor >= len(state.page_stack):
421-
cursor = max(0, len(state.page_stack) - 1)
422-
page = self._page_from_stack(state.page_stack[cursor])
423-
else:
424-
if state.page_stack:
425-
page = self._page_from_stack(state.page_stack[-1])
426-
427394
if isinstance(id, str):
428395
url = id
429396
if url in state.url_to_page:
@@ -450,6 +417,19 @@ def open(
450417
page_text = self._display_page(new_page, cursor, loc, num_lines)
451418
return {'state': self.get_state(), 'pageText': cap_tool_content(page_text)}
452419

420+
# Resolve current page from stack only if needed (int id or no id)
421+
page: Optional[Page] = None
422+
if cursor >= 0:
423+
if state.page_stack:
424+
if cursor >= len(state.page_stack):
425+
cursor = max(0, len(state.page_stack) - 1)
426+
page = self._page_from_stack(state.page_stack[cursor])
427+
else:
428+
page = None
429+
else:
430+
if state.page_stack:
431+
page = self._page_from_stack(state.page_stack[-1])
432+
453433
if isinstance(id, int):
454434
if not page:
455435
raise RuntimeError('No current page to resolve link from')

0 commit comments

Comments
 (0)