njbrake commited on
Commit
6b470cd
Β·
1 Parent(s): 36f3637

Sync with SSF

Browse files
Files changed (42) hide show
  1. CODE_OF_CONDUCT.md +0 -76
  2. CONTRIBUTING.md +0 -45
  3. Dockerfile +2 -2
  4. LICENSE +0 -201
  5. README.md +4 -97
  6. demo/constants.py β†’ constants.py +0 -0
  7. demo/Dockerfile +0 -21
  8. demo/README.md +0 -20
  9. docs/api.md +0 -13
  10. docs/assets/custom.css +0 -0
  11. docs/customization.md +0 -22
  12. docs/future-features-contributions.md +0 -28
  13. docs/getting-started.md +0 -9
  14. docs/images/Blueprint-logo-black-flavicon.png +0 -0
  15. docs/images/Blueprint-logo-black.png +0 -0
  16. docs/images/Blueprint-logo-white.png +0 -0
  17. docs/index.md +0 -41
  18. docs/step-by-step-guide.md +0 -27
  19. examples/multi_agent.yaml +0 -31
  20. examples/single_agent_user_confirmation.yaml +0 -32
  21. examples/single_agent_with_tools.yaml +0 -31
  22. images/Blueprint-logo-black.png +0 -0
  23. images/Blueprint-logo-white.png +0 -0
  24. mkdocs.yml +0 -53
  25. demo/pickers.py β†’ pickers.py +0 -0
  26. pyproject.toml +0 -61
  27. demo/requirements.txt β†’ requirements.txt +0 -0
  28. src/surf_spot_finder/__init__.py +0 -0
  29. src/surf_spot_finder/cli.py +0 -106
  30. src/surf_spot_finder/config.py +0 -233
  31. src/surf_spot_finder/instructions/__init__.py +0 -0
  32. src/surf_spot_finder/instructions/openai.py +0 -22
  33. src/surf_spot_finder/instructions/shared.py +0 -0
  34. src/surf_spot_finder/instructions/smolagents.py +0 -176
  35. src/surf_spot_finder/no_framework.py +0 -109
  36. src/surf_spot_finder/tools/__init__.py +0 -10
  37. src/surf_spot_finder/tools/openmeteo.py +0 -114
  38. src/surf_spot_finder/tools/openstreetmap.py +0 -92
  39. demo/streamlit_app.py β†’ streamlit_app.py +0 -0
  40. tests/unit/tools/test_unit_openmeteo.py +0 -106
  41. tests/unit/tools/test_unit_openstreetmap.py +0 -74
  42. demo/utils.py β†’ utils.py +0 -0
CODE_OF_CONDUCT.md DELETED
@@ -1,76 +0,0 @@
1
- # Contributor Covenant Code of Conduct
2
-
3
- ## Our Pledge
4
-
5
- In the interest of fostering an open and welcoming environment, we as
6
- contributors and maintainers pledge to making participation in our project and
7
- our community a harassment-free experience for everyone, regardless of age, body
8
- size, disability, ethnicity, sex characteristics, gender identity and expression,
9
- level of experience, education, socio-economic status, nationality, personal
10
- appearance, race, religion, or sexual identity and orientation.
11
-
12
- ## Our Standards
13
-
14
- Examples of behavior that contributes to creating a positive environment
15
- include:
16
-
17
- * Using welcoming and inclusive language
18
- * Being respectful of differing viewpoints and experiences
19
- * Gracefully accepting constructive criticism
20
- * Focusing on what is best for the community
21
- * Showing empathy towards other community members
22
-
23
- Examples of unacceptable behavior by participants include:
24
-
25
- * The use of sexualized language or imagery and unwelcome sexual attention or
26
- advances
27
- * Trolling, insulting/derogatory comments, and personal or political attacks
28
- * Public or private harassment
29
- * Publishing others' private information, such as a physical or electronic
30
- address, without explicit permission
31
- * Other conduct which could reasonably be considered inappropriate in a
32
- professional setting
33
-
34
- ## Our Responsibilities
35
-
36
- Project maintainers are responsible for clarifying the standards of acceptable
37
- behavior and are expected to take appropriate and fair corrective action in
38
- response to any instances of unacceptable behavior.
39
-
40
- Project maintainers have the right and responsibility to remove, edit, or
41
- reject comments, commits, code, wiki edits, issues, and other contributions
42
- that are not aligned to this Code of Conduct, or to ban temporarily or
43
- permanently any contributor for other behaviors that they deem inappropriate,
44
- threatening, offensive, or harmful.
45
-
46
- ## Scope
47
-
48
- This Code of Conduct applies both within project spaces and in public spaces
49
- when an individual is representing the project or its community. Examples of
50
- representing a project or community include using an official project e-mail
51
- address, posting via an official social media account, or acting as an appointed
52
- representative at an online or offline event. Representation of a project may be
53
- further defined and clarified by project maintainers.
54
-
55
- ## Enforcement
56
-
57
- Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
- reported by contacting the team at mozilla.ai. All
59
- complaints will be reviewed and investigated and will result in a response that
60
- is deemed necessary and appropriate to the circumstances. The project team is
61
- obligated to maintain confidentiality with regard to the reporter of an incident.
62
- Further details of specific enforcement policies may be posted separately.
63
-
64
- Project maintainers who do not follow or enforce the Code of Conduct in good
65
- faith may face temporary or permanent repercussions as determined by other
66
- members of the project's leadership.
67
-
68
- ## Attribution
69
-
70
- This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
- available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
72
-
73
- [homepage]: https://www.contributor-covenant.org
74
-
75
- For answers to common questions about this code of conduct, see
76
- https://www.contributor-covenant.org/faq
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
CONTRIBUTING.md DELETED
@@ -1,45 +0,0 @@
1
- # Contributing to mozilla.ai Blueprints
2
-
3
- Thank you for your interest in contributing to this repository! This project is part of the Blueprints initiative, which empowers developers to integrate AI capabilities into their projects using open-source tools and models.
4
-
5
- We welcome all kinds of contributions, from improving customization, to extending capabilities, to fixing bugs. Whether you’re an experienced developer or just starting out, your support is highly appreciated.
6
-
7
- ---
8
-
9
- ## **How to Contribute**
10
-
11
- ### **Customize for your use-case or Extend It** πŸ”§
12
- - Fork this repo and customize it for your own use-case or even extend its capabilities.
13
- - We'd love to see what you've built! Provided your fork is public, we may reach out to you to feature your work on the [Blueprints Hub](https://developer-hub.mozilla.ai/) .
14
-
15
- ### **Browse Existing Issues** πŸ”
16
- - Check the Issues page to see if there are any tasks you'd like to tackle.
17
- - Look for issues labeled **`good first issue`** if you're new to the projectβ€”they're a great place to start.
18
-
19
- ### **Report Issues** πŸ›
20
- - Found a bug? Open a Bug Report by clicking on 'New Issue'
21
- - Provide as much detail as possible, including the steps to reproduce the issue and Expected vs. actual behavior
22
-
23
- ### **Suggest Features** πŸš€
24
- - Have an idea for improving the Blueprint? Open a Feature Request by clicking on 'New Issue'
25
- - Share why the feature is important and any alternative solutions you’ve considered.
26
-
27
- ### **Submit Pull Requests** πŸ’»
28
- - Fork the repository and create a new branch for your changes.
29
- - Install [pre-commit](https://pre-commit.com/) to ensure the code is formatted and standardized correctly, by running `pip install pre-commit` and then `pre-commit install`.
30
- - Ensure your branch is up-to-date with the main branch before submitting the PR
31
- - Please follow the PR template, adding as much detail as possible, including how to test the changes
32
-
33
- ---
34
-
35
- ### **Guidelines for Contributions**
36
-
37
- **Coding Standards**
38
- - Follow PEP 8 for Python formatting.
39
- - Use clear variable and function names and add comments to improve readability.
40
-
41
- **Testing**
42
- - Test changes locally and in GitHub Codespaces to ensure functionality.
43
-
44
- **Documentation**
45
- - Update docs for changes to functionality and maintain consistency with existing docs.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Dockerfile CHANGED
@@ -9,8 +9,8 @@ RUN apt-get update && apt-get install -y \
9
  git \
10
  && rm -rf /var/lib/apt/lists/*
11
 
12
- COPY demo/requirements.txt ./
13
- COPY demo/ ./demo/
14
 
15
  RUN pip3 install -r requirements.txt
16
 
 
9
  git \
10
  && rm -rf /var/lib/apt/lists/*
11
 
12
+ COPY requirements.txt ./
13
+ COPY . ./demo/
14
 
15
  RUN pip3 install -r requirements.txt
16
 
LICENSE DELETED
@@ -1,201 +0,0 @@
1
- Apache License
2
- Version 2.0, January 2004
3
- http://www.apache.org/licenses/
4
-
5
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
-
7
- 1. Definitions.
8
-
9
- "License" shall mean the terms and conditions for use, reproduction,
10
- and distribution as defined by Sections 1 through 9 of this document.
11
-
12
- "Licensor" shall mean the copyright owner or entity authorized by
13
- the copyright owner that is granting the License.
14
-
15
- "Legal Entity" shall mean the union of the acting entity and all
16
- other entities that control, are controlled by, or are under common
17
- control with that entity. For the purposes of this definition,
18
- "control" means (i) the power, direct or indirect, to cause the
19
- direction or management of such entity, whether by contract or
20
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
- outstanding shares, or (iii) beneficial ownership of such entity.
22
-
23
- "You" (or "Your") shall mean an individual or Legal Entity
24
- exercising permissions granted by this License.
25
-
26
- "Source" form shall mean the preferred form for making modifications,
27
- including but not limited to software source code, documentation
28
- source, and configuration files.
29
-
30
- "Object" form shall mean any form resulting from mechanical
31
- transformation or translation of a Source form, including but
32
- not limited to compiled object code, generated documentation,
33
- and conversions to other media types.
34
-
35
- "Work" shall mean the work of authorship, whether in Source or
36
- Object form, made available under the License, as indicated by a
37
- copyright notice that is included in or attached to the work
38
- (an example is provided in the Appendix below).
39
-
40
- "Derivative Works" shall mean any work, whether in Source or Object
41
- form, that is based on (or derived from) the Work and for which the
42
- editorial revisions, annotations, elaborations, or other modifications
43
- represent, as a whole, an original work of authorship. For the purposes
44
- of this License, Derivative Works shall not include works that remain
45
- separable from, or merely link (or bind by name) to the interfaces of,
46
- the Work and Derivative Works thereof.
47
-
48
- "Contribution" shall mean any work of authorship, including
49
- the original version of the Work and any modifications or additions
50
- to that Work or Derivative Works thereof, that is intentionally
51
- submitted to Licensor for inclusion in the Work by the copyright owner
52
- or by an individual or Legal Entity authorized to submit on behalf of
53
- the copyright owner. For the purposes of this definition, "submitted"
54
- means any form of electronic, verbal, or written communication sent
55
- to the Licensor or its representatives, including but not limited to
56
- communication on electronic mailing lists, source code control systems,
57
- and issue tracking systems that are managed by, or on behalf of, the
58
- Licensor for the purpose of discussing and improving the Work, but
59
- excluding communication that is conspicuously marked or otherwise
60
- designated in writing by the copyright owner as "Not a Contribution."
61
-
62
- "Contributor" shall mean Licensor and any individual or Legal Entity
63
- on behalf of whom a Contribution has been received by Licensor and
64
- subsequently incorporated within the Work.
65
-
66
- 2. Grant of Copyright License. Subject to the terms and conditions of
67
- this License, each Contributor hereby grants to You a perpetual,
68
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
- copyright license to reproduce, prepare Derivative Works of,
70
- publicly display, publicly perform, sublicense, and distribute the
71
- Work and such Derivative Works in Source or Object form.
72
-
73
- 3. Grant of Patent License. Subject to the terms and conditions of
74
- this License, each Contributor hereby grants to You a perpetual,
75
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
- (except as stated in this section) patent license to make, have made,
77
- use, offer to sell, sell, import, and otherwise transfer the Work,
78
- where such license applies only to those patent claims licensable
79
- by such Contributor that are necessarily infringed by their
80
- Contribution(s) alone or by combination of their Contribution(s)
81
- with the Work to which such Contribution(s) was submitted. If You
82
- institute patent litigation against any entity (including a
83
- cross-claim or counterclaim in a lawsuit) alleging that the Work
84
- or a Contribution incorporated within the Work constitutes direct
85
- or contributory patent infringement, then any patent licenses
86
- granted to You under this License for that Work shall terminate
87
- as of the date such litigation is filed.
88
-
89
- 4. Redistribution. You may reproduce and distribute copies of the
90
- Work or Derivative Works thereof in any medium, with or without
91
- modifications, and in Source or Object form, provided that You
92
- meet the following conditions:
93
-
94
- (a) You must give any other recipients of the Work or
95
- Derivative Works a copy of this License; and
96
-
97
- (b) You must cause any modified files to carry prominent notices
98
- stating that You changed the files; and
99
-
100
- (c) You must retain, in the Source form of any Derivative Works
101
- that You distribute, all copyright, patent, trademark, and
102
- attribution notices from the Source form of the Work,
103
- excluding those notices that do not pertain to any part of
104
- the Derivative Works; and
105
-
106
- (d) If the Work includes a "NOTICE" text file as part of its
107
- distribution, then any Derivative Works that You distribute must
108
- include a readable copy of the attribution notices contained
109
- within such NOTICE file, excluding those notices that do not
110
- pertain to any part of the Derivative Works, in at least one
111
- of the following places: within a NOTICE text file distributed
112
- as part of the Derivative Works; within the Source form or
113
- documentation, if provided along with the Derivative Works; or,
114
- within a display generated by the Derivative Works, if and
115
- wherever such third-party notices normally appear. The contents
116
- of the NOTICE file are for informational purposes only and
117
- do not modify the License. You may add Your own attribution
118
- notices within Derivative Works that You distribute, alongside
119
- or as an addendum to the NOTICE text from the Work, provided
120
- that such additional attribution notices cannot be construed
121
- as modifying the License.
122
-
123
- You may add Your own copyright statement to Your modifications and
124
- may provide additional or different license terms and conditions
125
- for use, reproduction, or distribution of Your modifications, or
126
- for any such Derivative Works as a whole, provided Your use,
127
- reproduction, and distribution of the Work otherwise complies with
128
- the conditions stated in this License.
129
-
130
- 5. Submission of Contributions. Unless You explicitly state otherwise,
131
- any Contribution intentionally submitted for inclusion in the Work
132
- by You to the Licensor shall be under the terms and conditions of
133
- this License, without any additional terms or conditions.
134
- Notwithstanding the above, nothing herein shall supersede or modify
135
- the terms of any separate license agreement you may have executed
136
- with Licensor regarding such Contributions.
137
-
138
- 6. Trademarks. This License does not grant permission to use the trade
139
- names, trademarks, service marks, or product names of the Licensor,
140
- except as required for reasonable and customary use in describing the
141
- origin of the Work and reproducing the content of the NOTICE file.
142
-
143
- 7. Disclaimer of Warranty. Unless required by applicable law or
144
- agreed to in writing, Licensor provides the Work (and each
145
- Contributor provides its Contributions) on an "AS IS" BASIS,
146
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
- implied, including, without limitation, any warranties or conditions
148
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
- PARTICULAR PURPOSE. You are solely responsible for determining the
150
- appropriateness of using or redistributing the Work and assume any
151
- risks associated with Your exercise of permissions under this License.
152
-
153
- 8. Limitation of Liability. In no event and under no legal theory,
154
- whether in tort (including negligence), contract, or otherwise,
155
- unless required by applicable law (such as deliberate and grossly
156
- negligent acts) or agreed to in writing, shall any Contributor be
157
- liable to You for damages, including any direct, indirect, special,
158
- incidental, or consequential damages of any character arising as a
159
- result of this License or out of the use or inability to use the
160
- Work (including but not limited to damages for loss of goodwill,
161
- work stoppage, computer failure or malfunction, or any and all
162
- other commercial damages or losses), even if such Contributor
163
- has been advised of the possibility of such damages.
164
-
165
- 9. Accepting Warranty or Additional Liability. While redistributing
166
- the Work or Derivative Works thereof, You may choose to offer,
167
- and charge a fee for, acceptance of support, warranty, indemnity,
168
- or other liability obligations and/or rights consistent with this
169
- License. However, in accepting such obligations, You may act only
170
- on Your own behalf and on Your sole responsibility, not on behalf
171
- of any other Contributor, and only if You agree to indemnify,
172
- defend, and hold each Contributor harmless for any liability
173
- incurred by, or claims asserted against, such Contributor by reason
174
- of your accepting any such warranty or additional liability.
175
-
176
- END OF TERMS AND CONDITIONS
177
-
178
- APPENDIX: How to apply the Apache License to your work.
179
-
180
- To apply the Apache License to your work, attach the following
181
- boilerplate notice, with the fields enclosed by brackets "[]"
182
- replaced with your own identifying information. (Don't include
183
- the brackets!) The text should be enclosed in the appropriate
184
- comment syntax for the file format. We also recommend that a
185
- file or class name and description of purpose be included on the
186
- same "printed page" as the copyright notice for easier
187
- identification within third-party archives.
188
-
189
- Copyright [yyyy] [name of copyright owner]
190
-
191
- Licensed under the Apache License, Version 2.0 (the "License");
192
- you may not use this file except in compliance with the License.
193
- You may obtain a copy of the License at
194
-
195
- http://www.apache.org/licenses/LICENSE-2.0
196
-
197
- Unless required by applicable law or agreed to in writing, software
198
- distributed under the License is distributed on an "AS IS" BASIS,
199
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
- See the License for the specific language governing permissions and
201
- limitations under the License.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
README.md CHANGED
@@ -12,102 +12,9 @@ short_description: Find a surf spot near you
12
  license: apache-2.0
13
  ---
14
 
 
15
 
16
- <p align="center">
17
- <picture>
18
- <!-- When the user prefers dark mode, show the white logo -->
19
- <source media="(prefers-color-scheme: dark)" srcset="./images/Blueprint-logo-white.png">
20
- <!-- When the user prefers light mode, show the black logo -->
21
- <source media="(prefers-color-scheme: light)" srcset="./images/Blueprint-logo-black.png">
22
- <!-- Fallback: default to the black logo -->
23
- <img src="./images/Blueprint-logo-black.png" width="35%" alt="Project logo"/>
24
- </picture>
25
- </p>
26
 
27
- <div align="center">
28
- <p><a href="https://huggingface.co/spaces/mozilla-ai/surf-spot-finder" target="_blank">Huggingface Demo πŸ€—</a></p>
29
-
30
- </div>
31
-
32
-
33
-
34
- Many Large Language Model (LLM) capabilities are unlocked when they are given access to tools and given control of their
35
- own runtime and execution path. However, it's important that as they are given greater capabilities, they are properly
36
- evaluated and controlled.
37
-
38
- In this Blueprint, we demonstrate an AI agent designed for an extremely specific task (some refer to this as a "Vertical Agent")
39
- that is given the web and searching access it needs to find an answer the same way you would find the answer as a human.
40
-
41
- This agent is designed for help in finding the next great surf spot near you: the agent is provided with a location, a distance,
42
- a timestamp, and it's able to independently search and browse the web to recommend the best spot to you along with the
43
- relevant information!
44
-
45
- Although this exact use-case may not be useful to you directly, the framework we provide here is intended to be easily
46
- adapted to the Agent use case you have in mind.
47
-
48
- This implementation uses the [smolagents](https://huggingface.co/docs/smolagents/index) library for Agentic capabilities, alongside
49
- of the increasingly Model Context Protocol (MCP) which allows for a standard access communication standard for a large number of tools.
50
-
51
- πŸ“˜ To explore this project further and discover other Blueprints, visit the [**Blueprints Hub**](https://developer-hub.mozilla.ai/).
52
-
53
- ### Built with
54
- ![Python](https://img.shields.io/badge/Python-3.10%2B-blue)
55
- [![smolagents](https://img.shields.io/badge/Smolagents-%F0%9F%A4%97-yellow)](https://huggingface.co/docs/smolagents/index)
56
-
57
-
58
- ## πŸš€ Quick Start
59
-
60
- ### 1️⃣ Clone the Project
61
- ```bash
62
- git clone https://github.com/mozilla-ai/surf-spot-finder.git
63
- cd surf-spot-finder
64
- ```
65
-
66
- ### 2️⃣ Update submodule and install dependencies
67
- ```bash
68
- pip install -e . # Install root project dependencies
69
- ```
70
-
71
- ### 3️⃣ Run
72
-
73
- ```bash
74
- surf-spot-finder examples/single_agent_with_tools.yaml
75
- ```
76
-
77
- ## How it Works
78
-
79
-
80
- ## Pre-requisites
81
-
82
- - **System requirements**:
83
- - OS: Windows, macOS, or Linux
84
- - Python 3.10 or higher
85
- - Minimum RAM:
86
- - Disk space:
87
-
88
- - **Dependencies**:
89
- - Docker
90
- - Dependencies listed in `pyproject.toml`
91
-
92
- ## Run Tests
93
-
94
- ```bash
95
- pip install -e .[tests]
96
- ```
97
-
98
- ### Unit Tests
99
-
100
- ```bash
101
- pytest
102
- ```
103
-
104
- ## Troubleshooting
105
-
106
-
107
- ## License
108
-
109
- This project is licensed under the Apache 2.0 License. See the [LICENSE](LICENSE) file for details.
110
-
111
- ## Contributing
112
-
113
- Contributions are welcome! To get started, you can check out the [CONTRIBUTING.md](CONTRIBUTING.md) file.
 
12
  license: apache-2.0
13
  ---
14
 
15
+ # Welcome to Streamlit!
16
 
17
+ Edit `/src/streamlit_app.py` to customize this app to your heart's desire. :heart:
 
 
 
 
 
 
 
 
 
18
 
19
+ If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
20
+ forums](https://discuss.streamlit.io).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
demo/constants.py β†’ constants.py RENAMED
File without changes
demo/Dockerfile DELETED
@@ -1,21 +0,0 @@
1
- FROM python:3.12-slim
2
-
3
- WORKDIR /app
4
-
5
- RUN apt-get update && apt-get install -y \
6
- build-essential \
7
- curl \
8
- software-properties-common \
9
- git \
10
- && rm -rf /var/lib/apt/lists/*
11
-
12
- COPY requirements.txt ./
13
- COPY . ./demo/
14
-
15
- RUN pip3 install -r requirements.txt
16
-
17
- EXPOSE 8501
18
-
19
- HEALTHCHECK CMD curl --fail http://localhost:8501/_stcore/health
20
-
21
- ENTRYPOINT ["streamlit", "run", "demo/streamlit_app.py", "--server.port=8501", "--server.address=0.0.0.0"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
demo/README.md DELETED
@@ -1,20 +0,0 @@
1
- ---
2
- title: Surf Spot Finder
3
- emoji: πŸš€
4
- colorFrom: red
5
- colorTo: red
6
- sdk: docker
7
- app_port: 8501
8
- tags:
9
- - streamlit
10
- pinned: false
11
- short_description: Find a surf spot near you
12
- license: apache-2.0
13
- ---
14
-
15
- # Welcome to Streamlit!
16
-
17
- Edit `/src/streamlit_app.py` to customize this app to your heart's desire. :heart:
18
-
19
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
20
- forums](https://discuss.streamlit.io).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
docs/api.md DELETED
@@ -1,13 +0,0 @@
1
- # API Reference
2
-
3
- ::: surf_spot_finder.cli
4
-
5
- ::: surf_spot_finder.config.Config
6
-
7
- ::: surf_spot_finder.no_framework
8
-
9
- ## Tools
10
-
11
- ::: surf_spot_finder.tools.openmeteo
12
-
13
- ::: surf_spot_finder.tools.openstreetmap
 
 
 
 
 
 
 
 
 
 
 
 
 
 
docs/assets/custom.css DELETED
File without changes
docs/customization.md DELETED
@@ -1,22 +0,0 @@
1
- # 🎨 **Customization Guide**
2
-
3
- This Blueprint is designed to be flexible and easily adaptable to your specific needs. This guide will walk you through some key areas you can customize to make the Blueprint your own.
4
-
5
- ---
6
-
7
- ## 🧠 **Changing the Model**
8
-
9
-
10
-
11
- ## πŸ“ **Modifying the system Prompt**
12
-
13
-
14
-
15
- ## πŸ’‘ Other Customization Ideas
16
-
17
- - other ideas..
18
-
19
-
20
- ## 🀝 **Contributing to the Blueprint**
21
-
22
- Want to help improve or extend this Blueprint? Check out the **[Future Features & Contributions Guide](future-features-contributions.md)** to see how you can contribute your ideas, code, or feedback to make this Blueprint even better!
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
docs/future-features-contributions.md DELETED
@@ -1,28 +0,0 @@
1
- # πŸš€ **Future Features & Contributions**
2
-
3
- This Blueprint is an evolving project designed to grow with the help of the open-source community. Whether you’re an experienced developer or just starting, there are many ways you can contribute and help shape the future of this tool.
4
-
5
- ---
6
-
7
- ## 🌟 **How You Can Contribute**
8
-
9
- ### πŸ› οΈ **Enhance the Blueprint**
10
- - Check the [Issues](https://github.com/mozilla-ai/surf-spot-finder/issues) page to see if there are feature requests you'd like to implement
11
- - Refer to our [Contribution Guide](https://github.com/mozilla-ai/surf-spot-finder/blob/main/CONTRIBUTING.md) for more details on contributions
12
-
13
- ### 🎨 **Extensibility Ideas**
14
-
15
- This Blueprint is designed to be a foundation you can build upon. By extending its capabilities, you can open the door to new applications, improve user experience, and adapt the Blueprint to address other use cases. Here are a few ideas for how you can expand its potential:
16
-
17
-
18
- We’d love to see how you can enhance this Blueprint! If you create improvements or extend its capabilities, consider contributing them back to the project so others in the community can benefit from your work. Check out our [Contributions Guide](https://github.com/mozilla-ai/surf-spot-finder/blob/main/CONTRIBUTING.md) to get started!
19
-
20
- ### πŸ’‘ **Share Your Ideas**
21
- Got an idea for how this Blueprint could be improved? You can share your suggestions through [GitHub Discussions](https://github.com/mozilla-ai/surf-spot-finder/discussions).
22
-
23
- ### 🌍 **Build New Blueprints**
24
- This project is part of a larger initiative to create a collection of reusable starter code solutions that use open-source AI tools. If you’re inspired to create your own Blueprint, you can use the [surf-spot-finder](https://github.com/new?template_name=surf-spot-finder&template_owner=mozilla-ai) to get started.
25
-
26
- ---
27
-
28
- Your contributions help make this Blueprint better for everyone πŸŽ‰
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
docs/getting-started.md DELETED
@@ -1,9 +0,0 @@
1
- Get started with this Blueprint using one of the options below:
2
-
3
- ---
4
-
5
- ### **Option 1:**
6
-
7
-
8
-
9
- ### **Option 2:**
 
 
 
 
 
 
 
 
 
 
docs/images/Blueprint-logo-black-flavicon.png DELETED
Binary file (38.7 kB)
 
docs/images/Blueprint-logo-black.png DELETED
Binary file (63.6 kB)
 
docs/images/Blueprint-logo-white.png DELETED
Binary file (53.2 kB)
 
docs/index.md DELETED
@@ -1,41 +0,0 @@
1
- # **Welcome to the Blueprint docs**
2
-
3
- Blueprints are customizable workflows that help developers build AI applications using open-source tools and models
4
-
5
- These docs are your companion to mastering this Blueprint.
6
-
7
- ### Built with
8
- - Python 3.10+
9
- - Tool 1
10
- - Tool 2
11
-
12
-
13
- ---
14
-
15
- ### πŸš€ **Get Started Quickly**
16
- #### _Start building the Blueprint in minutes:_
17
- - **[Getting Started](getting-started.md):** Quick setup and installation instructions.
18
-
19
- ### πŸ” **Understand the System**
20
- #### _Dive deeper into how the Blueprint works:_
21
- - **[Step-by-Step Guide](step-by-step-guide.md):** A detailed breakdown of the system’s design and workflow.
22
- - **[API Reference](api.md):** Explore the technical details of the core modules.
23
-
24
- ### 🎨 **Make It Yours**
25
- #### _Customize the Blueprint to fit your needs:_
26
- - **[Customization Guide](customization.md):** Tailor project parameters to fit your needs
27
-
28
- ### 🌟 **Join the Community**
29
- #### _Help shape the future of Blueprints:_
30
- - **[Future Features & Contributions](future-features-contributions.md):** Learn about exciting upcoming features and how to contribute to the project.
31
-
32
-
33
- Have more questions? Reach out to us on Discord and we'll see how we can help:
34
-
35
- <a target="_blank" href="https://discord.gg/gazz5XDU"><img src="https://dcbadge.limes.pink/api/server/gazz5XDU" alt="" /></a>
36
-
37
- ---
38
-
39
- ## **Why Blueprints?**
40
-
41
- Blueprints are more than starter codeβ€”they’re your gateway to building AI-powered solutions with confidence. With step-by-step guidance, modular design, and open-source tools, we make AI accessible for developers of all skill levels.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
docs/step-by-step-guide.md DELETED
@@ -1,27 +0,0 @@
1
- # **Step-by-Step Guide: How this Blueprint Works**
2
-
3
-
4
- ---
5
-
6
- ## **Overview**
7
-
8
-
9
- ---
10
-
11
- ## **Step 1**
12
-
13
-
14
- ## **Step 2**
15
-
16
-
17
- ## **Step 3**
18
-
19
-
20
-
21
- ## 🎨 **Customizing the Blueprint**
22
-
23
- To better understand how you can tailor this Blueprint to suit your specific needs, please visit the **[Customization Guide](customization.md)**.
24
-
25
- ## 🀝 **Contributing to the Blueprint**
26
-
27
- Want to help improve or extend this Blueprint? Check out the **[Future Features & Contributions Guide](future-features-contributions.md)** to see how you can contribute your ideas, code, or feedback to make this Blueprint even better!
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
examples/multi_agent.yaml DELETED
@@ -1,31 +0,0 @@
1
- main_agent:
2
- name: main_agent
3
- model_id: # optional, will prompt for it if not provided
4
- instructions: >
5
- # System context\n
6
- You are part of a multi-agent system, designed to make agent coordination and execution easy.
7
- Agents uses two primary abstraction: **Agents** and **Handoffs**.
8
- An agent encompasses instructions and tools and can hand off a conversation to another agent when appropriate.
9
- Handoffs are achieved by calling a handoff function, generally named `transfer_to_<agent_name>`.
10
- Transfers between agents are handled seamlessly in the background; do not mention or draw attention to these transfers in your conversation with the user.\n
11
-
12
- managed_agents:
13
-
14
- - name: user-verification-agent
15
- model_id: # optional, will prompt for it if not provided
16
- instructions: Ask users to verify a step, plan or answer.
17
- tools:
18
- - any_agent.tools.ask_user_verification
19
-
20
- - name: general-web-search-agent
21
- model_id: # optional, will prompt for it if not provided
22
- instructions: Search the web and visit webpages to find answers.
23
- tools:
24
- - any_agent.tools.search_web
25
- - any_agent.tools.visit_webpage
26
-
27
- - name: user-communication-agent
28
- model_id: # optional, will prompt for it if not provided
29
- instructions: Communicates to the user
30
- tools:
31
- - any_agent.tools.show_final_output
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
examples/single_agent_user_confirmation.yaml DELETED
@@ -1,32 +0,0 @@
1
-
2
- input_prompt_template: |
3
- According to the forecast, what will be the best spot to surf around {LOCATION},
4
- in a {MAX_DRIVING_HOURS} hour driving radius, at {DATE}?
5
- Find a few options and then discuss it with a friend using the send_console_message any_agent.tools.ask_user_verification
6
- You should recommend some choices to them and then confirm the final selection with him.
7
- Once he gives the final selection, save a detailed description of the weather at the chosen location into a file
8
- named "final_answer.txt". Also save a file called "history.txt" which has a list of your thought process in the choice.
9
-
10
- main_agent:
11
- model_id: # optional, will prompt for it if not provided
12
- tools:
13
- - "surf_spot_finder.tools.driving_hours_to_meters"
14
- - "surf_spot_finder.tools.get_area_lat_lon"
15
- - "surf_spot_finder.tools.get_surfing_spots"
16
- - "surf_spot_finder.tools.get_wave_forecast"
17
- - "surf_spot_finder.tools.get_wind_forecast"
18
- - "any_agent.tools.send_console_message"
19
- - command: "docker"
20
- args:
21
- - "run"
22
- - "-i"
23
- - "--rm"
24
- - "--mount"
25
- - "type=bind,src={{ path_variable }},dst=/projects" # this is the custom part where for demo purposes we will check this in config.py
26
- - "mcp/filesystem"
27
- - "/projects"
28
- tools:
29
- - "read_file"
30
- - "write_file"
31
- - "directory_tree"
32
- - "list_allowed_directories"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
examples/single_agent_with_tools.yaml DELETED
@@ -1,31 +0,0 @@
1
- main_agent:
2
- model_id: # optional, will prompt for it if not provided
3
- tools:
4
- - "surf_spot_finder.tools.driving_hours_to_meters"
5
- - "surf_spot_finder.tools.get_area_lat_lon"
6
- - "surf_spot_finder.tools.get_surfing_spots"
7
- - "surf_spot_finder.tools.get_wave_forecast"
8
- - "surf_spot_finder.tools.get_wind_forecast"
9
- - "any_agent.tools.search_web"
10
- - "any_agent.tools.visit_webpage"
11
-
12
-
13
- evaluation_cases:
14
- - llm_judge: openai/gpt-4.1-mini
15
- checkpoints:
16
- - criteria: "Check if the agent used the get_surfing_spots tool and it succeeded, and that the tool was used before the get_wave_forecast and get_wind_forecast tools"
17
- points: 1
18
- - criteria: "Check if the agent used the get_wave_forecast tool and it succeeded"
19
- points: 1
20
- - criteria: "Check if the agent used the get_wind_forecast tool and it succeeded"
21
- points: 1
22
- - criteria: "Check if the agent used the get_area_lat_lon tool and it succeeded"
23
- points: 1
24
- - criteria: "Check if the agent used the driving_hours_to_meters tool to convert the driving hours to meters and it succeeded"
25
- points: 1
26
- - criteria: "Check if the final answer contains any description about the weather at the chosen location"
27
- points: 1
28
- - criteria: "Check if the final answer contains one of the surf spots found by a call of the get_surfing_spots tool"
29
- points: 1
30
- - criteria: "Check that the agent completed in fewer than 10 steps"
31
- points: 1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
images/Blueprint-logo-black.png DELETED
Binary file (63.6 kB)
 
images/Blueprint-logo-white.png DELETED
Binary file (53.2 kB)
 
mkdocs.yml DELETED
@@ -1,53 +0,0 @@
1
- site_name: Surf Spot Finder
2
-
3
- repo_url: https://github.com/mozilla-ai/surf-spot-finder
4
- repo_name: surf-spot-finder
5
-
6
- nav:
7
- - Home: index.md
8
- - Getting Started: getting-started.md
9
- - Step-by-Step Guide: step-by-step-guide.md
10
- - Customization Guide: customization.md
11
- - API Reference: api.md
12
- - Future Features & Contributions: future-features-contributions.md
13
-
14
- theme:
15
- name: material
16
- palette:
17
- - scheme: default
18
- primary: black
19
- toggle:
20
- icon: material/lightbulb
21
- name: Switch to dark mode
22
- - scheme: slate
23
- primary: grey
24
- toggle:
25
- icon: material/lightbulb-outline
26
- name: Switch to light mode
27
- logo: images/Blueprint-logo-white.png
28
- favicon: images/Blueprint-logo-black-flavicon.png
29
- extra_css:
30
- - assets/custom.css
31
- features:
32
- - content.code.copy
33
- - content.tabs.link
34
-
35
- markdown_extensions:
36
- - pymdownx.highlight:
37
- anchor_linenums: true
38
- line_spans: __span
39
- pygments_lang_class: true
40
- - pymdownx.inlinehilite
41
- - pymdownx.snippets
42
- - pymdownx.superfences
43
- - pymdownx.tabbed:
44
- alternate_style: true
45
-
46
- plugins:
47
- - search
48
- - mkdocstrings:
49
- handlers:
50
- python:
51
- options:
52
- show_root_heading: true
53
- heading_level: 3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
demo/pickers.py β†’ pickers.py RENAMED
File without changes
pyproject.toml DELETED
@@ -1,61 +0,0 @@
1
- [build-system]
2
- requires = ["setuptools>=48", "setuptools_scm[toml]>=6.3.1"]
3
- build-backend = "setuptools.build_meta"
4
-
5
- [project]
6
- name = "surf-spot-finder"
7
- readme = "README.md"
8
- license = {text = "Apache-2.0"}
9
- requires-python = ">=3.11"
10
- dynamic = ["version"]
11
- dependencies = [
12
- "any-agent[all]>=0.12.2",
13
- "fire",
14
- "pydantic",
15
- "pyyaml",
16
- "litellm",
17
- "geocoder>=1.38.1",
18
- "rich>=14.0.0",
19
- ]
20
-
21
- [project.optional-dependencies]
22
- demo = [
23
- "gradio",
24
- "spaces"
25
- ]
26
-
27
- docs = [
28
- "mkdocs",
29
- "mkdocs-material",
30
- "mkdocstrings-python",
31
- ]
32
-
33
- tests = [
34
- "pytest>=8,<9",
35
- "pytest-sugar>=0.9.6",
36
- "debugpy>=1.8.13",
37
- "evaluate>=0.4.3",
38
- ]
39
-
40
- dev = [
41
- "pre-commit>=4.1.0",
42
- "ipykernel>=6.29.5",
43
- "jupyter>=1.1.1",
44
- ]
45
-
46
- [project.urls]
47
- Documentation = "https://mozilla-ai.github.io/surf-spot-finder/"
48
- Issues = "https://github.com/mozilla-ai/surf-spot-finder/issues"
49
- Source = "https://github.com/mozilla-ai/surf-spot-finder"
50
-
51
- [tool.setuptools.packages.find]
52
- exclude = ["tests", "tests.*"]
53
- where = ["src"]
54
- namespaces = false
55
-
56
- [tool.setuptools_scm]
57
-
58
- [project.scripts]
59
- surf-spot-finder = "surf_spot_finder.cli:main"
60
- surf-spot-finder-no-framework = "surf_spot_finder.no_framework:main"
61
- surf-spot-finder-evaluate = "surf_spot_finder.evaluation.main:main"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
demo/requirements.txt β†’ requirements.txt RENAMED
File without changes
src/surf_spot_finder/__init__.py DELETED
File without changes
src/surf_spot_finder/cli.py DELETED
@@ -1,106 +0,0 @@
1
- import datetime
2
- import os
3
- from pathlib import Path
4
-
5
- from any_agent import AgentFramework, AnyAgent, TracingConfig
6
- from any_agent.evaluation.schemas import TraceEvaluationResult
7
- from fire import Fire
8
- from any_agent.logging import logger
9
- from any_agent.evaluation import evaluate
10
-
11
- from surf_spot_finder.config import (
12
- Config,
13
- )
14
-
15
- from surf_spot_finder.instructions.openai import SINGLE_AGENT_SYSTEM_PROMPT
16
- from surf_spot_finder.instructions.smolagents import SYSTEM_PROMPT
17
-
18
-
19
- async def find_surf_spot(
20
- config_file: str | None = None,
21
- ) -> str:
22
- """Find the best surf spot based on the given criteria.
23
-
24
- Args:
25
- config_file: Path to a YAML config file.
26
- See [Config][surf_spot_finder.config.Config]
27
-
28
- """
29
- if config_file is None:
30
- config = Config.from_dict({})
31
- else:
32
- logger.info("Loading %s", config_file)
33
- config = Config.from_yaml(config_file)
34
-
35
- if not config.main_agent.instructions:
36
- if config.framework == AgentFramework.SMOLAGENTS:
37
- config.main_agent.instructions = SYSTEM_PROMPT
38
- elif config.framework == AgentFramework.OPENAI:
39
- config.main_agent.instructions = SINGLE_AGENT_SYSTEM_PROMPT
40
-
41
- logger.info("Loading %s agent", config.framework)
42
- logger.info("Managed agents: %s", config.managed_agents)
43
- agent = await AnyAgent.create_async(
44
- agent_framework=config.framework,
45
- agent_config=config.main_agent,
46
- managed_agents=config.managed_agents,
47
- tracing=TracingConfig(console=True, cost_info=True),
48
- )
49
-
50
- query = config.input_prompt_template.format(
51
- LOCATION=config.location,
52
- MAX_DRIVING_HOURS=config.max_driving_hours,
53
- DATE=config.date,
54
- )
55
- logger.info("Running agent with query:\n%s", query)
56
- agent_trace = await agent.run_async(query)
57
-
58
- logger.info("Final output from agent:\n%s", agent_trace.final_output)
59
-
60
- # dump the trace in the "output" directory
61
- output_dir = "output"
62
- os.makedirs(output_dir, exist_ok=True)
63
- timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
64
- file_path = Path(output_dir) / f"{timestamp}_trace.json"
65
- with open(file_path, "w") as f:
66
- f.write(agent_trace.model_dump_json(indent=2))
67
-
68
- if config.evaluation_cases is not None:
69
- results = []
70
- logger.info("Found evaluation cases, running trace evaluation")
71
- for i, case in enumerate(config.evaluation_cases):
72
- logger.info("Evaluating case: %s", case)
73
- result: TraceEvaluationResult = evaluate(
74
- evaluation_case=case,
75
- trace=agent_trace,
76
- agent_framework=config.framework,
77
- )
78
- for list_of_checkpoints in [
79
- result.checkpoint_results,
80
- result.direct_results,
81
- result.hypothesis_answer_results,
82
- ]:
83
- for checkpoint in list_of_checkpoints:
84
- msg = (
85
- f"Checkpoint: {checkpoint.criteria}\n"
86
- f"\tPassed: {checkpoint.passed}\n"
87
- f"\tReason: {checkpoint.reason}\n"
88
- f"\tScore: {'%d/%d' % (checkpoint.points, checkpoint.points) if checkpoint.passed else '0/%d' % checkpoint.points}"
89
- )
90
- logger.info(msg)
91
- logger.info("==========================")
92
- logger.info("Overall Score: %d%%", 100 * result.score)
93
- logger.info("==========================")
94
- results.append(result)
95
- timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
96
- file_path = Path(output_dir) / f"{timestamp}_eval_case_{i}.json"
97
- with open(file_path, "w") as f:
98
- f.write(result.model_dump_json(indent=2))
99
-
100
-
101
- def main():
102
- Fire(find_surf_spot)
103
-
104
-
105
- if __name__ == "__main__":
106
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/surf_spot_finder/config.py DELETED
@@ -1,233 +0,0 @@
1
- import os
2
- import tempfile
3
- from typing import Annotated
4
- from datetime import datetime, timedelta
5
- from any_agent import AgentFramework
6
- from any_agent.config import AgentConfig
7
- from pydantic import AfterValidator, BaseModel, ConfigDict, FutureDatetime, PositiveInt
8
- import yaml
9
- from rich.prompt import Prompt
10
- from any_agent.logging import logger
11
- from any_agent.evaluation import EvaluationCase
12
- import geocoder
13
- from litellm.litellm_core_utils.get_llm_provider_logic import (
14
- get_llm_provider,
15
- )
16
-
17
- INPUT_PROMPT_TEMPLATE = """
18
- According to the forecast, what will be the best spot to surf around {LOCATION},
19
- in a {MAX_DRIVING_HOURS} hour driving radius,
20
- at {DATE}?"
21
- """.strip()
22
-
23
-
24
- def validate_prompt(value) -> str:
25
- for placeholder in ("{LOCATION}", "{MAX_DRIVING_HOURS}", "{DATE}"):
26
- if placeholder not in value:
27
- raise ValueError(f"prompt must contain {placeholder}")
28
- return value
29
-
30
-
31
- def ask_framework() -> AgentFramework:
32
- """
33
- Ask the user which framework they would like to use. They must select one of the Agent Frameworks
34
- """
35
- frameworks = [framework.name for framework in AgentFramework]
36
- frameworks_str = "\n".join(
37
- [f"{i}: {framework}" for i, framework in enumerate(frameworks)]
38
- )
39
- prompt = f"Select the agent framework to use:\n{frameworks_str}\n"
40
- choice = Prompt.ask(prompt, default="0")
41
- try:
42
- choice = int(choice)
43
- if choice < 0 or choice >= len(frameworks):
44
- raise ValueError("Invalid choice")
45
- return AgentFramework[frameworks[choice]]
46
- except ValueError:
47
- raise ValueError("Invalid choice")
48
-
49
-
50
- def date_picker() -> FutureDatetime:
51
- """
52
- Ask the user to select a date in the future. The date must be at least 1 day in the future.
53
- """
54
- prompt = "Select a date in the future (YYYY-MM-DD-HH)"
55
- # the default should be the current date + 1 day
56
- now = datetime.now()
57
- default_val = (now + timedelta(days=1)).strftime("%Y-%m-%d-%H")
58
- date_str = Prompt.ask(prompt, default=default_val)
59
- try:
60
- year, month, day, hour = map(int, date_str.split("-"))
61
- date = datetime(year, month, day, hour)
62
- return date
63
- except ValueError:
64
- raise ValueError("Invalid date format. Please use YYYY-MM-DD-HH.")
65
-
66
-
67
- def location_picker() -> str:
68
- """
69
- Ask the user to input a location. By default use the current location based on the IP address.
70
- """
71
- prompt = "Enter a location"
72
- g = geocoder.ip("me")
73
- default_val = f"{g.city} {g.state}, {g.country}"
74
- location = Prompt.ask(prompt, default=default_val)
75
- if not location:
76
- raise ValueError("location cannot be empty")
77
- return location
78
-
79
-
80
- def max_driving_hours_picker() -> int:
81
- """
82
- Ask the user to input the maximum driving hours. The default is 2 hours.
83
- """
84
- prompt = "Enter the maximum driving hours"
85
- default_val = str(2)
86
- max_driving_hours = Prompt.ask(prompt, default=default_val)
87
- try:
88
- max_driving_hours = int(max_driving_hours)
89
- if max_driving_hours <= 0:
90
- raise ValueError("Invalid choice")
91
- return max_driving_hours
92
- except ValueError:
93
- raise ValueError("Invalid choice")
94
-
95
-
96
- def get_litellm_model_id(agent_name) -> str:
97
- """
98
- Ask the user to input a model_id string. Validate it using the litellm.validate_environment function
99
- """
100
- from litellm.utils import validate_environment
101
-
102
- prompt = f"Enter a valid model_id for agent {agent_name} using LiteLLM syntax"
103
- default_val = "openai/gpt-4o"
104
- model_id = Prompt.ask(prompt, default=default_val)
105
- # make a call to validate the model id: this will throw an error if the model id is not valid
106
- get_llm_provider(model=model_id)
107
- # make a call to validate that the environment is correct for the model id
108
- env_check = validate_environment(model_id)
109
- if not env_check["keys_in_environment"]:
110
- msg = f"{env_check['missing_keys']} needed for {model_id}"
111
- raise ValueError(msg)
112
- return model_id
113
-
114
-
115
- def set_mcp_settings(tool):
116
- logger.info(
117
- f"This MCP uses {tool['command']}. If you don't have this set up this will not work"
118
- )
119
- if "mcp/filesystem" not in tool["args"]:
120
- msg = "The only MCP that this demo supports is the filesystem MCP"
121
- raise ValueError(msg)
122
- if not any("{{ path_variable }}" in arg for arg in tool["args"]):
123
- msg = "The filesystem MCP must have { path_variable } in the args list"
124
- raise ValueError(msg)
125
- for idx, item in enumerate(tool["args"]):
126
- if "{{ path_variable }}" in item:
127
- default_val = os.path.join(tempfile.gettempdir(), "surf_spot_finder")
128
- answer = Prompt.ask(
129
- "Please enter the path you'd like the Filesystem MCP to access",
130
- default=default_val,
131
- )
132
- os.makedirs(answer, exist_ok=True)
133
- tool["args"][idx] = item.replace("{{ path_variable }}", answer)
134
- return tool
135
-
136
-
137
- class Config(BaseModel):
138
- model_config = ConfigDict(extra="forbid")
139
-
140
- location: str
141
- max_driving_hours: PositiveInt
142
- date: FutureDatetime
143
- input_prompt_template: Annotated[str, AfterValidator(validate_prompt)] = (
144
- INPUT_PROMPT_TEMPLATE
145
- )
146
-
147
- framework: AgentFramework
148
-
149
- main_agent: AgentConfig
150
- managed_agents: list[AgentConfig] | None = None
151
-
152
- evaluation_cases: list[EvaluationCase] | None = None
153
-
154
- @classmethod
155
- def from_dict(cls, data: dict) -> "Config":
156
- """
157
- Create a Config instance from a dictionary.
158
- Args:
159
- data (dict): A dictionary containing the configuration data.
160
-
161
- Returns:
162
- Config: A new Config instance populated with values from the dictionary.
163
- """
164
- # for each tool listed in main_agent.tools, use import lib to import it and replace the str with the callable
165
- callables = []
166
- if data.get("main_agent") is None:
167
- data["main_agent"] = {}
168
- if not data["main_agent"].get("model_id"):
169
- data["main_agent"]["model_id"] = get_litellm_model_id("main_agent")
170
- else:
171
- logger.info(f"Main agent using model_id {data['main_agent']['model_id']}")
172
- for tool in data["main_agent"].get("tools", []):
173
- if isinstance(tool, str):
174
- module_name, func_name = tool.rsplit(".", 1)
175
- module = __import__(module_name, fromlist=[func_name])
176
- callables.append(getattr(module, func_name))
177
- else:
178
- # this means it must be an MCPStdioParams
179
- # For the purposes of this demo, currently we just look for the filesystem MCP which we have a placeholder
180
- # for the path variable (which controls which dirs the MCP will have access to).
181
- mcp_tool = set_mcp_settings(tool)
182
- callables.append(mcp_tool)
183
- data["main_agent"]["tools"] = callables
184
- for agent in data.get("managed_agents", []):
185
- if agent.get("model_id") is None:
186
- agent["model_id"] = get_litellm_model_id(
187
- agent.get("name", "managed_agent")
188
- )
189
- else:
190
- logger.info(f"Agent {agent['name']} using model_id {agent['model_id']}")
191
- callables = []
192
- for tool in agent.get("tools", []):
193
- if isinstance(tool, str):
194
- module_name, func_name = tool.rsplit(".", 1)
195
- module = __import__(module_name, fromlist=[func_name])
196
- callables.append(getattr(module, func_name))
197
- else:
198
- # this means it must be an MCPStdioParams
199
- mcp_tool = set_mcp_settings(tool)
200
- callables.append(mcp_tool)
201
- agent["tools"] = callables
202
- if not data.get("framework"):
203
- data["framework"] = ask_framework()
204
- else:
205
- logger.info(f"Using framework {data['framework']}")
206
- if not data.get("location"):
207
- data["location"] = location_picker()
208
- else:
209
- logger.info(f"Using location {data['location']}")
210
- if not data.get("max_driving_hours"):
211
- data["max_driving_hours"] = max_driving_hours_picker()
212
- else:
213
- logger.info(f"Using max driving hours {data['max_driving_hours']}")
214
- if not data.get("date"):
215
- data["date"] = date_picker()
216
- else:
217
- logger.info(f"Using date {data['date']}")
218
-
219
- return cls(**data)
220
-
221
- @classmethod
222
- def from_yaml(cls, yaml_path: str) -> "Config":
223
- """
224
- with open(yaml_path, "r") as f:
225
- data = yaml.safe_load(f)
226
- return cls(**data) yaml_path: Path to the YAML configuration file
227
-
228
- Returns:
229
- Config: A new Config instance populated with values from the YAML file
230
- """
231
- with open(yaml_path, "r") as f:
232
- data = yaml.safe_load(f)
233
- return cls.from_dict(data)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/surf_spot_finder/instructions/__init__.py DELETED
File without changes
src/surf_spot_finder/instructions/openai.py DELETED
@@ -1,22 +0,0 @@
1
- SINGLE_AGENT_SYSTEM_PROMPT = """
2
- You will be asked to perform a task.
3
-
4
- Before solving the task, plan a sequence of actions using the available tools.
5
- Then, execute the sequence of actions using the tools.
6
-
7
- Prefer to use task-specific tools before relying on generic tools like web search.
8
- """.strip()
9
-
10
- MULTI_AGENT_SYSTEM_PROMPT = """
11
- You will be asked to perform a task.
12
-
13
- Always follow this steps:
14
-
15
- First, before solving the task, plan a sequence of actions using the available tools.
16
- Second, show the plan of actions and ask for user verification. If the user does not verify the plan, come up with a better plan.
17
- Third, execute the plan using the available tools, until you get a final answer.
18
-
19
- Once you get a final answer, show it and ask for user verification. If the user does not verify the answer, come up with a better answer.
20
-
21
- Finally, use the available handoff tool (`transfer_to_<agent_name>`) to communicate it to the user.
22
- """.strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/surf_spot_finder/instructions/shared.py DELETED
File without changes
src/surf_spot_finder/instructions/smolagents.py DELETED
@@ -1,176 +0,0 @@
1
- # Copied from https://github.com/huggingface/smolagents/blob/main/src/smolagents/prompts/code_agent.yaml
2
- SYSTEM_PROMPT = """
3
- You are an expert assistant who can solve any task using code blobs. You will be given a task to solve as best you can.
4
- To do so, you have been given access to a list of tools: these tools are basically Python functions which you can call with code.
5
- To solve the task, you must plan forward to proceed in a series of steps, in a cycle of 'Thought:', 'Code:', and 'Observation:' sequences.
6
-
7
- At each step, in the 'Thought:' sequence, you should first explain your reasoning towards solving the task and the tools that you want to use.
8
- Then in the 'Code:' sequence, you should write the code in simple Python. The code sequence must end with '<end_code>' sequence.
9
- During each intermediate step, you can use 'print()' to save whatever important information you will then need.
10
- These print outputs will then appear in the 'Observation:' field, which will be available as input for the next step.
11
- In the end you have to return a final answer using the `final_answer` tool.
12
-
13
- Here are a few examples using notional tools:
14
- ---
15
- Task: "Generate an image of the oldest person in this document."
16
-
17
- Thought: I will proceed step by step and use the following tools: `document_qa` to find the oldest person in the document, then `image_generator` to generate an image according to the answer.
18
- Code:
19
- ```py
20
- answer = document_qa(document=document, question="Who is the oldest person mentioned?")
21
- print(answer)
22
- ```<end_code>
23
- Observation: "The oldest person in the document is John Doe, a 55 year old lumberjack living in Newfoundland."
24
-
25
- Thought: I will now generate an image showcasing the oldest person.
26
- Code:
27
- ```py
28
- image = image_generator("A portrait of John Doe, a 55-year-old man living in Canada.")
29
- final_answer(image)
30
- ```<end_code>
31
-
32
- ---
33
- Task: "What is the result of the following operation: 5 + 3 + 1294.678?"
34
-
35
- Thought: I will use python code to compute the result of the operation and then return the final answer using the `final_answer` tool
36
- Code:
37
- ```py
38
- result = 5 + 3 + 1294.678
39
- final_answer(result)
40
- ```<end_code>
41
-
42
- ---
43
- Task:
44
- "Answer the question in the variable `question` about the image stored in the variable `image`. The question is in French.
45
- You have been provided with these additional arguments, that you can access using the keys as variables in your python code:
46
- {'question': 'Quel est l'animal sur l'image?', 'image': 'path/to/image.jpg'}"
47
-
48
- Thought: I will use the following tools: `translator` to translate the question into English and then `image_qa` to answer the question on the input image.
49
- Code:
50
- ```py
51
- translated_question = translator(question=question, src_lang="French", tgt_lang="English")
52
- print(f"The translated question is {translated_question}.")
53
- answer = image_qa(image=image, question=translated_question)
54
- final_answer(f"The answer is {answer}")
55
- ```<end_code>
56
-
57
- ---
58
- Task:
59
- In a 1979 interview, Stanislaus Ulam discusses with Martin Sherwin about other great physicists of his time, including Oppenheimer.
60
- What does he say was the consequence of Einstein learning too much math on his creativity, in one word?
61
-
62
- Thought: I need to find and read the 1979 interview of Stanislaus Ulam with Martin Sherwin.
63
- Code:
64
- ```py
65
- pages = search(query="1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein")
66
- print(pages)
67
- ```<end_code>
68
- Observation:
69
- No result found for query "1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein".
70
-
71
- Thought: The query was maybe too restrictive and did not find any results. Let's try again with a broader query.
72
- Code:
73
- ```py
74
- pages = search(query="1979 interview Stanislaus Ulam")
75
- print(pages)
76
- ```<end_code>
77
- Observation:
78
- Found 6 pages:
79
- [Stanislaus Ulam 1979 interview](https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/)
80
-
81
- [Ulam discusses Manhattan Project](https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/)
82
-
83
- (truncated)
84
-
85
- Thought: I will read the first 2 pages to know more.
86
- Code:
87
- ```py
88
- for url in ["https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/", "https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/"]:
89
- whole_page = visit_webpage(url)
90
- print(whole_page)
91
- print("\n" + "="*80 + "\n") # Print separator between pages
92
- ```<end_code>
93
- Observation:
94
- Manhattan Project Locations:
95
- Los Alamos, NM
96
- Stanislaus Ulam was a Polish-American mathematician. He worked on the Manhattan Project at Los Alamos and later helped design the hydrogen bomb. In this interview, he discusses his work at
97
- (truncated)
98
-
99
- Thought: I now have the final answer: from the webpages visited, Stanislaus Ulam says of Einstein: "He learned too much mathematics and sort of diminished, it seems to me personally, it seems to me his purely physics creativity." Let's answer in one word.
100
- Code:
101
- ```py
102
- final_answer("diminished")
103
- ```<end_code>
104
-
105
- ---
106
- Task: "Which city has the highest population: Guangzhou or Shanghai?"
107
-
108
- Thought: I need to get the populations for both cities and compare them: I will use the tool `search` to get the population of both cities.
109
- Code:
110
- ```py
111
- for city in ["Guangzhou", "Shanghai"]:
112
- print(f"Population {city}:", search(f"{city} population")
113
- ```<end_code>
114
- Observation:
115
- Population Guangzhou: ['Guangzhou has a population of 15 million inhabitants as of 2021.']
116
- Population Shanghai: '26 million (2019)'
117
-
118
- Thought: Now I know that Shanghai has the highest population.
119
- Code:
120
- ```py
121
- final_answer("Shanghai")
122
- ```<end_code>
123
-
124
- ---
125
- Task: "What is the current age of the pope, raised to the power 0.36?"
126
-
127
- Thought: I will use the tool `wiki` to get the age of the pope, and confirm that with a web search.
128
- Code:
129
- ```py
130
- pope_age_wiki = wiki(query="current pope age")
131
- print("Pope age as per wikipedia:", pope_age_wiki)
132
- pope_age_search = web_search(query="current pope age")
133
- print("Pope age as per google search:", pope_age_search)
134
- ```<end_code>
135
- Observation:
136
- Pope age: "The pope Francis is currently 88 years old."
137
-
138
- Thought: I know that the pope is 88 years old. Let's compute the result using python code.
139
- Code:
140
- ```py
141
- pope_current_age = 88 ** 0.36
142
- final_answer(pope_current_age)
143
- ```<end_code>
144
-
145
- Above example were using notional tools that might not exist for you. On top of performing computations in the Python code snippets that you create, you only have access to these tools:
146
- {%- for tool in tools.values() %}
147
- - {{ tool.name }}: {{ tool.description }}
148
- Takes inputs: {{tool.inputs}}
149
- Returns an output of type: {{tool.output_type}}
150
- {%- endfor %}
151
-
152
- {%- if managed_agents and managed_agents.values() | list %}
153
- You can also give tasks to team members.
154
- Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task', a long string explaining your task.
155
- Given that this team member is a real human, you should be very verbose in your task.
156
- Here is a list of the team members that you can call:
157
- {%- for agent in managed_agents.values() %}
158
- - {{ agent.name }}: {{ agent.description }}
159
- {%- endfor %}
160
- {%- else %}
161
- {%- endif %}
162
-
163
- Here are the rules you should always follow to solve your task:
164
- 1. Always provide a 'Thought:' sequence, and a 'Code:\n```py' sequence ending with '```<end_code>' sequence, else you will fail.
165
- 2. Use only variables that you have defined!
166
- 3. Always use the right arguments for the tools. DO NOT pass the arguments as a dict as in 'answer = wiki({'query': "What is the place where James Bond lives?"})', but use the arguments directly as in 'answer = wiki(query="What is the place where James Bond lives?")'.
167
- 4. Take care to not chain too many sequential tool calls in the same code block, especially when the output format is unpredictable. For instance, a call to search has an unpredictable return format, so do not have another tool call that depends on its output in the same block: rather output results with print() to use them in the next block.
168
- 5. Call a tool only when needed, and never re-do a tool call that you previously did with the exact same parameters.
169
- 6. Don't name any new variable with the same name as a tool: for instance don't name a variable 'final_answer'.
170
- 7. Never create any notional variables in our code, as having these in your logs will derail you from the true variables.
171
- 8. You can use imports in your code, but only from the following list of modules: {{authorized_imports}}
172
- 9. The state persists between code executions: so if in one step you've created variables or imported modules, these will all persist.
173
- 10. Don't give up! You're in charge of solving the task, not providing directions to solve it.
174
-
175
- Now Begin! If you solve the task correctly, you will receive a reward of $1,000,000.
176
- """.strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/surf_spot_finder/no_framework.py DELETED
@@ -1,109 +0,0 @@
1
- import re
2
- from datetime import datetime
3
-
4
- from fire import Fire
5
- from litellm import completion
6
- from any_agent.logging import logger
7
- from pydantic import BaseModel
8
-
9
- from any_agent.tools.web_browsing import search_web, visit_webpage
10
- from surf_spot_finder.tools.openmeteo import get_wave_forecast, get_wind_forecast
11
- from surf_spot_finder.tools.openstreetmap import (
12
- driving_hours_to_meters,
13
- get_area_lat_lon,
14
- get_surfing_spots,
15
- )
16
-
17
-
18
- spot_info_pattern = r"\[.*?\]\((https:\/\/www\.surf-forecast\.com\/breaks\/[^)/]+)\)"
19
-
20
-
21
- class SpotScore(BaseModel):
22
- score: int
23
- reason: str
24
-
25
-
26
- def find_surf_spot_no_framework(
27
- location: str, max_driving_hours: int, date: datetime, model_id: str
28
- ) -> list[SpotScore]:
29
- """Find the best surf spot based on the given `location` and `date`.
30
-
31
- Uses the following tools:
32
-
33
- - any_agent.tools.web_browsing
34
- - [surf_spot_finder.tools.openmeteo][]
35
- - [surf_spot_finder.tools.openstreetmap][]
36
-
37
- To find nearby spots along with the forecast and
38
- recommended conditions for the spot.
39
-
40
- Then, uses `litellm` with the provided `model_id` to score
41
- each spot based on the available information.
42
-
43
- Args:
44
- location: The place of interest.
45
- max_driving_hours: Used to limit the surf spots based on
46
- the distance to `location`.
47
- date: Used to filter the forecast results.
48
- model_id: Can be any of the [litellm providers](https://docs.litellm.ai/docs/providers).
49
-
50
- Returns:
51
- A list of spot scores and reasons for the value.
52
- """
53
- max_driving_meters = driving_hours_to_meters(max_driving_hours)
54
- lat, lon = get_area_lat_lon(location)
55
-
56
- logger.info(f"Getting surfing spots around {location}")
57
- surf_spots = get_surfing_spots(lat, lon, max_driving_meters)
58
-
59
- if not surf_spots:
60
- logger.warning("No surfing spots found around {location}")
61
- return None
62
-
63
- spots_scores = []
64
- for spot_name, (spot_lat, spot_lon) in surf_spots:
65
- logger.info(f"Processing {spot_name}")
66
- logger.debug("Getting wave forecast...")
67
- wave_forecast = get_wave_forecast(spot_lat, spot_lon, date)
68
- logger.debug("Getting wind forecast...")
69
- wind_forecast = get_wind_forecast(spot_lat, spot_lon, date)
70
-
71
- logger.debug("Searching web for spot information")
72
- search_result = search_web(f"surf-forecast.com spot info {spot_name}")
73
- match = re.search(spot_info_pattern, search_result)
74
- if match:
75
- extracted_url = match.group(1)
76
- logger.debug(f"Visiting {extracted_url}")
77
- spot_info = visit_webpage(extracted_url)
78
- else:
79
- logger.debug(f"Couldn't find spot info for {spot_name}")
80
- continue
81
-
82
- logger.debug("Scoring conditions with LLM")
83
- response = completion(
84
- model="openai/gpt-4o-mini",
85
- messages=[
86
- {
87
- "content": "Given the wind and wave forecast along with the spot information, "
88
- "rate from 1 to 5 the expected surfing conditions."
89
- f"Wind forecast:\n{wind_forecast}\n"
90
- f"Wave forecast:\n{wave_forecast}\n"
91
- f"Spot Information:\n{spot_info}",
92
- "role": "user",
93
- }
94
- ],
95
- response_format=SpotScore,
96
- )
97
- spot_score = SpotScore.model_validate_json(response.choices[0].message.content)
98
- logger.debug(spot_score)
99
- spots_scores.append(spot_score)
100
-
101
- return spots_scores
102
-
103
-
104
- def main():
105
- Fire(find_surf_spot_no_framework)
106
-
107
-
108
- if __name__ == "__main__":
109
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/surf_spot_finder/tools/__init__.py DELETED
@@ -1,10 +0,0 @@
1
- from .openmeteo import get_wave_forecast, get_wind_forecast
2
- from .openstreetmap import driving_hours_to_meters, get_area_lat_lon, get_surfing_spots
3
-
4
- __all__ = [
5
- "driving_hours_to_meters",
6
- "get_area_lat_lon",
7
- "get_surfing_spots",
8
- "get_wave_forecast",
9
- "get_wind_forecast",
10
- ]
 
 
 
 
 
 
 
 
 
 
 
src/surf_spot_finder/tools/openmeteo.py DELETED
@@ -1,114 +0,0 @@
1
- import json
2
- from datetime import datetime, timedelta
3
- import requests
4
-
5
-
6
- def _extract_hourly_data(data: dict) -> list[dict]:
7
- hourly_data = data["hourly"]
8
- result = [
9
- {k: v for k, v in zip(hourly_data.keys(), values)}
10
- for values in zip(*hourly_data.values())
11
- ]
12
- return result
13
-
14
-
15
- def _filter_by_date(
16
- date: datetime, hourly_data: list[dict], timedelta: timedelta = timedelta(hours=1)
17
- ):
18
- start_date = date - timedelta
19
- end_date = date + timedelta
20
- return [
21
- item
22
- for item in hourly_data
23
- if start_date <= datetime.fromisoformat(item["time"]) <= end_date
24
- ]
25
-
26
-
27
- def get_wave_forecast(lat: float, lon: float, date: str) -> list[dict]:
28
- """Get wave forecast for given location.
29
-
30
- Forecast will include:
31
-
32
- - wave_direction (degrees)
33
- - wave_height (meters)
34
- - wave_period (seconds)
35
- - sea_level_height_msl (meters)
36
-
37
- Args:
38
- lat: Latitude of the location.
39
- lon: Longitude of the location.
40
- date: Date to filter by in any valid ISO 8601 format.
41
-
42
- Returns:
43
- Hourly data for wave forecast.
44
- Example output:
45
-
46
- ```json
47
- [
48
- {'time': '2025-03-19T09:00', 'winddirection_10m': 140, 'windspeed_10m': 24.5}, {'time': '2025-03-19T10:00', 'winddirection_10m': 140, 'windspeed_10m': 27.1},
49
- {'time': '2025-03-19T10:00', 'winddirection_10m': 140, 'windspeed_10m': 27.1}, {'time': '2025-03-19T11:00', 'winddirection_10m': 141, 'windspeed_10m': 29.2}
50
- ]
51
- ```
52
- """
53
- url = "https://marine-api.open-meteo.com/v1/marine"
54
- params = {
55
- "latitude": lat,
56
- "longitude": lon,
57
- "hourly": [
58
- "wave_direction",
59
- "wave_height",
60
- "wave_period",
61
- "sea_level_height_msl",
62
- ],
63
- }
64
- response = requests.get(url, params=params)
65
- response.raise_for_status()
66
- data = json.loads(response.content.decode())
67
- hourly_data = _extract_hourly_data(data)
68
- if date is not None:
69
- date = datetime.fromisoformat(date)
70
- hourly_data = _filter_by_date(date, hourly_data)
71
- if len(hourly_data) == 0:
72
- raise ValueError("No data found for the given date")
73
- return hourly_data
74
-
75
-
76
- def get_wind_forecast(lat: float, lon: float, date: str) -> list[dict]:
77
- """Get wind forecast for given location.
78
-
79
- Forecast will include:
80
-
81
- - wind_direction (degrees)
82
- - wind_speed (meters per second)
83
-
84
- Args:
85
- lat: Latitude of the location.
86
- lon: Longitude of the location.
87
- date: Date to filter by in any valid ISO 8601 format.
88
-
89
- Returns:
90
- Hourly data for wind forecast.
91
- Example output:
92
-
93
- ```json
94
- [
95
- {"time": "2025-03-18T22:00", "wind_direction": 196, "wind_speed": 9.6},
96
- {"time": "2025-03-18T23:00", "wind_direction": 183, "wind_speed": 7.9},
97
- ]
98
- ```
99
- """
100
- url = "https://api.open-meteo.com/v1/forecast"
101
- params = {
102
- "latitude": lat,
103
- "longitude": lon,
104
- "hourly": ["winddirection_10m", "windspeed_10m"],
105
- }
106
- response = requests.get(url, params=params)
107
- response.raise_for_status()
108
- data = json.loads(response.content.decode())
109
- hourly_data = _extract_hourly_data(data)
110
- date = datetime.fromisoformat(date)
111
- hourly_data = _filter_by_date(date, hourly_data)
112
- if len(hourly_data) == 0:
113
- raise ValueError("No data found for the given date")
114
- return hourly_data
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/surf_spot_finder/tools/openstreetmap.py DELETED
@@ -1,92 +0,0 @@
1
- import requests
2
- import json
3
-
4
-
5
- def get_area_lat_lon(area_name: str) -> tuple[float, float]:
6
- """Get the latitude and longitude of an area from Nominatim.
7
-
8
- Uses the [Nominatim API](https://nominatim.org/release-docs/develop/api/Search/).
9
-
10
- Args:
11
- area_name: The name of the area.
12
-
13
- Returns:
14
- The area found.
15
- """
16
- response = requests.get(
17
- f"https://nominatim.openstreetmap.org/search?q={area_name}&format=json",
18
- headers={"User-Agent": "Mozilla/5.0"},
19
- )
20
- response.raise_for_status()
21
- area = json.loads(response.content.decode())
22
- return area[0]["lat"], area[0]["lon"]
23
-
24
-
25
- def driving_hours_to_meters(driving_hours: int) -> int:
26
- """Convert driving hours to meters assuming a 70 km/h average speed.
27
-
28
-
29
- Args:
30
- driving_hours: The driving hours.
31
-
32
- Returns:
33
- The distance in meters.
34
- """
35
- return driving_hours * 70 * 1000
36
-
37
-
38
- def get_lat_lon_center(bounds: dict) -> tuple[float, float]:
39
- """Get the latitude and longitude of the center of a bounding box.
40
-
41
- Args:
42
- bounds: The bounding box.
43
-
44
- ```json
45
- {
46
- "minlat": float,
47
- "minlon": float,
48
- "maxlat": float,
49
- "maxlon": float,
50
- }
51
- ```
52
-
53
- Returns:
54
- The latitude and longitude of the center.
55
- """
56
- return (
57
- (bounds["minlat"] + bounds["maxlat"]) / 2,
58
- (bounds["minlon"] + bounds["maxlon"]) / 2,
59
- )
60
-
61
-
62
- def get_surfing_spots(
63
- lat: float, lon: float, radius: int
64
- ) -> list[tuple[str, tuple[float, float]]]:
65
- """Get surfing spots around a given latitude and longitude.
66
-
67
- Uses the [Overpass API](https://wiki.openstreetmap.org/wiki/Overpass_API).
68
-
69
- Args:
70
- lat: The latitude.
71
- lon: The longitude.
72
- radius: The radius in meters.
73
-
74
- Returns:
75
- The surfing places found.
76
- """
77
- overpass_url = "https://overpass-api.de/api/interpreter"
78
- query = "[out:json];("
79
- query += f'nwr["natural"="beach"](around:{radius},{lat},{lon});'
80
- query += f'nwr["natural"="reef"](around:{radius},{lat},{lon});'
81
- query += ");out body geom;"
82
- params = {"data": query}
83
- response = requests.get(
84
- overpass_url, params=params, headers={"User-Agent": "Mozilla/5.0"}
85
- )
86
- response.raise_for_status()
87
- elements = response.json()["elements"]
88
- return [
89
- (element.get("tags", {}).get("name", ""), get_lat_lon_center(element["bounds"]))
90
- for element in elements
91
- if "surfing" in element.get("tags", {}).get("sport", "") and "bounds" in element
92
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
demo/streamlit_app.py β†’ streamlit_app.py RENAMED
File without changes
tests/unit/tools/test_unit_openmeteo.py DELETED
@@ -1,106 +0,0 @@
1
- import json
2
- from datetime import datetime, timedelta
3
- from unittest.mock import patch, MagicMock
4
-
5
- from surf_spot_finder.tools import openmeteo
6
-
7
-
8
- def test_extract_hourly_data():
9
- data = {
10
- "hourly": {
11
- "time": ["2023-01-01T00:00", "2023-01-01T01:00"],
12
- "wave_height": [1.5, 1.6],
13
- "wave_period": [10, 11],
14
- }
15
- }
16
- expected = [
17
- {"time": "2023-01-01T00:00", "wave_height": 1.5, "wave_period": 10},
18
- {"time": "2023-01-01T01:00", "wave_height": 1.6, "wave_period": 11},
19
- ]
20
- assert openmeteo._extract_hourly_data(data) == expected
21
-
22
-
23
- def test_filter_by_date():
24
- hourly_data = [
25
- {"time": "2023-01-01T00:00", "wave_height": 1.5},
26
- {"time": "2023-01-01T01:00", "wave_height": 1.6},
27
- {"time": "2023-01-01T02:00", "wave_height": 1.7},
28
- {"time": "2023-01-01T03:00", "wave_height": 1.8},
29
- ]
30
- date = datetime.fromisoformat("2023-01-01T01:00")
31
- expected = [
32
- {"time": "2023-01-01T00:00", "wave_height": 1.5},
33
- {"time": "2023-01-01T01:00", "wave_height": 1.6},
34
- {"time": "2023-01-01T02:00", "wave_height": 1.7},
35
- ]
36
- assert openmeteo._filter_by_date(date, hourly_data) == expected
37
-
38
- expected = [
39
- {"time": "2023-01-01T01:00", "wave_height": 1.6},
40
- ]
41
- assert openmeteo._filter_by_date(date, hourly_data, timedelta(hours=0)) == expected
42
-
43
-
44
- def test_get_wave_forecast():
45
- with patch("requests.get") as mock_get:
46
- mock_response = MagicMock()
47
- mock_response.status_code = 200
48
- mock_response.content.decode.return_value = json.dumps(
49
- {
50
- "hourly": {
51
- "time": ["2023-02-02T00:00", "2023-02-02T01:00"],
52
- "wave_direction": [270, 280],
53
- "wave_height": [1.5, 1.6],
54
- "wave_period": [10, 11],
55
- "sea_level_height_msl": [0.5, 0.6],
56
- }
57
- }
58
- )
59
- mock_get.return_value = mock_response
60
- result = openmeteo.get_wave_forecast(
61
- lat=40.0, lon=-3.0, date="2023-02-02T01:00"
62
- )
63
-
64
- assert len(result) == 2
65
- assert result[1]["time"] == "2023-02-02T01:00"
66
- assert result[1]["wave_direction"] == 280
67
- assert result[1]["wave_height"] == 1.6
68
- assert result[1]["wave_period"] == 11
69
- assert result[1]["sea_level_height_msl"] == 0.6
70
-
71
- result_filtered = openmeteo.get_wave_forecast(
72
- lat=40.0, lon=-3.0, date="2023-02-02T02:00"
73
- )
74
- assert len(result_filtered) == 1
75
- assert result_filtered[0]["time"] == "2023-02-02T01:00"
76
-
77
-
78
- def test_get_wind_forecast():
79
- with patch("requests.get") as mock_get:
80
- mock_response = MagicMock()
81
- mock_response.status_code = 200
82
- mock_response.content.decode.return_value = json.dumps(
83
- {
84
- "hourly": {
85
- "time": ["2023-02-02T00:00", "2023-02-02T01:00"],
86
- "winddirection_10m": [270, 280],
87
- "windspeed_10m": [10, 11],
88
- }
89
- }
90
- )
91
- mock_get.return_value = mock_response
92
-
93
- result = openmeteo.get_wind_forecast(
94
- lat=40.0, lon=-3.0, date="2023-02-02T01:00"
95
- )
96
- assert len(result) == 2
97
- assert result[1]["time"] == "2023-02-02T01:00"
98
- assert result[1]["winddirection_10m"] == 280
99
- assert result[1]["windspeed_10m"] == 11
100
-
101
- result_filtered = openmeteo.get_wind_forecast(
102
- lat=40.0, lon=-3.0, date="2023-02-02T02:00"
103
- )
104
- assert len(result_filtered) == 1
105
- assert result_filtered[0]["time"] == "2023-02-02T01:00"
106
- assert result[0]["windspeed_10m"] == 10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/unit/tools/test_unit_openstreetmap.py DELETED
@@ -1,74 +0,0 @@
1
- import json
2
- from unittest.mock import MagicMock, patch
3
-
4
- from surf_spot_finder.tools import openstreetmap
5
-
6
-
7
- def test_get_area_lat_lon():
8
- with patch("requests.get") as mock_get:
9
- mock_response = MagicMock()
10
- mock_response.status_code = 200
11
- mock_response.content.decode.return_value = json.dumps(
12
- [{"lat": "40.0", "lon": "-3.0"}]
13
- )
14
- mock_get.return_value = mock_response
15
-
16
- lat, lon = openstreetmap.get_area_lat_lon("Madrid")
17
- assert lat == "40.0"
18
- assert lon == "-3.0"
19
-
20
-
21
- def test_driving_hours_to_meters():
22
- assert openstreetmap.driving_hours_to_meters(1) == 70000
23
-
24
-
25
- def test_get_lat_lon_center():
26
- bounds = {"minlat": 40.0, "minlon": -3.0, "maxlat": 41.0, "maxlon": -2.0}
27
- lat, lon = openstreetmap.get_lat_lon_center(bounds)
28
- assert lat == 40.5
29
- assert lon == -2.5
30
-
31
-
32
- def test_get_surfing_spots():
33
- with patch("requests.get") as mock_get:
34
- mock_response = MagicMock()
35
- mock_response.status_code = 200
36
- mock_response.json.return_value = {
37
- "elements": [
38
- {
39
- "tags": {"name": "Surf Spot 1", "sport": "surfing"},
40
- "bounds": {
41
- "minlat": 40.0,
42
- "minlon": -3.0,
43
- "maxlat": 40.1,
44
- "maxlon": -2.9,
45
- },
46
- },
47
- {
48
- "tags": {"name": "Beach 2", "sport": "swimming"},
49
- "bounds": {
50
- "minlat": 41.0,
51
- "minlon": -4.0,
52
- "maxlat": 41.1,
53
- "maxlon": -3.9,
54
- },
55
- },
56
- {
57
- "tags": {"name": "Surf Spot 3", "sport": "surfing"},
58
- "bounds": {
59
- "minlat": 42.0,
60
- "minlon": -5.0,
61
- "maxlat": 42.1,
62
- "maxlon": -4.9,
63
- },
64
- },
65
- ]
66
- }
67
- mock_get.return_value = mock_response
68
-
69
- results = openstreetmap.get_surfing_spots(lat=40.5, lon=-3.5, radius=10000)
70
- assert len(results) == 2
71
- assert results[0][0] == "Surf Spot 1"
72
- assert results[0][1] == (40.05, -2.95)
73
- assert results[1][0] == "Surf Spot 3"
74
- assert results[1][1] == (42.05, -4.95)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
demo/utils.py β†’ utils.py RENAMED
File without changes