├── .DS_Store
├── .gitbook
└── assets
│ ├── Group.jpg
│ └── logo.png
├── .idea
├── .gitignore
├── Social-Science.iml
├── deployment.xml
├── inspectionProfiles
│ ├── Project_Default.xml
│ └── profiles_settings.xml
├── misc.xml
├── modules.xml
├── rSettings.xml
└── vcs.xml
├── Group.jpg
├── LICENSE
├── README.md
├── SUMMARY.md
├── agentscope-main
├── .flake8
├── .github
│ ├── ISSUE_TEMPLATE
│ │ ├── bug_report.md
│ │ ├── custom.md
│ │ └── feature_request.md
│ ├── PULL_REQUEST_TEMPLATE.md
│ ├── README.md
│ ├── issue_template
│ │ ├── README.md
│ │ ├── bug_report.md
│ │ ├── custom.md
│ │ └── feature_request.md
│ ├── pull_request_template.md
│ ├── release-drafter.yml
│ └── workflows
│ │ ├── pre-commit.yml
│ │ ├── sphinx_docs.yml
│ │ └── unittest.yml
├── .gitignore
├── .pre-commit-config.yaml
├── README.md
├── pyproject.toml
├── scripts.md
├── scripts
│ ├── README.md
│ ├── fastchat
│ │ ├── fastchat_setup.sh
│ │ └── model_config.json
│ ├── flask_modelscope
│ │ ├── model_config.json
│ │ └── setup_ms_service.py
│ ├── flask_transformers
│ │ ├── model_config.json
│ │ └── setup_hf_service.py
│ ├── ollama
│ │ ├── model_config.json
│ │ └── ollama.sh
│ └── vllm
│ │ ├── model_config.json
│ │ └── vllm_setup.sh
├── setup.py
└── src
│ └── agentscope
│ ├── __init__.py
│ ├── _init.py
│ ├── _version.py
│ ├── agents
│ ├── __init__.py
│ ├── agent.py
│ ├── dialog_agent.py
│ ├── dict_dialog_agent.py
│ ├── operator.py
│ ├── rag_agent.py
│ ├── react_agent.py
│ ├── rpc_agent.py
│ ├── sci_agent.py
│ ├── text_to_image_agent.py
│ └── user_agent.py
│ ├── constants.py
│ ├── exception.py
│ ├── file_manager.py
│ ├── logging.py
│ ├── manager
│ ├── __init__.py
│ ├── _file.py
│ ├── _manager.py
│ ├── _model.py
│ └── _monitor.py
│ ├── memory
│ ├── __init__.py
│ ├── memory.py
│ └── temporary_memory.py
│ ├── message
│ ├── __init__.py
│ ├── msg.py
│ └── placeholder.py
│ ├── models
│ ├── __init__.py
│ ├── _model_utils.py
│ ├── dashscope_model.py
│ ├── gemini_model.py
│ ├── litellm_model.py
│ ├── model.py
│ ├── ollama_model.py
│ ├── openai_model.py
│ ├── post_model.py
│ ├── response.py
│ └── zhipu_model.py
│ ├── msghub.py
│ ├── parsers
│ ├── __init__.py
│ ├── code_block_parser.py
│ ├── json_object_parser.py
│ ├── parser_base.py
│ ├── regex_tagged_content_parser.py
│ └── tagged_content_parser.py
│ ├── pipelines
│ ├── __init__.py
│ ├── functional.py
│ └── pipeline.py
│ ├── prompt
│ ├── __init__.py
│ ├── _prompt_comparer.py
│ ├── _prompt_engine.py
│ ├── _prompt_examples.json
│ ├── _prompt_generator_base.py
│ ├── _prompt_generator_en.py
│ ├── _prompt_generator_zh.py
│ ├── _prompt_optimizer.py
│ └── _prompt_utils.py
│ ├── rag
│ ├── __init__.py
│ ├── knowledge.py
│ ├── knowledge_bank.py
│ └── llama_index_knowledge.py
│ ├── rpc
│ ├── __init__.py
│ ├── rpc_agent.proto
│ ├── rpc_agent_client.py
│ ├── rpc_agent_pb2.py
│ └── rpc_agent_pb2_grpc.py
│ ├── server
│ ├── __init__.py
│ ├── launcher.py
│ └── servicer.py
│ ├── service
│ ├── __init__.py
│ ├── execute_code
│ │ ├── __init__.py
│ │ ├── exec_notebook.py
│ │ ├── exec_python.py
│ │ └── exec_shell.py
│ ├── file
│ │ ├── __init__.py
│ │ ├── common.py
│ │ ├── json.py
│ │ └── text.py
│ ├── multi_modality
│ │ ├── __init__.py
│ │ ├── dashscope_services.py
│ │ └── openai_services.py
│ ├── retrieval
│ │ ├── __init__.py
│ │ ├── retrieval_from_list.py
│ │ └── similarity.py
│ ├── service_response.py
│ ├── service_status.py
│ ├── service_toolkit.py
│ ├── sql_query
│ │ ├── __init__.py
│ │ ├── mongodb.py
│ │ ├── mysql.py
│ │ └── sqlite.py
│ ├── text_processing
│ │ ├── __init__.py
│ │ └── summarization.py
│ └── web
│ │ ├── __init__.py
│ │ ├── arxiv.py
│ │ ├── dblp.py
│ │ ├── download.py
│ │ ├── search.py
│ │ ├── web_digest.py
│ │ └── wikipedia.py
│ ├── strategy
│ ├── __init__.py
│ └── mixture_of_agent.py
│ ├── studio
│ ├── __init__.py
│ ├── _app.py
│ ├── _app_online.py
│ ├── _client.py
│ ├── _studio_utils.py
│ ├── static
│ │ ├── css
│ │ │ ├── base.css
│ │ │ ├── dashboard-detail-code.css
│ │ │ ├── dashboard-detail-dialogue.css
│ │ │ ├── dashboard-detail-invocation.css
│ │ │ ├── dashboard-detail.css
│ │ │ ├── dashboard-runs.css
│ │ │ ├── dashboard.css
│ │ │ ├── font.css
│ │ │ ├── index.css
│ │ │ ├── login.css
│ │ │ ├── server.css
│ │ │ ├── workstation-drag-components.css
│ │ │ └── workstation.css
│ │ ├── css_third_party
│ │ │ ├── clusterize.css
│ │ │ ├── drawflow.min.css
│ │ │ ├── highlight.min.css
│ │ │ ├── katex.min.css
│ │ │ ├── prism-line-numbers.min.css
│ │ │ ├── prism.min.css
│ │ │ └── tabulator.min.css
│ │ ├── fonts
│ │ │ ├── KRYPTON.ttf
│ │ │ └── SourceSans3-Regular.ttf
│ │ ├── html-drag-components
│ │ │ ├── agent-dialogagent.html
│ │ │ ├── agent-dictdialogagent.html
│ │ │ ├── agent-reactagent.html
│ │ │ ├── agent-texttoimageagent.html
│ │ │ ├── agent-useragent.html
│ │ │ ├── message-msg.html
│ │ │ ├── model-dashscope-chat.html
│ │ │ ├── model-openai-chat.html
│ │ │ ├── model-post-api-chat.html
│ │ │ ├── model-post-api-dall-e.html
│ │ │ ├── pipeline-forlooppipeline.html
│ │ │ ├── pipeline-ifelsepipeline.html
│ │ │ ├── pipeline-msghub.html
│ │ │ ├── pipeline-placeholder.html
│ │ │ ├── pipeline-sequentialpipeline.html
│ │ │ ├── pipeline-switchpipeline.html
│ │ │ ├── pipeline-whilelooppipeline.html
│ │ │ ├── service-bing-search.html
│ │ │ ├── service-execute-python.html
│ │ │ ├── service-google-search.html
│ │ │ ├── service-read-text.html
│ │ │ ├── service-write-text.html
│ │ │ └── welcome.html
│ │ ├── html
│ │ │ ├── dashboard-detail-code.html
│ │ │ ├── dashboard-detail-dialogue.html
│ │ │ ├── dashboard-detail-invocation.html
│ │ │ ├── dashboard-detail.html
│ │ │ ├── dashboard-runs.html
│ │ │ ├── dashboard.html
│ │ │ ├── index-guide.html
│ │ │ ├── market.html
│ │ │ ├── server.html
│ │ │ ├── template.html
│ │ │ └── workstation_iframe.html
│ │ ├── js
│ │ │ ├── dashboard-detail-code.js
│ │ │ ├── dashboard-detail-dialogue.js
│ │ │ ├── dashboard-detail-invocation.js
│ │ │ ├── dashboard-detail.js
│ │ │ ├── dashboard-runs.js
│ │ │ ├── dashboard.js
│ │ │ ├── index.js
│ │ │ ├── server.js
│ │ │ ├── workstation.js
│ │ │ └── workstation_iframe.js
│ │ ├── js_third_party
│ │ │ ├── buttons.js
│ │ │ ├── clusterize.min.js
│ │ │ ├── drawflow.min.js
│ │ │ ├── highlight.min.js
│ │ │ ├── jquery.min.js
│ │ │ ├── katex.min.js
│ │ │ ├── marked-katex-extension.umd.js
│ │ │ ├── marked.min.js
│ │ │ ├── micromodal.min.js
│ │ │ ├── monaco-editor.loader.js
│ │ │ ├── prism-line-numbers.min.js
│ │ │ ├── prism-python.min.js
│ │ │ ├── prism.min.js
│ │ │ ├── socket.io.js
│ │ │ ├── sweetalert2@11
│ │ │ └── tabulator.min.js
│ │ ├── svg
│ │ │ ├── circle-add.svg
│ │ │ ├── circle-delete.svg
│ │ │ ├── flush.svg
│ │ │ └── trash-bin.svg
│ │ └── workstation_templates
│ │ │ ├── en1.json
│ │ │ ├── en2.json
│ │ │ ├── en3.json
│ │ │ ├── en4.json
│ │ │ └── zh1.json
│ ├── templates
│ │ ├── index.html
│ │ ├── login.html
│ │ └── workstation.html
│ └── utils.py
│ ├── utils
│ ├── __init__.py
│ ├── common.py
│ ├── token_utils.py
│ └── tools.py
│ └── web
│ ├── __init__.py
│ ├── gradio
│ ├── __init__.py
│ ├── constants.py
│ ├── studio.py
│ └── utils.py
│ └── workstation
│ ├── __init__.py
│ ├── examples
│ ├── 0_two_agent.json
│ ├── 1_conversation.json
│ ├── 2_msghub.json
│ ├── 3_condition_pipeline.json
│ ├── 4_copiednode.json
│ ├── 5_groupchat.json
│ └── 6_reactagent.json
│ ├── workflow.py
│ ├── workflow_dag.py
│ ├── workflow_node.py
│ └── workflow_utils.py
├── logo.png
├── preprocess_data
├── CS_data
│ ├── data_extraction
│ │ ├── extract_coauthor2json.py
│ │ ├── extract_data_in_range.py
│ │ └── extract_publication2json.py
│ ├── database
│ │ ├── add_paper_citation_num.py
│ │ └── create_database.py
│ └── visualization
│ │ ├── author_affiliation_distribution.py
│ │ ├── author_citation_distribution.py
│ │ ├── author_topic_distrbution.py
│ │ └── cluster_community.py
└── OAG_data
│ └── database
│ └── create_database.py
├── requirements.txt
└── sci_platform
├── .DS_Store
├── __pycache__
└── platform.cpython-311.pyc
├── configs
├── knowledge_config.json
└── model_configs.json
├── run.py
├── sci_platform.py
├── sci_team
├── SciTeam.py
└── __init__.py
└── utils
├── __init__.py
├── prompt.py
└── scientist_utils.py
/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/open-sciencelab/Virtual-Scientists/9a6d0f32f9adbccef68f70f1705fa12fc9d10e23/.DS_Store
--------------------------------------------------------------------------------
/.gitbook/assets/Group.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/open-sciencelab/Virtual-Scientists/9a6d0f32f9adbccef68f70f1705fa12fc9d10e23/.gitbook/assets/Group.jpg
--------------------------------------------------------------------------------
/.gitbook/assets/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/open-sciencelab/Virtual-Scientists/9a6d0f32f9adbccef68f70f1705fa12fc9d10e23/.gitbook/assets/logo.png
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 | # Editor-based HTTP Client requests
5 | /httpRequests/
6 | # Datasource local storage ignored files
7 | /dataSources/
8 | /dataSources.local.xml
9 |
--------------------------------------------------------------------------------
/.idea/Social-Science.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/.idea/deployment.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/.idea/inspectionProfiles/Project_Default.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/.idea/inspectionProfiles/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/rSettings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Group.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/open-sciencelab/Virtual-Scientists/9a6d0f32f9adbccef68f70f1705fa12fc9d10e23/Group.jpg
--------------------------------------------------------------------------------
/SUMMARY.md:
--------------------------------------------------------------------------------
1 | # Table of contents
2 |
3 | * [README](README.md)
4 | * [agentscope-main](agentscope-main/README.md)
5 | * [.github](agentscope-main/.github/README.md)
6 | * [PULL\_REQUEST\_TEMPLATE](agentscope-main/.github/pull_request_template.md)
7 | * [ISSUE\_TEMPLATE](agentscope-main/.github/issue_template/README.md)
8 | * [\[Bug\]:](agentscope-main/.github/issue_template/bug_report.md)
9 | * [custom](agentscope-main/.github/issue_template/custom.md)
10 | * [\[Feature\]:](agentscope-main/.github/issue_template/feature_request.md)
11 | * [scripts](agentscope-main/scripts.md)
12 |
--------------------------------------------------------------------------------
/agentscope-main/.flake8:
--------------------------------------------------------------------------------
1 | [flake8]
2 | exclude =
3 | scripts/*
4 | src/agentscope/rpc/*
5 | max-line-length = 79
6 | inline-quotes = "
7 | avoid-escape = no
8 | ignore =
9 | F401
10 | F403
11 | W503
12 | E731
--------------------------------------------------------------------------------
/agentscope-main/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug Report
3 | about: Create a report to help us improve
4 | title: '[Bug]:'
5 | labels: 'bug'
6 | assignees: ''
7 |
8 | ---
9 |
10 | **AgentScope is an open-source project. To involve a broader community, we recommend asking your questions in English. **
11 |
12 | **Describe the bug**
13 | A clear and concise description of what the bug is.
14 |
15 | **To Reproduce**
16 | Steps to reproduce the behavior:
17 |
18 | 1. You code
19 | 2. How to execute
20 | 3. See error
21 |
22 | **Expected behavior**
23 | A clear and concise description of what you expected to happen.
24 |
25 | **Error messages**
26 | Detailed error messages.
27 |
28 | **Environment (please complete the following information):**
29 |
30 | - AgentScope Version: [e.g. 0.0.2 via `print(agentscope.__version__)`]
31 | - Python Version: [e.g. 3.9]
32 | - OS: [e.g. macos, windows]
33 |
34 | **Additional context**
35 | Add any other context about the problem here.
36 |
--------------------------------------------------------------------------------
/agentscope-main/.github/ISSUE_TEMPLATE/custom.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Custom issue template
3 | about: Describe this issue template's purpose here.
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **AgentScope is an open-source project. To involve a broader community, we recommend asking your questions in English. **
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/agentscope-main/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature Request
3 | about: Suggest an idea for this project
4 | title: '[Feature]: '
5 | labels: 'enhancement'
6 | assignees: ''
7 |
8 | ---
9 |
10 | **AgentScope is an open-source project. To involve a broader community, we recommend asking your questions in English. **
11 |
12 |
13 | **Is your feature request related to a problem? Please describe.**
14 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
15 |
16 | **Describe the solution you'd like**
17 | A clear and concise description of what you want to happen.
18 |
19 | **Describe alternatives you've considered**
20 | A clear and concise description of any alternative solutions or features you've considered.
21 |
22 | **Additional context**
23 | Add any other context or screenshots about the feature request here.
--------------------------------------------------------------------------------
/agentscope-main/.github/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Pull Request
3 | about: Create a pull request
4 | ---
5 | ## Description
6 |
7 | [Please describe the background, purpose, changes made, and how to test this PR]
8 |
9 |
10 |
11 | ## Checklist
12 |
13 | Please check the following items before code is ready to be reviewed.
14 |
15 | - [ ] Code has passed all tests
16 | - [ ] Docstrings have been added/updated in Google Style
17 | - [ ] Documentation has been updated
18 | - [ ] Code is ready for review
--------------------------------------------------------------------------------
/agentscope-main/.github/README.md:
--------------------------------------------------------------------------------
1 | # .github
2 |
3 |
--------------------------------------------------------------------------------
/agentscope-main/.github/issue_template/README.md:
--------------------------------------------------------------------------------
1 | # ISSUE\_TEMPLATE
2 |
3 |
--------------------------------------------------------------------------------
/agentscope-main/.github/issue_template/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug Report
3 | about: Create a report to help us improve
4 | title: '[Bug]:'
5 | labels: 'bug'
6 | assignees: ''
7 |
8 | ---
9 |
10 | **AgentScope is an open-source project. To involve a broader community, we recommend asking your questions in English. **
11 |
12 | **Describe the bug**
13 | A clear and concise description of what the bug is.
14 |
15 | **To Reproduce**
16 | Steps to reproduce the behavior:
17 |
18 | 1. You code
19 | 2. How to execute
20 | 3. See error
21 |
22 | **Expected behavior**
23 | A clear and concise description of what you expected to happen.
24 |
25 | **Error messages**
26 | Detailed error messages.
27 |
28 | **Environment (please complete the following information):**
29 |
30 | - AgentScope Version: [e.g. 0.0.2 via `print(agentscope.__version__)`]
31 | - Python Version: [e.g. 3.9]
32 | - OS: [e.g. macos, windows]
33 |
34 | **Additional context**
35 | Add any other context about the problem here.
36 |
--------------------------------------------------------------------------------
/agentscope-main/.github/issue_template/custom.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Custom issue template
3 | about: Describe this issue template's purpose here.
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **AgentScope is an open-source project. To involve a broader community, we recommend asking your questions in English. **
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/agentscope-main/.github/issue_template/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature Request
3 | about: Suggest an idea for this project
4 | title: '[Feature]: '
5 | labels: 'enhancement'
6 | assignees: ''
7 |
8 | ---
9 |
10 | **AgentScope is an open-source project. To involve a broader community, we recommend asking your questions in English. **
11 |
12 |
13 | **Is your feature request related to a problem? Please describe.**
14 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
15 |
16 | **Describe the solution you'd like**
17 | A clear and concise description of what you want to happen.
18 |
19 | **Describe alternatives you've considered**
20 | A clear and concise description of any alternative solutions or features you've considered.
21 |
22 | **Additional context**
23 | Add any other context or screenshots about the feature request here.
--------------------------------------------------------------------------------
/agentscope-main/.github/pull_request_template.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Pull Request
3 | about: Create a pull request
4 | ---
5 | ## Description
6 |
7 | [Please describe the background, purpose, changes made, and how to test this PR]
8 |
9 |
10 |
11 | ## Checklist
12 |
13 | Please check the following items before code is ready to be reviewed.
14 |
15 | - [ ] Code has passed all tests
16 | - [ ] Docstrings have been added/updated in Google Style
17 | - [ ] Documentation has been updated
18 | - [ ] Code is ready for review
--------------------------------------------------------------------------------
/agentscope-main/.github/release-drafter.yml:
--------------------------------------------------------------------------------
1 | name-template: 'v$RESOLVED_VERSION 🌈'
2 | tag-template: 'v$RESOLVED_VERSION'
3 | categories:
4 | - title: '🚀 Features'
5 | labels:
6 | - 'feature'
7 | - 'enhancement'
8 | - 'Feature'
9 | - title: '🐛 Bug Fixes'
10 | labels:
11 | - 'fix'
12 | - 'bugfix'
13 | - 'bug'
14 | - 'hotfix'
15 | - title: '🧰 Maintenance'
16 | labels:
17 | - 'chore'
18 | - 'maintenance'
19 | - 'refactor'
20 | - 'style'
21 | - 'docs'
22 | exclude-labels:
23 | - 'skip-changelog'
24 | - 'duplicate'
25 | - 'question'
26 | - 'invalid'
27 | - 'wontfix'
28 | change-template: '- $TITLE @$AUTHOR (#$NUMBER)'
29 | change-title-escapes: '\<*_&' # You can add # and @ to disable mentions, and add ` to disable code blocks.
30 | version-resolver:
31 | major:
32 | labels:
33 | - 'major'
34 | minor:
35 | labels:
36 | - 'minor'
37 | patch:
38 | labels:
39 | - 'patch'
40 | default: patch
41 | template: |
42 | ## What's Changed
43 |
44 | $CHANGES
45 |
46 | ## Contributors
47 | Thanks to all the contributors who have helped with this release!
48 | $CONTRIBUTORS
--------------------------------------------------------------------------------
/agentscope-main/.github/workflows/pre-commit.yml:
--------------------------------------------------------------------------------
1 | name: Pre-commit
2 |
3 | on: [push, pull_request]
4 |
5 | jobs:
6 | run:
7 | runs-on: ${{ matrix.os }}
8 | strategy:
9 | fail-fast: True
10 | matrix:
11 | os: [ubuntu-latest]
12 | env:
13 | OS: ${{ matrix.os }}
14 | PYTHON: '3.9'
15 | steps:
16 | - uses: actions/checkout@master
17 | - name: Setup Python
18 | uses: actions/setup-python@master
19 | with:
20 | python-version: 3.9
21 | - name: Update setuptools
22 | run: |
23 | pip install setuptools==68.2.2 wheel==0.41.2
24 | - name: Install AgentScope
25 | run: |
26 | pip install -q -e .[full]
27 | - name: Install pre-commit
28 | run: |
29 | pre-commit install
30 | - name: Pre-commit starts
31 | run: |
32 | pre-commit run --all-files > pre-commit.log 2>&1 || true
33 | cat pre-commit.log
34 | if grep -q Failed pre-commit.log; then
35 | echo -e "\e[41m [**FAIL**] Please install pre-commit and format your code first. \e[0m"
36 | exit 1
37 | fi
38 | echo -e "\e[46m ********************************Passed******************************** \e[0m"
39 |
--------------------------------------------------------------------------------
/agentscope-main/.github/workflows/sphinx_docs.yml:
--------------------------------------------------------------------------------
1 | name: Deploy Sphinx documentation to Pages
2 |
3 | on:
4 | pull_request:
5 | types: [opened, synchronize]
6 | paths:
7 | - 'docs/**/*'
8 | push:
9 | branches:
10 | - main
11 |
12 | jobs:
13 | pages:
14 | timeout-minutes: 20
15 | runs-on: ${{ matrix.os }}
16 | strategy:
17 | matrix:
18 | os: [ubuntu-latest]
19 | python-version: ['3.9']
20 | env:
21 | OS: ${{ matrix.os }}
22 | PYTHON: '3.9'
23 | steps:
24 | - uses: actions/checkout@master
25 | - name: Setup Python ${{ matrix.python-version }}
26 | uses: actions/setup-python@master
27 | with:
28 | python-version: ${{ matrix.python-version }}
29 | - name: Update setuptools
30 | run: |
31 | pip install setuptools==68.2.2 wheel==0.41.2
32 | - name: Install Dependencies
33 | run: |
34 | pip install -q -e .[full]
35 | - id: build
36 | name: Build Documentation
37 | run: |
38 | cd docs/sphinx_doc
39 | ./build_sphinx_doc.sh
40 | - name: Upload Documentation
41 | uses: actions/upload-artifact@v4
42 | with:
43 | name: SphinxDoc
44 | path: 'docs/sphinx_doc/build'
45 | - uses: peaceiris/actions-gh-pages@v3
46 | if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' }}
47 | with:
48 | github_token: ${{ secrets.GITHUB_TOKEN }}
49 | publish_dir: 'docs/sphinx_doc/build/html'
50 | cname: doc.agentscope.io
--------------------------------------------------------------------------------
/agentscope-main/.github/workflows/unittest.yml:
--------------------------------------------------------------------------------
1 | name: Python Unittest Coverage
2 |
3 | on: [push, pull_request]
4 |
5 | jobs:
6 | test:
7 | if: false == contains(github.event.pull_request.title, 'WIP')
8 | runs-on: ${{ matrix.os }}
9 | strategy:
10 | matrix:
11 | os: [ubuntu-latest, windows-latest, macos-13]
12 | python-version: ['3.9', '3.10', '3.11', '3.12']
13 | env:
14 | OS: ${{ matrix.os }}
15 | steps:
16 | - uses: actions/checkout@master
17 | - name: Setup Python ${{ matrix.python-version }}
18 | uses: actions/setup-python@master
19 | with:
20 | python-version: ${{ matrix.python-version }}
21 | - name: Update setuptools
22 | run: |
23 | pip install setuptools==68.2.2 wheel==0.41.2
24 | - name: Install Minimal Dependencies
25 | run: |
26 | pip install -q -e .
27 | - name: Run import tests
28 | run: |
29 | python -c "import agentscope; print(agentscope.__version__)"
30 | - name: Install Full Dependencies
31 | run: |
32 | pip install -q -e .[full]
33 | pip install coverage
34 | - name: Run tests with coverage
35 | run: |
36 | coverage run tests/run.py
37 | - name: Generate coverage report
38 | run: |
39 | coverage report -m
40 |
--------------------------------------------------------------------------------
/agentscope-main/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | pip-wheel-metadata/
24 | share/python-wheels/
25 | *.egg-info/
26 | .installed.cfg
27 | *.egg
28 | MANIFEST
29 |
30 | # PyInstaller
31 | # Usually these files are written by a python script from a template
32 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
33 | *.manifest
34 | *.spec
35 |
36 | # Installer logs
37 | pip-log.txt
38 | pip-delete-this-directory.txt
39 |
40 | # Unit test / coverage reports
41 | htmlcov/
42 | .tox/
43 | .nox/
44 | .coverage
45 | .coverage.*
46 | .cache
47 | nosetests.xml
48 | coverage.xml
49 | *.cover
50 | *.py,cover
51 | .hypothesis/
52 | .pytest_cache/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | target/
76 |
77 | # Jupyter Notebook
78 | .ipynb_checkpoints
79 |
80 | # IPython
81 | profile_default/
82 | ipython_config.py
83 |
84 | # pyenv
85 | .python-version
86 |
87 | # pipenv
88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
91 | # install all needed dependencies.
92 | #Pipfile.lock
93 |
94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
95 | __pypackages__/
96 |
97 | # Celery stuff
98 | celerybeat-schedule
99 | celerybeat.pid
100 |
101 | # SageMath parsed files
102 | *.sage.py
103 |
104 | # Environments
105 | .env
106 | .venv
107 | env/
108 | venv/
109 | ENV/
110 | env.bak/
111 | venv.bak/
112 |
113 | # Spyder project settings
114 | .spyderproject
115 | .spyproject
116 |
117 | # Rope project settings
118 | .ropeproject
119 |
120 | # mkdocs documentation
121 | /site
122 |
123 | # mypy
124 | .mypy_cache/
125 | .dmypy.json
126 | dmypy.json
127 |
128 | # Pyre type checker
129 | .pyre/
130 |
131 | .idea/
132 |
133 | # macOS
134 | .DS_Store
135 |
136 | # docs
137 | docs/sphinx_doc/build/
138 |
139 | # Used to save loggings and files
140 | *runs/
141 | agentscope.db
142 | tmp*.json
143 |
--------------------------------------------------------------------------------
/agentscope-main/.pre-commit-config.yaml:
--------------------------------------------------------------------------------
1 | repos:
2 | - repo: https://github.com/pre-commit/pre-commit-hooks
3 | rev: v4.3.0
4 | hooks:
5 | - id: check-ast
6 | - id: sort-simple-yaml
7 | - id: check-yaml
8 | exclude: |
9 | (?x)^(
10 | meta.yaml
11 | )$
12 | - id: check-xml
13 | - id: check-toml
14 | - id: check-docstring-first
15 | - id: check-json
16 | - id: fix-encoding-pragma
17 | - id: detect-private-key
18 | - id: trailing-whitespace
19 | - repo: https://github.com/asottile/add-trailing-comma
20 | rev: v3.1.0
21 | hooks:
22 | - id: add-trailing-comma
23 | - repo: https://github.com/pre-commit/mirrors-mypy
24 | rev: v1.7.0
25 | hooks:
26 | - id: mypy
27 | exclude:
28 | (?x)(
29 | pb2\.py$
30 | | grpc\.py$
31 | | ^docs
32 | | \.html$
33 | )
34 | args: [ --disallow-untyped-defs,
35 | --disallow-incomplete-defs,
36 | --ignore-missing-imports,
37 | --disable-error-code=var-annotated,
38 | --disable-error-code=union-attr,
39 | --disable-error-code=assignment,
40 | --disable-error-code=attr-defined,
41 | --disable-error-code=import-untyped,
42 | --disable-error-code=truthy-function,
43 | --follow-imports=skip,
44 | --explicit-package-bases,
45 | ]
46 | # - repo: https://github.com/numpy/numpydoc
47 | # rev: v1.6.0
48 | # hooks:
49 | # - id: numpydoc-validation
50 | - repo: https://github.com/psf/black
51 | rev: 23.3.0
52 | hooks:
53 | - id: black
54 | args: [--line-length=79]
55 | - repo: https://github.com/PyCQA/flake8
56 | rev: 6.1.0
57 | hooks:
58 | - id: flake8
59 | args: ["--extend-ignore=E203"]
60 | - repo: https://github.com/pylint-dev/pylint
61 | rev: v3.0.2
62 | hooks:
63 | - id: pylint
64 | exclude:
65 | (?x)(
66 | ^docs
67 | | pb2\.py$
68 | | grpc\.py$
69 | | \.demo$
70 | | \.md$
71 | | \.html$
72 | )
73 | args: [
74 | --disable=W0511,
75 | --disable=W0718,
76 | --disable=W0122,
77 | --disable=C0103,
78 | --disable=R0913,
79 | --disable=E0401,
80 | --disable=E1101,
81 | --disable=C0415,
82 | --disable=W0603,
83 | --disable=R1705,
84 | --disable=R0914,
85 | --disable=E0601,
86 | --disable=W0602,
87 | --disable=W0604,
88 | --disable=R0801,
89 | --disable=R0902,
90 | --disable=R0903,
91 | --disable=C0123,
92 | --disable=W0231,
93 | --disable=W1113,
94 | --disable=W0221,
95 | --disable=R0401,
96 | --disable=W0632,
97 | --disable=W0123,
98 | --disable=C3001,
99 | ]
100 | - repo: https://github.com/regebro/pyroma
101 | rev: "4.0"
102 | hooks:
103 | - id: pyroma
104 | args: [--min=10, .]
105 |
--------------------------------------------------------------------------------
/agentscope-main/README.md:
--------------------------------------------------------------------------------
1 | # agentscope-main
2 |
3 |
--------------------------------------------------------------------------------
/agentscope-main/scripts/fastchat/fastchat_setup.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | model_name_or_path="meta-llama/Llama-2-7b-chat-hf"
4 | port=8000
5 |
6 | while getopts "m:p:" flag
7 | do
8 | # shellcheck disable=SC2220
9 | case "${flag}" in
10 | m) model_name_or_path=${OPTARG};;
11 | p) port=${OPTARG};;
12 | esac
13 | done
14 |
15 |
16 | python3 -m fastchat.serve.controller &
17 | sleep 1
18 | python3 -m fastchat.serve.model_worker --model-path "${model_name_or_path}" &
19 | sleep 1
20 | python3 -m fastchat.serve.openai_api_server --host localhost --port "${port}" &
21 |
--------------------------------------------------------------------------------
/agentscope-main/scripts/fastchat/model_config.json:
--------------------------------------------------------------------------------
1 | {
2 | "model_type": "openai_chat",
3 | "config_name": "fastchat_llama2-7b-chat-hf",
4 | "model_name": "meta-llama/Llama-2-7b-chat-hf",
5 | "api_key": "EMPTY",
6 | "client_args": {
7 | "base_url": "http://localhost:8000/v1/"
8 | },
9 | "generate_args": {
10 | "temperature": 0.5
11 | }
12 | }
--------------------------------------------------------------------------------
/agentscope-main/scripts/flask_modelscope/model_config.json:
--------------------------------------------------------------------------------
1 | {
2 | "model_type": "post_api_chat",
3 | "config_name": "flask_llama2-7b-chat-ms",
4 | "api_url": "http://127.0.0.1:8000/llm/",
5 | "json_args": {
6 | "max_length": 4096,
7 | "temperature": 0.5
8 | }
9 | }
--------------------------------------------------------------------------------
/agentscope-main/scripts/flask_transformers/model_config.json:
--------------------------------------------------------------------------------
1 | {
2 | "model_type": "post_api_chat",
3 | "config_name": "flask_llama-2-chat-7b-hf",
4 | "api_url": "http://127.0.0.1:8000/llm/",
5 | "json_args": {
6 | "max_length": 4096,
7 | "temperature": 0.5
8 | }
9 | }
--------------------------------------------------------------------------------
/agentscope-main/scripts/ollama/model_config.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "config_name": "my_ollama_chat_config",
4 | "model_type": "ollama_chat",
5 | "model_name": "{model_name}",
6 | "options": {
7 | "temperature": 0.5,
8 | "seed": 123
9 | },
10 | "keep_alive": "5m"
11 | },
12 | {
13 | "config_name": "my_ollama_generate_config",
14 | "model_type": "ollama_generate",
15 | "model_name": "{model_name}",
16 | "options": {
17 | "temperature": 0.5,
18 | "seed": 123
19 | },
20 | "keep_alive": "5m"
21 | },
22 | {
23 | "config_name": "my_ollama_embedding_config",
24 | "model_type": "ollama_embedding",
25 | "model_name": "{model_name}",
26 | "options": {
27 | "temperature": 0.5,
28 | "seed": 123
29 | },
30 | "keep_alive": "5m"
31 | }
32 | ]
--------------------------------------------------------------------------------
/agentscope-main/scripts/ollama/ollama.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | ollama pull llama2
--------------------------------------------------------------------------------
/agentscope-main/scripts/vllm/model_config.json:
--------------------------------------------------------------------------------
1 | {
2 | "model_type": "openai_chat",
3 | "config_name": "vllm_llama2-7b-chat-hf",
4 | "model_name": "meta-llama/Llama-2-7b-chat-hf",
5 | "api_key": "EMPTY",
6 | "client_args": {
7 | "base_url": "http://localhost:8000/v1/"
8 | },
9 | "generate_args": {
10 | "temperature": 0.5
11 | }
12 | }
--------------------------------------------------------------------------------
/agentscope-main/scripts/vllm/vllm_setup.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # pip3 install vllm
4 |
5 | model_name_or_path="meta-llama/Llama-2-7b-chat-hf"
6 | port=8000
7 |
8 | while getopts "m:p:" flag
9 | do
10 | # shellcheck disable=SC2220
11 | case "${flag}" in
12 | m) model_name_or_path=${OPTARG};;
13 | p) port=${OPTARG};;
14 | esac
15 | done
16 |
17 | python -m vllm.entrypoints.openai.api_server --model "${model_name_or_path}" \
18 | --port "${port}" --enforce-eager
19 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """ Import all modules in the package. """
3 |
4 | # modules
5 | from . import manager
6 | from . import agents
7 | from . import memory
8 | from . import models
9 | from . import pipelines
10 | from . import service
11 | from . import message
12 | from . import prompt
13 | from . import web
14 | from . import exception
15 | from . import parsers
16 | from . import rag
17 |
18 | # objects or function
19 | from .msghub import msghub
20 | from ._version import __version__
21 | from ._init import init
22 | from ._init import print_llm_usage
23 | from ._init import state_dict
24 |
25 | __all__ = [
26 | "init",
27 | "state_dict",
28 | "print_llm_usage",
29 | "msghub",
30 | ]
31 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/_version.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """ Version of AgentScope."""
3 |
4 | __version__ = "0.0.6alpha3"
5 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/agents/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """ Import all agent related modules in the package. """
3 | from .agent import AgentBase, DistConf
4 | from .operator import Operator
5 | from .dialog_agent import DialogAgent
6 | from .dict_dialog_agent import DictDialogAgent
7 | from .user_agent import UserAgent
8 | from .text_to_image_agent import TextToImageAgent
9 | from .rpc_agent import RpcAgent
10 | from .react_agent import ReActAgent
11 | from .rag_agent import LlamaIndexAgent
12 | from .sci_agent import SciAgent
13 |
14 |
15 | __all__ = [
16 | "AgentBase",
17 | "Operator",
18 | "DialogAgent",
19 | "DictDialogAgent",
20 | "TextToImageAgent",
21 | "UserAgent",
22 | "ReActAgent",
23 | "DistConf",
24 | "RpcAgent",
25 | "LlamaIndexAgent",
26 | "SciAgent"
27 | ]
28 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/agents/dialog_agent.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """A general dialog agent."""
3 | from typing import Optional, Union, Sequence
4 |
5 | from ..message import Msg
6 | from .agent import AgentBase
7 |
8 |
9 | class DialogAgent(AgentBase):
10 | """A simple agent used to perform a dialogue. Your can set its role by
11 | `sys_prompt`."""
12 |
13 | def __init__(
14 | self,
15 | name: str,
16 | sys_prompt: str,
17 | model_config_name: str,
18 | use_memory: bool = True,
19 | memory_config: Optional[dict] = None,
20 | ) -> None:
21 | """Initialize the dialog agent.
22 |
23 | Arguments:
24 | name (`str`):
25 | The name of the agent.
26 | sys_prompt (`Optional[str]`):
27 | The system prompt of the agent, which can be passed by args
28 | or hard-coded in the agent.
29 | model_config_name (`str`):
30 | The name of the model config, which is used to load model from
31 | configuration.
32 | use_memory (`bool`, defaults to `True`):
33 | Whether the agent has memory.
34 | memory_config (`Optional[dict]`):
35 | The config of memory.
36 | """
37 | super().__init__(
38 | name=name,
39 | sys_prompt=sys_prompt,
40 | model_config_name=model_config_name,
41 | use_memory=use_memory,
42 | memory_config=memory_config,
43 | )
44 |
45 | def reply(self, x: Optional[Union[Msg, Sequence[Msg]]] = None) -> Msg:
46 | """Reply function of the agent. Processes the input data,
47 | generates a prompt using the current dialogue memory and system
48 | prompt, and invokes the language model to produce a response. The
49 | response is then formatted and added to the dialogue memory.
50 |
51 | Args:
52 | x (`Optional[Union[Msg, Sequence[Msg]]]`, defaults to `None`):
53 | The input message(s) to the agent, which also can be omitted if
54 | the agent doesn't need any input.
55 |
56 | Returns:
57 | `Msg`: The output message generated by the agent.
58 | """
59 | # record the input if needed
60 | if self.memory:
61 | self.memory.add(x)
62 |
63 | # prepare prompt
64 | prompt = self.model.format(
65 | Msg("system", self.sys_prompt, role="system"),
66 | self.memory
67 | and self.memory.get_memory()
68 | or x, # type: ignore[arg-type]
69 | )
70 |
71 | # call llm and generate response
72 | response = self.model(prompt)
73 |
74 | # Print/speak the message in this agent's voice
75 | # Support both streaming and non-streaming responses by "or"
76 | self.speak(response.stream or response.text)
77 |
78 | msg = Msg(self.name, response.text, role="assistant")
79 |
80 | # Record the message in memory
81 | if self.memory:
82 | self.memory.add(msg)
83 |
84 | return msg
85 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/agents/operator.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """A common base class for AgentBase and PipelineBase"""
3 | from abc import ABC
4 | from abc import abstractmethod
5 | from typing import Any
6 |
7 |
8 | class Operator(ABC):
9 | """
10 | Abstract base class `Operator` defines a protocol for classes that
11 | implement callable behavior.
12 | The class is designed to be subclassed with an overridden `__call__`
13 | method that specifies the execution logic for the operator.
14 | """
15 |
16 | @abstractmethod
17 | def __call__(self, *args: Any, **kwargs: Any) -> dict:
18 | """Calling function"""
19 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/agents/text_to_image_agent.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """An agent that convert text to image."""
3 |
4 | from typing import Optional, Union, Sequence
5 |
6 | from loguru import logger
7 |
8 | from .agent import AgentBase
9 | from ..message import Msg
10 |
11 |
12 | class TextToImageAgent(AgentBase):
13 | """
14 | A agent used to perform text to image tasks.
15 |
16 | TODO: change the agent into a service.
17 | """
18 |
19 | def __init__(
20 | self,
21 | name: str,
22 | model_config_name: str,
23 | use_memory: bool = True,
24 | memory_config: Optional[dict] = None,
25 | ) -> None:
26 | """Initialize the text to image agent.
27 |
28 | Arguments:
29 | name (`str`):
30 | The name of the agent.
31 | model_config_name (`str`, defaults to None):
32 | The name of the model config, which is used to load model from
33 | configuration.
34 | use_memory (`bool`, defaults to `True`):
35 | Whether the agent has memory.
36 | memory_config (`Optional[dict]`):
37 | The config of memory.
38 | """
39 | super().__init__(
40 | name=name,
41 | sys_prompt="",
42 | model_config_name=model_config_name,
43 | use_memory=use_memory,
44 | memory_config=memory_config,
45 | )
46 |
47 | logger.warning(
48 | "The `TextToImageAgent` will be deprecated in v0.0.6, "
49 | "please use `text_to_image` service and `ReActAgent` instead.",
50 | )
51 |
52 | def reply(self, x: Optional[Union[Msg, Sequence[Msg]]] = None) -> Msg:
53 | if self.memory:
54 | self.memory.add(x)
55 | if x is None:
56 | # get the last message from memory
57 | if self.memory and self.memory.size() > 0:
58 | x = self.memory.get_memory()[-1]
59 | else:
60 | return Msg(
61 | self.name,
62 | content="Please provide a text prompt to generate image.",
63 | role="assistant",
64 | )
65 | image_urls = self.model(x.content).image_urls
66 | # TODO: optimize the construction of content
67 | msg = Msg(
68 | self.name,
69 | content="This is the generated image",
70 | role="assistant",
71 | url=image_urls,
72 | )
73 |
74 | self.speak(msg)
75 |
76 | if self.memory:
77 | self.memory.add(msg)
78 |
79 | return msg
80 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/constants.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """ Some constants used in the project"""
3 | from numbers import Number
4 | from enum import IntEnum
5 |
6 | from pathlib import Path
7 |
8 | PACKAGE_NAME = "agentscope"
9 | MSG_TOKEN = f"[{PACKAGE_NAME}_msg]"
10 |
11 |
12 | # default values
13 | _RUNTIME_TIMESTAMP_FORMAT = "%Y-%m-%d %H:%M:%S"
14 | _RUNTIME_ID_FORMAT = "run_%Y%m%d-%H%M%S_{}"
15 |
16 | # for file manager
17 | _DEFAULT_SAVE_DIR = "./runs"
18 | _DEFAULT_LOG_LEVEL = "INFO"
19 | _DEFAULT_SUBDIR_CODE = "code"
20 | _DEFAULT_SUBDIR_FILE = "file"
21 | _DEFAULT_SUBDIR_INVOKE = "invoke"
22 | _DEFAULT_CACHE_DIR = str(Path.home() / ".cache" / "agentscope")
23 | _DEFAULT_CFG_NAME = ".config"
24 | _DEFAULT_IMAGE_NAME = "image_{}_{}.png"
25 | _DEFAULT_SQLITE_DB_NAME = "agentscope.db"
26 |
27 |
28 | # for model wrapper
29 | _DEFAULT_MAX_RETRIES = 3
30 | _DEFAULT_MESSAGES_KEY = "messages"
31 | _DEFAULT_RETRY_INTERVAL = 1
32 | _DEFAULT_API_BUDGET = None
33 | # for execute python
34 | _DEFAULT_PYPI_MIRROR = "http://mirrors.aliyun.com/pypi/simple/"
35 | _DEFAULT_TRUSTED_HOST = "mirrors.aliyun.com"
36 | # for monitor
37 | _DEFAULT_TABLE_NAME_FOR_CHAT_AND_EMBEDDING = "chat_and_embedding_model_monitor"
38 | _DEFAULT_TABLE_NAME_FOR_IMAGE = "image_model_monitor"
39 | # for summarization
40 | _DEFAULT_SUMMARIZATION_PROMPT = """
41 | TEXT: {}
42 | """
43 | _DEFAULT_SYSTEM_PROMPT = """
44 | You are a helpful agent to summarize the text.
45 | You need to keep all the key information of the text in the summary.
46 | """
47 | _DEFAULT_TOKEN_LIMIT_PROMPT = """
48 | Summarize the text after TEXT in less than {} tokens:
49 | """
50 |
51 | # typing
52 | Embedding = list[Number]
53 |
54 | # rpc
55 |
56 | # set max message size to 32 MB
57 | _DEFAULT_RPC_OPTIONS = [
58 | ("grpc.max_send_message_length", 32 * 1024 * 1024),
59 | ("grpc.max_receive_message_length", 32 * 1024 * 1024),
60 | ]
61 |
62 |
63 | # enums
64 | class ResponseFormat(IntEnum):
65 | """Enum for model response format."""
66 |
67 | NONE = 0
68 | JSON = 1
69 |
70 |
71 | class ShrinkPolicy(IntEnum):
72 | """Enum for shrink strategies when the prompt is too long."""
73 |
74 | TRUNCATE = 0
75 | SUMMARIZE = 1
76 |
77 |
78 | # rag related
79 | DEFAULT_CHUNK_SIZE = 1024
80 | DEFAULT_CHUNK_OVERLAP = 20
81 | DEFAULT_TOP_K = 5
82 |
83 | # flask server
84 | EXPIRATION_SECONDS = 604800 # One week
85 | TOKEN_EXP_TIME = 1440 # One day long
86 | FILE_SIZE_LIMIT = 1024 * 1024 # 10 MB
87 | FILE_COUNT_LIMIT = 10
88 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/file_manager.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/open-sciencelab/Virtual-Scientists/9a6d0f32f9adbccef68f70f1705fa12fc9d10e23/agentscope-main/src/agentscope/file_manager.py
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/manager/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """Import all manager related classes and functions."""
3 |
4 | from ._monitor import MonitorManager
5 | from ._file import FileManager
6 | from ._model import ModelManager
7 | from ._manager import ASManager
8 |
9 | __all__ = [
10 | "FileManager",
11 | "ModelManager",
12 | "MonitorManager",
13 | "ASManager",
14 | ]
15 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/memory/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | """
4 | import al memory related modules
5 | """
6 |
7 | from .memory import MemoryBase
8 | from .temporary_memory import TemporaryMemory
9 |
10 | __all__ = [
11 | "MemoryBase",
12 | "TemporaryMemory",
13 | ]
14 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/message/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """The message module of AgentScope."""
3 |
4 | from .msg import Msg, MessageBase
5 | from .placeholder import PlaceholderMessage, deserialize, serialize
6 |
7 | __all__ = [
8 | "Msg",
9 | "MessageBase",
10 | "deserialize",
11 | "serialize",
12 | ]
13 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/models/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """ Import modules in models package."""
3 | from typing import Type
4 |
5 | from loguru import logger
6 |
7 | from .model import ModelWrapperBase
8 | from .response import ModelResponse
9 | from .post_model import (
10 | PostAPIModelWrapperBase,
11 | PostAPIChatWrapper,
12 | )
13 | from .openai_model import (
14 | OpenAIWrapperBase,
15 | OpenAIChatWrapper,
16 | OpenAIDALLEWrapper,
17 | OpenAIEmbeddingWrapper,
18 | )
19 | from .dashscope_model import (
20 | DashScopeChatWrapper,
21 | DashScopeImageSynthesisWrapper,
22 | DashScopeTextEmbeddingWrapper,
23 | DashScopeMultiModalWrapper,
24 | )
25 | from .ollama_model import (
26 | OllamaChatWrapper,
27 | OllamaEmbeddingWrapper,
28 | OllamaGenerationWrapper,
29 | )
30 | from .gemini_model import (
31 | GeminiChatWrapper,
32 | GeminiEmbeddingWrapper,
33 | )
34 | from .zhipu_model import (
35 | ZhipuAIChatWrapper,
36 | ZhipuAIEmbeddingWrapper,
37 | )
38 | from .litellm_model import (
39 | LiteLLMChatWrapper,
40 | )
41 |
42 |
43 | __all__ = [
44 | "ModelWrapperBase",
45 | "ModelResponse",
46 | "PostAPIModelWrapperBase",
47 | "PostAPIChatWrapper",
48 | "OpenAIWrapperBase",
49 | "OpenAIChatWrapper",
50 | "OpenAIDALLEWrapper",
51 | "OpenAIEmbeddingWrapper",
52 | "DashScopeChatWrapper",
53 | "DashScopeImageSynthesisWrapper",
54 | "DashScopeTextEmbeddingWrapper",
55 | "DashScopeMultiModalWrapper",
56 | "OllamaChatWrapper",
57 | "OllamaEmbeddingWrapper",
58 | "OllamaGenerationWrapper",
59 | "GeminiChatWrapper",
60 | "GeminiEmbeddingWrapper",
61 | "ZhipuAIChatWrapper",
62 | "ZhipuAIEmbeddingWrapper",
63 | "LiteLLMChatWrapper",
64 | ]
65 |
66 |
67 | def _get_model_wrapper(model_type: str) -> Type[ModelWrapperBase]:
68 | """Get the specific type of model wrapper
69 |
70 | Args:
71 | model_type (`str`): The model type name.
72 |
73 | Returns:
74 | `Type[ModelWrapperBase]`: The corresponding model wrapper class.
75 | """
76 | wrapper = ModelWrapperBase.get_wrapper(model_type=model_type)
77 | if wrapper is None:
78 | logger.warning(
79 | f"Unsupported model_type [{model_type}],"
80 | "use PostApiModelWrapper instead.",
81 | )
82 | return PostAPIModelWrapperBase
83 | return wrapper
84 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/models/_model_utils.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """Utils for models"""
3 |
4 |
5 | def _verify_text_content_in_openai_delta_response(response: dict) -> bool:
6 | """Verify if the text content exists in the openai streaming response
7 |
8 | Args:
9 | response (`dict`):
10 | The JSON-format OpenAI response (After calling `model_dump`
11 | function)
12 |
13 | Returns:
14 | `bool`: If the text content exists
15 | """
16 |
17 | if len(response.get("choices", [])) == 0:
18 | return False
19 |
20 | if response["choices"][0].get("delta", None) is None:
21 | return False
22 |
23 | if response["choices"][0]["delta"].get("content", None) is None:
24 | return False
25 |
26 | return True
27 |
28 |
29 | def _verify_text_content_in_openai_message_response(response: dict) -> bool:
30 | """Verify if the text content exists in the openai streaming response
31 |
32 | Args:
33 | response (`dict`):
34 | The JSON-format OpenAI response (After calling `model_dump`
35 | function)
36 |
37 | Returns:
38 | `bool`: If the text content exists
39 | """
40 |
41 | if len(response.get("choices", [])) == 0:
42 | return False
43 |
44 | if response["choices"][0].get("message", None) is None:
45 | return False
46 |
47 | if response["choices"][0]["message"].get("content", None) is None:
48 | return False
49 |
50 | return True
51 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/parsers/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """Model response parser module."""
3 | from .parser_base import ParserBase
4 | from .json_object_parser import (
5 | MarkdownJsonObjectParser,
6 | MarkdownJsonDictParser,
7 | )
8 | from .code_block_parser import MarkdownCodeBlockParser
9 | from .regex_tagged_content_parser import RegexTaggedContentParser
10 | from .tagged_content_parser import (
11 | TaggedContent,
12 | MultiTaggedContentParser,
13 | )
14 |
15 |
16 | __all__ = [
17 | "ParserBase",
18 | "MarkdownJsonObjectParser",
19 | "MarkdownJsonDictParser",
20 | "MarkdownCodeBlockParser",
21 | "TaggedContent",
22 | "MultiTaggedContentParser",
23 | "RegexTaggedContentParser",
24 | ]
25 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/parsers/code_block_parser.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """Model response parser class for Markdown code block."""
3 | from typing import Optional
4 |
5 | from agentscope.models import ModelResponse
6 | from agentscope.parsers import ParserBase
7 |
8 |
9 | class MarkdownCodeBlockParser(ParserBase):
10 | """The base class for parsing the response text by fenced block."""
11 |
12 | name: str = "{language_name} block"
13 | """The name of the parser."""
14 |
15 | tag_begin: str = "```{language_name}"
16 | """The beginning tag."""
17 |
18 | content_hint: str = "${{your_{language_name}_code}}"
19 | """The hint of the content."""
20 |
21 | tag_end: str = "```"
22 | """The ending tag."""
23 |
24 | format_instruction: str = (
25 | "You should generate {language_name} code in a {language_name} fenced "
26 | "code block as follows: \n```{language_name}\n"
27 | "{content_hint}\n```"
28 | )
29 | """The instruction for the format of the code block."""
30 |
31 | def __init__(
32 | self,
33 | language_name: str,
34 | content_hint: Optional[str] = None,
35 | ) -> None:
36 | """Initialize the parser with the language name and the optional
37 | content hint.
38 |
39 | Args:
40 | language_name (`str`):
41 | The name of the language, which will be used
42 | in ```{language_name}
43 | content_hint (`Optional[str]`, defaults to `None`):
44 | The hint used to remind LLM what should be fill between the
45 | tags. If not provided, the default content hint
46 | "${{your_{language_name}_code}}" will be used.
47 | """
48 | self.name = self.name.format(language_name=language_name)
49 | self.tag_begin = self.tag_begin.format(language_name=language_name)
50 |
51 | if content_hint is None:
52 | self.content_hint = f"${{your_{language_name}_code}}"
53 | else:
54 | self.content_hint = content_hint
55 |
56 | self.format_instruction = self.format_instruction.format(
57 | language_name=language_name,
58 | content_hint=self.content_hint,
59 | ).strip()
60 |
61 | def parse(self, response: ModelResponse) -> ModelResponse:
62 | """Extract the content between the tag_begin and tag_end in the
63 | response and store it in the parsed field of the response object.
64 | """
65 |
66 | extract_text = self._extract_first_content_by_tag(
67 | response,
68 | self.tag_begin,
69 | self.tag_end,
70 | )
71 | response.parsed = extract_text
72 | return response
73 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/pipelines/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """ Import all pipeline related modules in the package. """
3 | from .pipeline import (
4 | PipelineBase,
5 | SequentialPipeline,
6 | IfElsePipeline,
7 | SwitchPipeline,
8 | ForLoopPipeline,
9 | WhileLoopPipeline,
10 | )
11 |
12 | from .functional import (
13 | sequentialpipeline,
14 | ifelsepipeline,
15 | switchpipeline,
16 | forlooppipeline,
17 | whilelooppipeline,
18 | )
19 |
20 | __all__ = [
21 | "PipelineBase",
22 | "SequentialPipeline",
23 | "IfElsePipeline",
24 | "SwitchPipeline",
25 | "ForLoopPipeline",
26 | "WhileLoopPipeline",
27 | "sequentialpipeline",
28 | "ifelsepipeline",
29 | "switchpipeline",
30 | "forlooppipeline",
31 | "whilelooppipeline",
32 | ]
33 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/prompt/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """ Import all prompt related modules in the package. """
3 |
4 | from ._prompt_generator_base import SystemPromptGeneratorBase
5 | from ._prompt_generator_zh import ChineseSystemPromptGenerator
6 | from ._prompt_generator_en import EnglishSystemPromptGenerator
7 | from ._prompt_comparer import SystemPromptComparer
8 | from ._prompt_optimizer import SystemPromptOptimizer
9 | from ._prompt_engine import PromptEngine
10 |
11 |
12 | __all__ = [
13 | "PromptEngine",
14 | "SystemPromptGeneratorBase",
15 | "ChineseSystemPromptGenerator",
16 | "EnglishSystemPromptGenerator",
17 | "SystemPromptComparer",
18 | "SystemPromptOptimizer",
19 | ]
20 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/prompt/_prompt_generator_zh.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """Prompt generator class."""
3 | from typing import List, Literal, Optional
4 |
5 | from ._prompt_generator_base import SystemPromptGeneratorBase
6 | from ._prompt_utils import _DEFAULT_EXAMPLE_LIST_ZH
7 |
8 | _DEFAULT_META_PROMPT_ZH = """
9 | 你是一个擅长写和优化system prompt的专家。你的任务是优化用户提供的prompt, 使得优化后的system prompt包含对agent的角色或者性格描述,agent的技能点,和一些限制。
10 |
11 | ## 注意
12 | 1. 优化后的system prompt必须与用户原始prompt意图一致,可适当加入可调用的工具、具体关键词、时间框架、上下文或任何可以缩小范围并指导agent能够更好地理解完成任务的附加信息,对用户的prompt进行重构。
13 | 2. 请注意角色描述和技能点的描述不能缩小用户原始prompt定义的范围。例如用户原始prompt里描述的是文案大师,优化后的prompt描述不能缩小范围变成小红书文案大师。
14 | 3. 对技能点的描述应该尽量详细准确。用户原始的prompt会提到一些示例,技能点应该能覆盖这些案例,但注意不能只局限于用户prompt里给的示例。例如用户原始prompt里提到出题机器人可以出填空题的考题的示例,优化后的prompt里技能点不能只包括出填空题。
15 | 4. 技能范围不能超过大模型的能力,如果超过,请必须注明需要调用哪些工具,或者需要哪些知识库来帮助大模型拥有这个技能。比如大模型并没有搜索功能,如果需要搜索,则需要调用搜索工具来实现。
16 | 5. 请以markdown的格式输出优化后的prompt。
17 | 6. 优化后的prompt必须语言简练,字数不超过1000字。
18 | 7. 如果用户提供的prompt包含知识库或者Memory部分,优化后的system prompt也必须保留这些部分。
19 | 8. 如果prompt中含有如下标识符的变量:${{variable}}, 请确保改变量在优化后的prompt里只出现一次,在其他要使用该变量的地方直接使用该变量名。例如${{document}}再次出现的时候,请直接使用"检索内容"。
20 | 9. 优化后的prompt语言与用户提供的prompt一致,即用户提供的prompt使用中文写的,优化后的prompt也必须是中文, 如果用户提供的prompt使用英文写的,优化后的prompt也必须是英文。
21 | """ # noqa
22 |
23 | _DEFAULT_EXAMPLE_PROMPT_TEMPLATE_ZH = """## 样例{index}
24 | - 用户输入:
25 | ```
26 | {user_prompt}
27 | ```
28 |
29 | - 优化后的system prompt:
30 | ```
31 | {opt_prompt}
32 | ```
33 | """
34 |
35 | _DEFAULT_RESPONSE_PROMPT_TEMPLATE_ZH = """## 用户输入
36 | ```
37 | {user_prompt}
38 | ```
39 |
40 | ## 优化后的system prompt
41 | """
42 |
43 | # The name of the default local embedding model, which is used when
44 | # `embed_model_config_name` is not provided.
45 | _DEFAULT_LOCAL_EMBEDDING_MODEL = "sentence-transformers/all-mpnet-base-v2"
46 |
47 |
48 | class ChineseSystemPromptGenerator(SystemPromptGeneratorBase):
49 | """Optimize the users' system prompt with the given meta prompt and
50 | examples if provided."""
51 |
52 | def __init__(
53 | self,
54 | model_config_name: str,
55 | meta_prompt: str = _DEFAULT_META_PROMPT_ZH,
56 | response_prompt_template: str = _DEFAULT_RESPONSE_PROMPT_TEMPLATE_ZH,
57 | example_num: int = 0,
58 | example_list: List = _DEFAULT_EXAMPLE_LIST_ZH,
59 | example_selection_strategy: Literal["random", "similarity"] = "random",
60 | example_prompt_template: str = _DEFAULT_EXAMPLE_PROMPT_TEMPLATE_ZH,
61 | embed_model_config_name: Optional[str] = None,
62 | local_embedding_model: str = _DEFAULT_LOCAL_EMBEDDING_MODEL,
63 | ):
64 | super().__init__(
65 | model_config_name=model_config_name,
66 | meta_prompt=meta_prompt,
67 | response_prompt_template=response_prompt_template,
68 | example_num=example_num,
69 | example_list=example_list,
70 | example_selection_strategy=example_selection_strategy,
71 | example_prompt_template=example_prompt_template,
72 | embed_model_config_name=embed_model_config_name,
73 | local_embedding_model=local_embedding_model,
74 | )
75 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/prompt/_prompt_utils.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """Utility functions for prompt optimization."""
3 | import json
4 | from typing import List
5 |
6 | from pathlib import Path
7 | import numpy as np
8 |
9 | from scipy.spatial.distance import cdist
10 |
11 |
12 | def _find_top_k_embeddings(
13 | query_embedding: List[float],
14 | list_embeddings: List[List[float]],
15 | k: int,
16 | ) -> List:
17 | """
18 | Find the top k embeddings that are closed to the query embedding.
19 |
20 | Args:
21 | query_embedding (`List[float]`):
22 | the query to be searched.
23 | list_embeddings (`List[List[float]]`):
24 | the list of embeddings to be searched.
25 | k (`int`):
26 | the number of embeddings to be returned.
27 | Returns:
28 | `List`:
29 | the list of indices of the top k embeddings.
30 | """
31 | # Compute cosine similarity between the query and the list of embeddings.
32 | # cdist returns the distance of 2-dimension arrays,
33 | # so we subtract from 1 to get similarity.
34 | # Cosine distance is defined as 1.0 minus the cosine similarity.
35 |
36 | similarities = (
37 | 1 - cdist([query_embedding], list_embeddings, "cosine").flatten()
38 | )
39 |
40 | # Get the top k indices sorted by similarity (in descending order).
41 | return list(np.argsort(similarities)[::-1][:k])
42 |
43 |
44 | def _read_json_same_dir(file_name: str) -> dict:
45 | """Read the json file in the same dir"""
46 | current_file_path = Path(__file__)
47 |
48 | json_file_path = current_file_path.parent / file_name
49 |
50 | with open(json_file_path, "r", encoding="utf-8") as file:
51 | data = json.load(file)
52 |
53 | return data
54 |
55 |
56 | _examples = _read_json_same_dir("_prompt_examples.json")
57 |
58 | _DEFAULT_EXAMPLE_LIST_EN = _examples["en"]
59 |
60 | _DEFAULT_EXAMPLE_LIST_ZH = _examples["zh"]
61 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/rag/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """ Import all pipeline related modules in the package. """
3 | from .knowledge import Knowledge
4 | from .llama_index_knowledge import LlamaIndexKnowledge
5 | from .knowledge_bank import KnowledgeBank
6 |
7 | __all__ = [
8 | "Knowledge",
9 | "LlamaIndexKnowledge",
10 | "KnowledgeBank",
11 | ]
12 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/rpc/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """Import all rpc related modules in the package."""
3 | from .rpc_agent_client import RpcAgentClient, ResponseStub, call_in_thread
4 |
5 | try:
6 | from .rpc_agent_pb2 import RpcMsg # pylint: disable=E0611
7 | from .rpc_agent_pb2_grpc import RpcAgentServicer
8 | from .rpc_agent_pb2_grpc import RpcAgentStub
9 | from .rpc_agent_pb2_grpc import add_RpcAgentServicer_to_server
10 | except ImportError as import_error:
11 | from agentscope.utils.tools import ImportErrorReporter
12 |
13 | RpcMsg = ImportErrorReporter(import_error, "distribute") # type: ignore[misc]
14 | RpcAgentServicer = ImportErrorReporter(import_error, "distribute")
15 | RpcAgentStub = ImportErrorReporter(import_error, "distribute")
16 | add_RpcAgentServicer_to_server = ImportErrorReporter(
17 | import_error,
18 | "distribute",
19 | )
20 |
21 |
22 | __all__ = [
23 | "RpcAgentClient",
24 | "ResponseStub",
25 | "RpcMsg",
26 | "RpcAgentServicer",
27 | "RpcAgentStub",
28 | "call_in_thread",
29 | "add_RpcAgentServicer_to_server",
30 | ]
31 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/rpc/rpc_agent.proto:
--------------------------------------------------------------------------------
1 | syntax = "proto3";
2 |
3 | import "google/protobuf/empty.proto";
4 |
5 | // Servicer for rpc agent server
6 | service RpcAgent {
7 | // check server is alive
8 | rpc is_alive (google.protobuf.Empty) returns (GeneralResponse) {}
9 |
10 | // stop the server
11 | rpc stop (google.protobuf.Empty) returns (GeneralResponse) {}
12 |
13 | // create a new agent on the server
14 | rpc create_agent (CreateAgentRequest) returns (GeneralResponse) {}
15 |
16 | // delete agent from the server
17 | rpc delete_agent (StringMsg) returns (GeneralResponse) {}
18 |
19 | // clear all agent on the server
20 | rpc delete_all_agents (google.protobuf.Empty) returns (GeneralResponse) {}
21 |
22 | // clone an agent with specific agent_id
23 | rpc clone_agent (StringMsg) returns (GeneralResponse) {}
24 |
25 | // get id of all agents on the server as a list
26 | rpc get_agent_list (google.protobuf.Empty) returns (GeneralResponse) {}
27 |
28 | // get the resource utilization information of the server
29 | rpc get_server_info(google.protobuf.Empty) returns (GeneralResponse) {}
30 |
31 | // update the model configs in the server
32 | rpc set_model_configs(StringMsg) returns (GeneralResponse) {}
33 |
34 | // get memory of a specific agent
35 | rpc get_agent_memory (StringMsg) returns (GeneralResponse) {}
36 |
37 | // call funcs of agent running on the server
38 | rpc call_agent_func(RpcMsg) returns (GeneralResponse) {}
39 |
40 | // update value of PlaceholderMessage
41 | rpc update_placeholder(UpdatePlaceholderRequest) returns (GeneralResponse) {}
42 |
43 | // file transfer
44 | rpc download_file(StringMsg) returns (stream ByteMsg) {}
45 | }
46 |
47 | // Message classes for agent server management
48 | message GeneralResponse {
49 | bool ok = 1;
50 | string message = 2;
51 | }
52 |
53 | message CreateAgentRequest {
54 | string agent_id = 1;
55 | bytes agent_init_args = 2;
56 | bytes agent_source_code = 3;
57 | }
58 |
59 | message AgentStatus {
60 | string agent_id = 1;
61 | string status = 2;
62 | }
63 |
64 | message UpdatePlaceholderRequest {
65 | int64 task_id = 1;
66 | }
67 |
68 | message StringMsg {
69 | string value = 1;
70 | }
71 |
72 | message ByteMsg {
73 | bytes data = 1;
74 | }
75 |
76 | // Message class for agent function call
77 | message RpcMsg {
78 | string value = 1;
79 | string target_func = 2;
80 | string agent_id = 3;
81 | }
82 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/server/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """Import all server related modules in the package."""
3 | from .launcher import RpcAgentServerLauncher, as_server
4 | from .servicer import AgentServerServicer
5 |
6 | __all__ = [
7 | "RpcAgentServerLauncher",
8 | "AgentServerServicer",
9 | "as_server",
10 | ]
11 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/service/execute_code/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/open-sciencelab/Virtual-Scientists/9a6d0f32f9adbccef68f70f1705fa12fc9d10e23/agentscope-main/src/agentscope/service/execute_code/__init__.py
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/service/execute_code/exec_shell.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """Service to execute shell commands."""
3 | import subprocess
4 |
5 | from loguru import logger
6 |
7 | from agentscope.service.service_status import ServiceExecStatus
8 | from agentscope.service.service_response import ServiceResponse
9 |
10 |
11 | def execute_shell_command(command: str) -> ServiceResponse:
12 | """
13 | Executes a given shell command.
14 |
15 | Args:
16 | command (str): The shell command to execute.
17 |
18 | Returns:
19 | ServiceResponse: Contains either the output from the shell command as a
20 | string if sucessful, or an error message include the error type.
21 |
22 | Note:
23 | Use any bash/shell commands you want (e.g. find, grep, cat, ls),
24 | but note that :
25 | 1. interactive session commands (e.g. python, vim) or commands that
26 | change current state (e.g. cd that change the current directory)
27 | are NOT supported yet, so please do not invoke them.
28 | 2. be VERY CAREFUL when using commands that will
29 | change/edit the files current directory (e.g. rm, sed).
30 | ...
31 | """
32 |
33 | if any(_ in command for _ in execute_shell_command.insecure_commands):
34 | logger.warning(
35 | f"The command {command} is blocked for security reasons. "
36 | f"If you want to enable the command, try to reset the "
37 | f"insecure command list by executing "
38 | f'`execute_shell_command.insecure_commands = ["xxx", "xxx"]`',
39 | )
40 | return ServiceResponse(
41 | status=ServiceExecStatus.ERROR,
42 | content=f"The command {command} is blocked for security reasons.",
43 | )
44 |
45 | try:
46 | result = subprocess.run(
47 | command,
48 | shell=True,
49 | check=True,
50 | stdout=subprocess.PIPE,
51 | stderr=subprocess.PIPE,
52 | text=True,
53 | )
54 | return ServiceResponse(
55 | status=ServiceExecStatus.SUCCESS,
56 | content=result.stdout.strip() if result.stdout else "Success.",
57 | )
58 | except subprocess.CalledProcessError as e:
59 | error_message = (
60 | e.stderr.strip()
61 | if e.stderr
62 | else "An error occurred \
63 | while executing the command."
64 | )
65 | return ServiceResponse(
66 | status=ServiceExecStatus.ERROR,
67 | content=error_message,
68 | )
69 | except Exception as e:
70 | return ServiceResponse(
71 | status=ServiceExecStatus.ERROR,
72 | content=str(e),
73 | )
74 |
75 |
76 | # Security check: Block insecure commands
77 | execute_shell_command.insecure_commands = [
78 | # System management
79 | "shutdown",
80 | "kill",
81 | "reboot",
82 | "pkill",
83 | # User management
84 | "useradd",
85 | "userdel",
86 | "usermod",
87 | # File management
88 | "rm -rf",
89 | ]
90 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/service/file/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/open-sciencelab/Virtual-Scientists/9a6d0f32f9adbccef68f70f1705fa12fc9d10e23/agentscope-main/src/agentscope/service/file/__init__.py
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/service/file/json.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """ Operators for json file and directory. """
3 | import json
4 | import os
5 | from typing import Any
6 |
7 | from agentscope.service.service_response import ServiceResponse
8 | from agentscope.service.service_status import ServiceExecStatus
9 |
10 |
11 | def read_json_file(file_path: str) -> ServiceResponse:
12 | """
13 | Read and parse a JSON file.
14 |
15 | Args:
16 | file_path (`str`):
17 | The path to the JSON file to be read.
18 |
19 | Returns:
20 | `ServiceResponse`: Where the boolean indicates success, the
21 | Any is the parsed JSON content (typically a dict), and the str contains
22 | an error message if any, including the error type.
23 | """
24 | try:
25 | with open(file_path, "r", encoding="utf-8") as file:
26 | return ServiceResponse(
27 | status=ServiceExecStatus.SUCCESS,
28 | content=f"{json.load(file)}",
29 | )
30 | except Exception as e:
31 | error_message = f"{e.__class__.__name__}: {e}"
32 | return ServiceResponse(
33 | status=ServiceExecStatus.ERROR,
34 | content=error_message,
35 | )
36 |
37 |
38 | def write_json_file(
39 | file_path: str,
40 | data: Any,
41 | overwrite: bool = False,
42 | ) -> ServiceResponse:
43 | """
44 | Serialize data to a JSON file.
45 |
46 | Args:
47 | file_path (`str`):
48 | The path to the file where the JSON data will be written.
49 | data (`Any`):
50 | The data to serialize to JSON.
51 | overwrite (`bool`):
52 | Whether to overwrite the file if it already exists.
53 |
54 | Returns:
55 | `ServiceResponse`: where the boolean indicates success, and the
56 | str contains an error message if any, including the error type.
57 | """
58 | if not overwrite and os.path.exists(file_path):
59 | return ServiceResponse(
60 | status=ServiceExecStatus.ERROR,
61 | content="FileExistsError: The file already exists.",
62 | )
63 | try:
64 | with open(file_path, "w", encoding="utf-8") as file:
65 | json.dump(data, file, ensure_ascii=False, indent=4)
66 | return ServiceResponse(
67 | status=ServiceExecStatus.SUCCESS,
68 | content="Success",
69 | )
70 | except Exception as e:
71 | error_message = f"{e.__class__.__name__}: {e}"
72 | return ServiceResponse(
73 | status=ServiceExecStatus.ERROR,
74 | content=error_message,
75 | )
76 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/service/file/text.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """ Operators for txt file and directory. """
3 | import os
4 |
5 | from agentscope.utils.common import write_file
6 | from agentscope.service.service_response import ServiceResponse
7 | from agentscope.service.service_status import ServiceExecStatus
8 |
9 |
10 | def read_text_file(file_path: str) -> ServiceResponse:
11 | """
12 | Read the content of the text file.
13 |
14 | Args:
15 | file_path (`str`):
16 | The path to the text file to be read.
17 |
18 | Returns:
19 | `ServiceResponse`: A tuple (bool, str) where the boolean indicates
20 | success, and the str contains the file content or an error message
21 | if any, including the error type.
22 | """
23 | try:
24 | with open(file_path, "r", encoding="utf-8") as file:
25 | return ServiceResponse(
26 | status=ServiceExecStatus.SUCCESS,
27 | content=file.read(),
28 | )
29 | except Exception as e:
30 | error_message = f"{e.__class__.__name__}: {e}"
31 | return ServiceResponse(
32 | status=ServiceExecStatus.ERROR,
33 | content=error_message,
34 | )
35 |
36 |
37 | def write_text_file(
38 | file_path: str,
39 | content: str,
40 | overwrite: bool = False,
41 | ) -> ServiceResponse:
42 | """
43 | Write content to a text file.
44 |
45 | Args:
46 | file_path (`str`):
47 | The path to the file where content will be written.
48 | content (`str`):
49 | Content to write into the file.
50 | overwrite (`bool`, defaults to `False`):
51 | Whether to overwrite the file if it already exists.
52 |
53 | Returns:
54 | `ServiceResponse`: where the boolean indicates success, and the
55 | str contains an error message if any, including the error type.
56 | """
57 | if not overwrite and os.path.exists(file_path):
58 | return ServiceResponse(
59 | status=ServiceExecStatus.ERROR,
60 | content="FileExistsError: The file already exists.",
61 | )
62 | return write_file(content, file_path)
63 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/service/multi_modality/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/open-sciencelab/Virtual-Scientists/9a6d0f32f9adbccef68f70f1705fa12fc9d10e23/agentscope-main/src/agentscope/service/multi_modality/__init__.py
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/service/retrieval/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/open-sciencelab/Virtual-Scientists/9a6d0f32f9adbccef68f70f1705fa12fc9d10e23/agentscope-main/src/agentscope/service/retrieval/__init__.py
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/service/retrieval/retrieval_from_list.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """Retrieve service working with memory specially."""
3 | from typing import Callable, Optional, Any, Sequence
4 | from loguru import logger
5 |
6 | from agentscope.service.service_response import ServiceResponse
7 | from agentscope.service.service_status import ServiceExecStatus
8 | from agentscope.models import ModelWrapperBase
9 |
10 |
11 | def retrieve_from_list(
12 | query: Any,
13 | knowledge: Sequence, # TODO: rename
14 | score_func: Callable[[Any, Any], float],
15 | top_k: int = None,
16 | embedding_model: Optional[ModelWrapperBase] = None,
17 | preserve_order: bool = True,
18 | ) -> ServiceResponse:
19 | """
20 | Retrieve data in a list.
21 |
22 | Memory retrieval with user-defined score function. The score function is
23 | expected to take the `query` and one of the element in 'knowledge' (a
24 | list). This function retrieves top-k elements in 'knowledge' with
25 | HIGHEST scores. If the 'query' is a dict but has no embedding,
26 | we use the embedding model to embed the query.
27 |
28 | Args:
29 | query (`Any`):
30 | A message to be retrieved.
31 | knowledge (`Sequence`):
32 | Data/knowledge to be retrieved from.
33 | score_func (`Callable[[Any, Any], float]`):
34 | User-defined function for comparing two messages.
35 | top_k (`int`, defaults to `None`):
36 | Maximum number of messages returned.
37 | embedding_model (`Optional[ModelWrapperBase]`, defaults to `None`):
38 | A model to embed the query/message.
39 | preserve_order (`bool`, defaults to `True`):
40 | Whether to preserve the original order of the retrieved data.
41 | Defaults to True.
42 |
43 | Returns:
44 | `ServiceResponse`: The top-k retrieved messages with HIGHEST scores.
45 | """
46 | if isinstance(query, dict):
47 | if embedding_model is not None and "embedding" not in query:
48 | query["embedding"] = embedding_model(
49 | [query],
50 | return_embedding_only=True,
51 | )
52 | elif embedding_model is None and "embedding" not in query:
53 | logger.warning(
54 | "Since the input query has no embedding, embedding model is "
55 | "is not provided either.",
56 | )
57 |
58 | # (score, index, object)
59 | scores = [
60 | (score_func(query, msg), i, msg) for i, msg in enumerate(knowledge)
61 | ]
62 |
63 | # ordered by score, and extract the top-k items with highest scores
64 | top_k = len(scores) if top_k is None else top_k
65 | ordered_top_k_scores = sorted(scores, key=lambda x: x[0], reverse=True)[
66 | :top_k
67 | ]
68 |
69 | # if keep the original order
70 | if preserve_order:
71 | # ordered by index
72 | content = sorted(ordered_top_k_scores, key=lambda x: x[1])
73 | else:
74 | content = ordered_top_k_scores
75 |
76 | # The returned content includes a list of triples of (score, index, object)
77 | return ServiceResponse(
78 | status=ServiceExecStatus.SUCCESS,
79 | content=content,
80 | )
81 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/service/retrieval/similarity.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """
3 | Similarity functions for retrieval
4 | """
5 | try:
6 | import numpy as np
7 | except ImportError:
8 | np = None
9 |
10 | from agentscope.service.service_status import ServiceExecStatus
11 | from agentscope.service.service_response import ServiceResponse
12 | from agentscope.constants import Embedding
13 |
14 |
15 | def cos_sim(
16 | a: Embedding,
17 | b: Embedding,
18 | ) -> ServiceResponse:
19 | """Compute the cosine similarity between two different embeddings
20 |
21 | Args:
22 | a (`Embedding`):
23 | Embedding
24 | b (`Embedding`):
25 | Embedding
26 |
27 | Returns:
28 | `ServiceResponse`: A float.
29 | """
30 | if not len(a) == len(b):
31 | return ServiceResponse(
32 | ServiceExecStatus.ERROR,
33 | "embedding length not equal",
34 | )
35 | a, b = np.array(a), np.array(b)
36 | return ServiceResponse(
37 | ServiceExecStatus.SUCCESS,
38 | np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)),
39 | )
40 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/service/service_response.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """ Service response module """
3 | from typing import Any
4 |
5 | from agentscope.service.service_status import ServiceExecStatus
6 |
7 |
8 | class ServiceResponse(dict):
9 | """Used to wrap the execution results of the services"""
10 |
11 | __setattr__ = dict.__setitem__
12 | __getattr__ = dict.__getitem__
13 |
14 | def __init__(
15 | self,
16 | status: ServiceExecStatus,
17 | content: Any,
18 | ):
19 | """Constructor of ServiceResponse
20 |
21 | Args:
22 | status (`ServiceExeStatus`):
23 | The execution status of the service.
24 | content (`Any`)
25 | If the argument`status` is `SUCCESS`, `content` is the
26 | response. We use `object` here to support various objects,
27 | e.g. str, dict, image, video, etc.
28 | Otherwise, `content` is the error message.
29 | """
30 | self.status = status
31 | self.content = content
32 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/service/service_status.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """ Enum for service execution status."""
3 | from enum import IntEnum
4 |
5 |
6 | class ServiceExecStatus(IntEnum):
7 | """Enum for service execution status."""
8 |
9 | SUCCESS = 1
10 | ERROR = -1
11 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/service/sql_query/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/open-sciencelab/Virtual-Scientists/9a6d0f32f9adbccef68f70f1705fa12fc9d10e23/agentscope-main/src/agentscope/service/sql_query/__init__.py
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/service/sql_query/mongodb.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """query in MongoDB """
3 | from typing import Optional, Any
4 |
5 | from ..service_response import ServiceResponse
6 | from ...service.service_status import ServiceExecStatus
7 |
8 | try:
9 | import pymongo.errors
10 | except ImportError:
11 | pymongo = None
12 |
13 |
14 | def query_mongodb(
15 | database: str,
16 | collection: str,
17 | query: dict,
18 | host: str,
19 | port: int,
20 | maxcount_results: Optional[int] = None,
21 | **kwargs: Any,
22 | ) -> ServiceResponse:
23 | """Execute query within MongoDB database.
24 |
25 | Args:
26 | database (`str`):
27 | The name of the database to use.
28 | collection (`str`):
29 | The name of the collection to use in mongodb.
30 | query (`dict`):
31 | The mongodb query to execute.
32 | host (`str`):
33 | The hostname or IP address of the MongoDB server.
34 | port (`int`):
35 | The port number of MongoDB server.
36 | maxcount_results (`int`, defaults to `None`):
37 | The maximum number of results to return. Defaults to `100` to
38 | avoid too many results.
39 | **kwargs:
40 |
41 | Returns:
42 | `ServiceResponse`: A `ServiceResponse` object that contains execution
43 | results or error message.
44 |
45 | Note:
46 | MongoDB is a little different from mysql and sqlite, for its
47 | operations corresponds to different functions. Now we only support
48 | `find` query and leave other operations in the future.
49 | """
50 | try:
51 | # Establish connection to MongoDB
52 | with pymongo.MongoClient(
53 | host=host,
54 | port=port,
55 | **kwargs,
56 | ) as mongo_client:
57 | db = mongo_client[database]
58 | coll = db[collection]
59 |
60 | # Perform the query
61 | if maxcount_results is not None:
62 | results = coll.find(query).limit(maxcount_results)
63 | else:
64 | results = coll.find(query)
65 |
66 | # mongo_client.close()
67 |
68 | # Convert the cursor to a list
69 | documents = list(results)
70 | return ServiceResponse(
71 | status=ServiceExecStatus.SUCCESS,
72 | content=documents,
73 | )
74 |
75 | except Exception as e:
76 | # mongo_client.close()
77 | return ServiceResponse(
78 | status=ServiceExecStatus.ERROR,
79 | # TODO: more specific error message
80 | content=str(e),
81 | )
82 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/service/sql_query/mysql.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """query in Mysql """
3 | from typing import Optional
4 | from typing import Any
5 |
6 | from ..service_response import ServiceResponse
7 | from ...utils.common import _if_change_database
8 | from ...service.service_status import ServiceExecStatus
9 |
10 | try:
11 | import pymysql
12 | except ImportError:
13 | pymysql = None
14 |
15 |
16 | def query_mysql(
17 | database: str,
18 | query: str,
19 | host: str,
20 | user: str,
21 | password: str,
22 | port: int,
23 | allow_change_data: bool = False,
24 | maxcount_results: Optional[int] = None,
25 | **kwargs: Any,
26 | ) -> ServiceResponse:
27 | """
28 | Execute query within MySQL database.
29 |
30 | Args:
31 | database (`str`):
32 | The name of the database to use.
33 | query (`str`):
34 | SQL query to execute.
35 | host (`str`):
36 | The host name or IP address of the MySQL server, e.g. "localhost".
37 | user (`str`):
38 | The username of the MySQL account to use.
39 | password (`str`):
40 | The password of the MySQL account to use.
41 | port (`str`):
42 | The port number of the MySQL server, e.g. 3306.
43 | allow_change_data (`bool`, defaults to `False`):
44 | Whether to allow changing data in the database. Defaults to
45 | `False` to avoid accidental changes to the database.
46 | maxcount_results (`int`, defaults to `None`):
47 | The maximum number of results to return. Defaults to `100` to
48 | avoid too many results.
49 |
50 | Returns:
51 | `ServiceResponse`: A `ServiceResponse` object that contains
52 | execution results or error message.
53 | """
54 |
55 | # Check if the query is safe
56 | if not allow_change_data and not _if_change_database(query):
57 | raise ValueError(
58 | "Unsafe SQL query detected. Only SELECT statements are allowed. "
59 | "If you want to allow changing data in the database, "
60 | "set `allow_change_data` to `True`.",
61 | )
62 |
63 | # Limit the number of results by adding LIMIT keywords if necessary
64 | if maxcount_results is not None:
65 | if "limit" not in query.lower():
66 | query += f" LIMIT {maxcount_results}"
67 |
68 | # Execute the query
69 | try:
70 | # Establish a connection to the database
71 | conn = pymysql.connect(
72 | host=host,
73 | port=port,
74 | user=user,
75 | password=password,
76 | database=database,
77 | **kwargs,
78 | )
79 |
80 | cursor = conn.cursor()
81 | cursor.execute(query)
82 |
83 | if _if_change_database(query):
84 | conn.commit()
85 |
86 | cursor.close()
87 | conn.close()
88 |
89 | # Fetch the results
90 | results = cursor.fetchall()
91 | return ServiceResponse(
92 | status=ServiceExecStatus.SUCCESS,
93 | content=results,
94 | )
95 | except Exception as e:
96 | return ServiceResponse(
97 | status=ServiceExecStatus.ERROR,
98 | # TODO: more specific error message
99 | content=str(e),
100 | )
101 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/service/sql_query/sqlite.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """ Query in sqlite """
3 | from typing import Optional
4 | from typing import Any
5 |
6 | from ...service.service_response import ServiceResponse
7 | from ...utils.common import _if_change_database
8 | from ...service.service_status import ServiceExecStatus
9 |
10 | try:
11 | import sqlite3
12 | except ImportError:
13 | sqlite3 = None
14 |
15 |
16 | def query_sqlite(
17 | database: str,
18 | query: str,
19 | allow_change_data: bool = False,
20 | maxcount_results: Optional[int] = None,
21 | **kwargs: Any,
22 | ) -> ServiceResponse:
23 | """Executes query within sqlite database.
24 |
25 | Args:
26 | database (`str`):
27 | The name of the database to use.
28 | query (`str`):
29 | The query to execute.
30 | allow_change_data (`bool`, defaults to `False`):
31 | Whether to allow changing data in the database. Defaults to
32 | `False` to avoid accidental changes to the database.
33 | maxcount_results (`int`, defaults to `None`):
34 | The maximum number of results to return.
35 |
36 | Returns:
37 | `ServiceResponse`: A `ServiceResponse` object that contains
38 | execution results or error message.
39 | """
40 |
41 | # Check if the query is safe
42 | if not allow_change_data and not _if_change_database(query):
43 | raise ValueError(
44 | "Unsafe SQL query detected. Only SELECT statements are allowed. "
45 | "If you want to allow changing data in the database, "
46 | "set `allow_change_data` to `True`.",
47 | )
48 |
49 | # Limit the number of results by adding LIMIT keywords if necessary
50 | if maxcount_results is not None:
51 | if "limit" not in query.lower():
52 | query += f" LIMIT {maxcount_results}"
53 |
54 | try:
55 | conn = sqlite3.connect(database, **kwargs)
56 | cursor = conn.cursor()
57 | cursor.execute(query)
58 | results = cursor.fetchall()
59 |
60 | # commit the change if needed
61 | if _if_change_database(query):
62 | conn.commit()
63 |
64 | cursor.close()
65 | conn.close()
66 |
67 | return ServiceResponse(
68 | status=ServiceExecStatus.SUCCESS,
69 | content=results,
70 | )
71 | except Exception as e:
72 | return ServiceResponse(
73 | status=ServiceExecStatus.ERROR,
74 | # TDOO: more specific error message
75 | content=str(e),
76 | )
77 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/service/text_processing/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/open-sciencelab/Virtual-Scientists/9a6d0f32f9adbccef68f70f1705fa12fc9d10e23/agentscope-main/src/agentscope/service/text_processing/__init__.py
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/service/text_processing/summarization.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """
3 | Service for text processing
4 | """
5 | from loguru import logger
6 |
7 | from agentscope.models import ModelWrapperBase
8 | from agentscope.service.service_status import ServiceExecStatus
9 | from agentscope.service.service_response import ServiceResponse
10 | from agentscope.message import Msg
11 | from agentscope.constants import _DEFAULT_SYSTEM_PROMPT
12 | from agentscope.constants import _DEFAULT_TOKEN_LIMIT_PROMPT
13 |
14 |
15 | def summarization(
16 | model: ModelWrapperBase,
17 | text: str,
18 | system_prompt: str = _DEFAULT_SYSTEM_PROMPT,
19 | max_return_token: int = -1,
20 | token_limit_prompt: str = _DEFAULT_TOKEN_LIMIT_PROMPT,
21 | ) -> ServiceResponse:
22 | """Summarize the input text.
23 |
24 | Summarization function (Notice: current version of token limitation is
25 | built with Open AI API)
26 |
27 | Args:
28 | model (`ModelWrapperBase`):
29 | Model used to summarize provided text.
30 | text (`str`):
31 | Text to be summarized by the model.
32 | system_prompt (`str`, defaults to `_DEFAULT_SYSTEM_PROMPT`):
33 | Prompts as instruction for the system, will be as an instruction
34 | for the model.
35 | max_return_token (`int`, defaults to `-1`):
36 | Whether provide additional prompting instruction to limit the
37 | number of tokens in summarization returned by the model.
38 | token_limit_prompt (`str`, defaults to `_DEFAULT_TOKEN_LIMIT_PROMPT`):
39 | Prompt to instruct the model follow token limitation.
40 |
41 | Returns:
42 | `ServiceResponse`: If the model successfully summarized the text, and
43 | the summarization satisfies the provided token limitation, return
44 | `ServiceResponse` with `ServiceExecStatus.SUCCESS`; otherwise return
45 | `ServiceResponse` with `ServiceExecStatus.ERROR` (if the summary is
46 | return successfully but exceed the token limits, the content
47 | contains the summary as well).
48 |
49 | Example:
50 |
51 | The default message with `text` to be summarized:
52 |
53 | .. code-block:: python
54 |
55 | [
56 | {
57 | "role": "system",
58 | "name": "system",
59 | "content": "You are a helpful agent to summarize the text.\\
60 | You need to keep all the key information of the text in the\\
61 | summary."
62 | },
63 | {
64 | "role": "user",
65 | "name": "user",
66 | "content": text
67 | },
68 | ]
69 |
70 | Messages will be processed by model.format() before feeding to models.
71 | """
72 | if max_return_token > 0:
73 | system_prompt += token_limit_prompt.format(max_return_token)
74 | try:
75 | msgs = [
76 | Msg(name="system", role="system", content=system_prompt),
77 | Msg(name="user", role="user", content=text),
78 | ]
79 | msgs = model.format(msgs)
80 | model_output = model(msgs)
81 | summary = model_output.text
82 | return ServiceResponse(
83 | ServiceExecStatus.SUCCESS,
84 | content=summary,
85 | )
86 | except ValueError as e:
87 | logger.exception(e)
88 | return ServiceResponse(
89 | ServiceExecStatus.ERROR,
90 | content=f"Summarization by model {model.model} fail",
91 | )
92 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/service/web/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/open-sciencelab/Virtual-Scientists/9a6d0f32f9adbccef68f70f1705fa12fc9d10e23/agentscope-main/src/agentscope/service/web/__init__.py
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/service/web/download.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """Download file from URL."""
3 | import os
4 |
5 | import requests
6 | from tqdm import tqdm
7 |
8 | from agentscope.service import ServiceResponse, ServiceExecStatus
9 |
10 |
11 | def download_from_url(
12 | url: str,
13 | filepath: str,
14 | timeout: int = 120,
15 | retries: int = 3,
16 | ) -> ServiceResponse:
17 | """Download file from the given url to the specified location.
18 |
19 | Args:
20 | url (`str`):
21 | The URL of the file to download.
22 | filepath (`str`):
23 | The path to save the downloaded file.
24 | timeout (`int`, defaults to `120`):
25 | The timeout for the download request.
26 | retries (`int`, defaults to `3`):
27 | The number of retries for the download request.
28 |
29 | Returns:
30 | `ServiceResponse`: A `ServiceResponse` object that contains execution
31 | results or error message.
32 | """
33 |
34 | # Check if the target file exists already
35 | if os.path.exists(filepath):
36 | return ServiceResponse(
37 | status=ServiceExecStatus.ERROR,
38 | content=f"The file {filepath} already exists.",
39 | )
40 |
41 | # Download the file
42 | try:
43 | session = requests.Session()
44 | response = session.get(url, stream=True, timeout=timeout)
45 | response.raise_for_status()
46 |
47 | file_size = int(response.headers.get("content-length", 0))
48 | chunk_size = 1024 * 32 # 32 KB
49 | progress_bar = tqdm(total=file_size, unit="iB", unit_scale=True)
50 |
51 | with open(filepath, "wb") as file:
52 | for chunk in response.iter_content(chunk_size=chunk_size):
53 | progress_bar.update(len(chunk))
54 | file.write(chunk)
55 | progress_bar.close()
56 |
57 | return ServiceResponse(
58 | status=ServiceExecStatus.SUCCESS,
59 | content={
60 | "url": url,
61 | "saved_file_path": filepath,
62 | },
63 | )
64 | except requests.exceptions.RequestException as e:
65 | if retries > 0:
66 | # remove the incomplete file
67 | if os.path.exists(filepath):
68 | os.remove(filepath)
69 | # retry the download
70 | return download_from_url(url, filepath, timeout, retries - 1)
71 | else:
72 | return ServiceResponse(
73 | status=ServiceExecStatus.ERROR,
74 | content=f"Failed to download file from {url}: {str(e)}",
75 | )
76 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/strategy/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """ Import modules in strategy package."""
3 | from .mixture_of_agent import MixtureOfAgents
4 |
5 | __all__ = [
6 | "MixtureOfAgents",
7 | ]
8 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """Import the entry point of AgentScope Studio."""
3 | from ._app import init
4 |
5 | __all__ = ["init"]
6 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/_studio_utils.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """The utility functions for AgentScope Studio."""
3 | import os.path
4 | import sqlite3
5 |
6 |
7 | def _check_and_convert_id_type(db_path: str, table_name: str) -> None:
8 | """Check and convert the type of the 'id' column in the specified table
9 | from INTEGER to VARCHAR.
10 |
11 | Args:
12 | db_path (str): The path of the SQLite database file.
13 | table_name (str): The name of the table to be checked and converted.
14 | """
15 |
16 | if not os.path.exists(db_path):
17 | return
18 |
19 | # Connect to the SQLite database
20 | conn = sqlite3.connect(db_path)
21 | cursor = conn.cursor()
22 |
23 | try:
24 | # Obtain the table structure information
25 | cursor.execute(f"PRAGMA table_info({table_name});")
26 | columns = cursor.fetchall()
27 |
28 | # Look for the type of the 'id' column
29 | id_column = [col for col in columns if col[1] == "id"]
30 | if not id_column:
31 | return
32 |
33 | id_type = id_column[0][2].upper()
34 | if id_type in ["VARCHAR", "TEXT"]:
35 | return
36 |
37 | if id_type == "INTEGER":
38 | # Temporary table name
39 | temp_table_name = table_name + "_temp"
40 |
41 | # Create a new table and change the type of the 'id' column to
42 | # VARCHAR
43 | create_table_sql = f"CREATE TABLE {temp_table_name} ("
44 | for col in columns:
45 | col_type = "VARCHAR" if col[1] == "id" else col[2]
46 | create_table_sql += f"{col[1]} {col_type}, "
47 | create_table_sql = create_table_sql.rstrip(", ") + ");"
48 |
49 | cursor.execute(create_table_sql)
50 |
51 | # Copy data and convert the value of the 'id' column to a string
52 | column_names = ", ".join([col[1] for col in columns])
53 | column_values = ", ".join(
54 | [
55 | f"CAST({col[1]} AS VARCHAR)" if col[1] == "id" else col[1]
56 | for col in columns
57 | ],
58 | )
59 | cursor.execute(
60 | f"INSERT INTO {temp_table_name} ({column_names}) "
61 | f"SELECT {column_values} FROM {table_name};",
62 | )
63 |
64 | # Delete the old table
65 | cursor.execute(f"DROP TABLE {table_name};")
66 |
67 | # Rename the new table
68 | cursor.execute(
69 | f"ALTER TABLE {temp_table_name} RENAME TO {table_name};",
70 | )
71 |
72 | conn.commit()
73 |
74 | except sqlite3.Error as e:
75 | print(f"SQLite error: {e}")
76 | finally:
77 | conn.close()
78 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/css/base.css:
--------------------------------------------------------------------------------
1 | :root {
2 | --tab-btn-icon-length: 20px;
3 |
4 | --body-bg: #ffffff;
5 |
6 | --main-color: #59AC80;
7 | --main-color-light: #A0D9C4;
8 | --main-color-light-light: #D1E9DC;
9 | --main-color-very-light: #F3F9F1;
10 | --main-color-dark: #3D7D5A;
11 | --base-color: #F3F9F1;
12 |
13 | --border-color: #EBEBF0;
14 |
15 | /*Titlebar for each page*/
16 | --page-titlebar-height: 60px;
17 | --page-content-height: calc(100% - var(--page-titlebar-height));
18 |
19 | /*Navigation bar*/
20 | --page-sidebar-width: 250px;
21 | }
22 |
23 | /*Text cannot be selected*/
24 | .unselectable-text {
25 | -webkit-user-select: none; /* Safari */
26 | -moz-user-select: none; /* Firefox */
27 | -ms-user-select: none; /* IE10+/Edge */
28 | user-select: none; /* Standard */
29 | }
30 |
31 | a {
32 | text-decoration: none;
33 | }
34 |
35 | .page-titlebar {
36 | display: flex;
37 | width: 100%;
38 | height: var(--page-titlebar-height);
39 | flex-direction: row;
40 | align-items: center;
41 | border-bottom: 1px solid var(--border-color);
42 | box-sizing: border-box;
43 | padding: 0 20px;
44 | }
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/css/dashboard-detail-code.css:
--------------------------------------------------------------------------------
1 | :root {
2 | --code-list-width: 350px;
3 | --code-content-width: calc(100% - var(--code-list-width));
4 | }
5 |
6 | #code-body {
7 | display: flex;
8 | flex-direction: row;
9 | height: 100%;
10 | width: 100%;
11 | }
12 |
13 | #code-list {
14 | display: flex;
15 | flex-direction: column;
16 | height: 100%;
17 | width: var(--code-list-width);
18 | box-sizing: border-box;
19 | border: 0;
20 | }
21 |
22 | #code-list ul {
23 | display: block;
24 | flex-direction: column;
25 | align-items: flex-start;
26 | justify-content: center;
27 | width: 100%;
28 | height: 35px;
29 | box-sizing: border-box;
30 | border-bottom: 1px solid var(--border-color);
31 | padding: 5px;
32 | margin: 0 0 3px 0;
33 | white-space: nowrap;
34 | overflow: hidden;
35 | text-overflow: ellipsis;
36 | }
37 |
38 | #code-filename {
39 | display: block;
40 | flex-direction: column;
41 | align-items: flex-start;
42 | justify-content: center;
43 | width: 100%;
44 | height: 35px;
45 | box-sizing: border-box;
46 | border-bottom: 1px solid var(--border-color);
47 | padding: 5px;
48 | margin: 0;
49 | white-space: nowrap;
50 | overflow: hidden;
51 | text-overflow: ellipsis;
52 | }
53 |
54 | #code-list li {
55 | display: flex;
56 | flex-direction: column;
57 | align-items: flex-start;
58 | justify-content: center;
59 | width: 100%;
60 | height: 35px;
61 | padding: 3px 15px;
62 | margin: 0;
63 | white-space: nowrap;
64 | overflow: hidden;
65 | text-overflow: ellipsis;
66 | box-sizing: border-box;
67 | }
68 |
69 | #code-list li:hover {
70 | background-color: var(--main-color-light-light);
71 | cursor: pointer;
72 | }
73 |
74 | #code-list li.selected {
75 | background-color: var(--main-color-light);
76 | }
77 |
78 | #code-list ul:hover {
79 | background-color: var(--main-color-light);
80 | overflow: visible;
81 | width: fit-content;
82 | border-radius: 5px;
83 | z-index: 10;
84 | }
85 |
86 | #code-content {
87 | display: flex;
88 | flex-direction: column;
89 | width: var(--code-content-width);
90 | height: 100%;
91 | box-sizing: border-box;
92 | border: 1px solid var(--border-color);
93 | }
94 |
95 | #code-editor {
96 | display: flex;
97 | width: 100%;
98 | height: 100%;
99 | overflow: auto;
100 | white-space: pre;
101 | }
102 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/css/dashboard-detail-invocation.css:
--------------------------------------------------------------------------------
1 | #invocation-body {
2 | display: flex;
3 | flex-direction: row;
4 | align-items: flex-end;
5 | height: 100%;
6 | width: 100%;
7 | }
8 |
9 | #invocation-list {
10 | display: flex;
11 | flex-direction: column;
12 | height: 100%;
13 | width: 350px;
14 | box-sizing: border-box;
15 | border: 0;
16 | background-color: #ffffff;
17 | }
18 |
19 | #invocation-content {
20 | display: flex;
21 | flex-direction: column;
22 | width: calc(100% - 350px);
23 | height: 100%;
24 | box-sizing: border-box;
25 | border-left: 1px solid var(--border-color);
26 | }
27 |
28 | #invocation-content .monaco-editor {
29 | display: flex;
30 | height: 100%;
31 | width: 100%;
32 | flex-grow: 1;
33 | min-width: 100%;
34 | }
35 |
36 | .content-placeholder {
37 | display: flex;
38 | color: var(--main-color-light-light);
39 | width: 100%;
40 | height: 100%;
41 | align-items: center;
42 | justify-content: center;
43 | font-size: 18px;
44 | }
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/css/dashboard-detail.css:
--------------------------------------------------------------------------------
1 | :root {
2 | --detail-sidebar-padding-vertical: 5px;
3 | --detail-content-width: calc(100% - var(--page-sidebar-width));
4 | }
5 |
6 | #detail-body {
7 | display: flex;
8 | flex-direction: row;
9 | height: 100%;
10 | width: 100%;
11 | }
12 |
13 | #detail-sidebar {
14 | display: flex;
15 | box-sizing: border-box;
16 | height: 100%;
17 | flex-direction: column;
18 | width: var(--page-sidebar-width);
19 | background-color: #ffffff;
20 |
21 | border-right-color: var(--border-color);
22 | border-right-width: 1px;
23 | border-right-style: solid;
24 | padding: var(--detail-sidebar-padding-vertical) 0;
25 | }
26 |
27 | .detail-sidebar-tabs {
28 | display: flex;
29 | flex-direction: column;
30 | width: 100%;
31 | height: 100%;
32 | padding: 45px 10px;
33 | box-sizing: border-box;
34 | }
35 |
36 | .detail-sidebar-tab {
37 | display: flex;
38 | flex-direction: row;
39 | height: var(--navigation-bar-item-height);
40 | width: 100%;
41 | box-sizing: border-box;
42 | align-items: center;
43 | border-radius: 10px;
44 | padding-left: 20px;
45 | margin: 5px 0;
46 | cursor: pointer;
47 | }
48 |
49 | .detail-sidebar-tab:hover {
50 | background-color: var(--main-color-light);
51 | fill: var(--base-color);
52 | color: var(--base-color);
53 | }
54 |
55 | .detail-sidebar-tab:active {
56 | background-color: var(--main-color-dark);
57 | fill: var(--base-color);
58 | color: var(--base-color);
59 | }
60 |
61 | .detail-sidebar-tab.selected {
62 | background-color: var(--main-color);
63 | fill: var(--base-color);
64 | color: var(--base-color);
65 | }
66 |
67 | .detail-sidebar-tab-svg {
68 | display: flex;
69 | width: var(--tab-btn-icon-length);
70 | height: var(--tab-btn-icon-length);
71 | margin-right: 10px;
72 | }
73 |
74 | #detail-content {
75 | display: flex;
76 | background-color: #ffffff;
77 | flex-direction: row;
78 | height: 100%;
79 | width: var(--detail-content-width);
80 | }
81 |
82 |
83 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/css/dashboard-runs.css:
--------------------------------------------------------------------------------
1 | :root {
2 | --runs-content-padding-vertical: 50px;
3 | --runs-content-padding-horizontal: 80px;
4 | --runs-content-control-panel-height: 55px;
5 | --runs-search-input-height: 35px;
6 | --runs-table-height: calc(100% - var(--runs-content-control-panel-height));
7 | }
8 |
9 | #runs-content {
10 | display: flex;
11 | flex-direction: column;
12 | height: 100%;
13 | width: 100%;
14 | padding: var(--runs-content-padding-vertical) var(--runs-content-padding-horizontal);
15 | box-sizing: border-box;
16 | }
17 |
18 | #runs-control-panel {
19 | display: flex;
20 | flex-direction: row;
21 | justify-content: space-between;
22 | align-items: center;
23 | height: var(--runs-content-control-panel-height);
24 | width: 100%;
25 | }
26 |
27 | #runs-table {
28 | flex-grow: 1;
29 | overflow-y: auto;
30 | width: 100%;
31 | height: var(--runs-table-height);
32 | max-height: var(--runs-table-height);
33 | background-color: #ffffff;
34 | border: 1px solid var(--border-color);
35 | }
36 |
37 | #runs-search-input {
38 | display: flex;
39 | height: var(--runs-search-input-height);
40 | flex-grow: 1;
41 | align-items: center;
42 | border: 1px solid var(--border-color);
43 | padding: 0 10px;
44 | }
45 |
46 | #runs-search-input:focus {
47 | border-color: var(--main-color);
48 | outline: none; /* 移除默认的焦点轮廓样式 */
49 | }
50 |
51 | /* Remove border from tabulator */
52 | .tabulator .tabulator-cell,
53 | .tabulator .tabulator-col,
54 | .tabulator .tabulator-header .tabulator-col {
55 | border: none !important;
56 | }
57 |
58 | .tabulator .tabulator-cell {
59 | height: 45px;
60 | }
61 |
62 | /* Remove the bottom border from table header */
63 | .tabulator .tabulator-header {
64 | border-bottom: none !important;
65 | }
66 |
67 | .tabulator-col-sorter-element.tabulator-sortable.tabulator-col {
68 | background-color: var(--main-color-light);
69 | color: var(--main-color-dark);
70 | }
71 |
72 | /* Set the same color for all rows */
73 | /*.tabulator .tabulator-row {*/
74 | /* background-color: #FFF !important; !* Replace by your color *!*/
75 | /*}*/
76 |
77 | /* or, you just want to remove the alternative background color and keep the basic background */
78 | /*.tabulator .tabulator-row:nth-child(even) {*/
79 | /* background-color: var(--main-color-light-light) !important; !* Causes even row background colors to inherit the default or specified row background colors *!*/
80 | /*}*/
81 |
82 | .runs-table-status-tag {
83 | display: flex;
84 | flex-direction: row;
85 | align-items: center;
86 | height: 26px;
87 | width: fit-content;
88 | border-radius: 13px;
89 | color: var(--base-color);
90 | box-sizing: border-box;
91 | margin: 0 5px;
92 | padding: 0 14px;
93 | }
94 |
95 | .running.runs-table-status-tag {
96 | background-color: #d1e7fa;
97 | color: #58c1ef;
98 | fill: #58c1ef;
99 | }
100 |
101 | .finished.runs-table-status-tag {
102 | background-color: var(--main-color-light);
103 | color: var(--main-color-dark);
104 | fill: var(--main-color-dark);
105 | }
106 |
107 | .waiting.runs-table-status-tag {
108 | background-color: #f8efba;
109 | color: #f6b93b;
110 | fill: #f6b93b;
111 | }
112 |
113 | .unknown.runs-table-status-tag {
114 | background-color: #e1e1e1;
115 | color: #3d4047;
116 | fill: #3d4047;
117 | }
118 |
119 | .runs-table-status-svg {
120 | display: flex;
121 | width: 15px;
122 | height: 15px;
123 | margin-right: 7px;
124 | }
125 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/css/dashboard.css:
--------------------------------------------------------------------------------
1 | #dashboard-panel {
2 | display: flex;
3 | height: 100%;
4 | width: 100%;
5 | flex-direction: column;
6 | }
7 |
8 | .dashboard-titlebar-span {
9 | display: flex;
10 | height: 50px;
11 | width: fit-content;
12 | align-items: center;
13 | cursor: pointer;
14 | }
15 |
16 | .dashboard-subtitlebar-span {
17 | display: flex;
18 | height: 50px;
19 | width: fit-content;
20 | align-items: center;
21 | }
22 |
23 | .dashboard-titlebar-svg {
24 | display: flex;
25 | width: 15px;
26 | height: 15px;
27 | align-items: center;
28 | justify-content: center;
29 | margin: 0 10px;
30 | }
31 |
32 | #dashboard-content {
33 | display: flex;
34 | height: var(--page-content-height);
35 | width: 100%;
36 | flex-direction: row;
37 | }
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/css/font.css:
--------------------------------------------------------------------------------
1 | @font-face {
2 | font-family: 'krypton';
3 | src: url('/static/fonts/KRYPTON.ttf') format('truetype');
4 | }
5 |
6 | @font-face {
7 | font-family: 'source-sans';
8 | src: url('/static/fonts/SourceSans3-Regular.ttf') format('truetype');
9 | }
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/css/login.css:
--------------------------------------------------------------------------------
1 | body {
2 | font-family: 'Arial', sans-serif;
3 | background-color: #f0f0f0;
4 | display: flex;
5 | flex-direction: column;
6 | justify-content: center;
7 | align-items: center;
8 | height: 100vh;
9 | margin: 0;
10 | }
11 |
12 | .login-container {
13 | padding: 2rem;
14 | background: #fff;
15 | box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
16 | border-radius: 8px;
17 | text-align: center;
18 | width: 100%;
19 | max-width: 80%;
20 | }
21 |
22 | #loginButton {
23 | background-color: #2ea44f;
24 | color: white;
25 | font-size: 18px;
26 | padding: 15px 24px;
27 | border: none;
28 | border-radius: 5px;
29 | cursor: pointer;
30 | box-shadow: 0px 4px 14px -3px rgba(0, 0, 0, 0.4);
31 | transition: background-color 0.3s, transform 0.2s;
32 | margin-top: 1rem;
33 | display: inline-block;
34 | width: 100%;
35 | }
36 |
37 | #loginButton:hover {
38 | background-color: #2c974b;
39 | transform: scale(1.05);
40 | }
41 |
42 | #loginButton:active {
43 | background-color: #258741;
44 | transform: scale(1);
45 | }
46 |
47 | #loginButton:disabled {
48 | background-color: #94d3a2;
49 | cursor: not-allowed;
50 | }
51 |
52 | .terms {
53 | background: #fff;
54 | padding: 20px;
55 | margin: 1rem auto;
56 | box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);
57 | border-radius: 8px;
58 | max-width: 600px;
59 | }
60 |
61 | .terms ul {
62 | margin-left: 20px;
63 | }
64 |
65 | .terms li {
66 | margin-bottom: 10px;
67 | }
68 |
69 | .checkbox {
70 | margin-bottom: 1rem;
71 | }
72 |
73 | .brand-gif {
74 | background: #fff;
75 | box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
76 | width: 50%;
77 | height: auto;
78 | border-radius: 8px;
79 | }
80 |
81 | .link-like {
82 | color: #707070;
83 | text-decoration: underline;
84 | cursor: pointer;
85 | opacity: 0.15;
86 | }
87 |
88 | .link-like:hover {
89 | opacity: 1.0;
90 | }
91 |
92 | .waiting {
93 | position: fixed;
94 | top: 50%;
95 | left: 50%;
96 | transform: translate(-50%, -50%);
97 | display: flex;
98 | align-items: center;
99 | justify-content: center;
100 | z-index: 1000;
101 | background-color: rgba(255, 255, 255, 0.8);
102 | border-radius: 10px;
103 | padding: 20px 40px;
104 | box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.25);
105 | flex-direction: column;
106 | }
107 |
108 | .css-spinner {
109 | border: 4px solid rgba(0, 0, 0, .1);
110 | border-radius: 50%;
111 | border-top: 4px solid #3498db;
112 | width: 40px;
113 | height: 40px;
114 | animation: spin 2s linear infinite;
115 | }
116 |
117 | @keyframes spin {
118 | 0% {
119 | transform: rotate(0deg);
120 | }
121 | 100% {
122 | transform: rotate(360deg);
123 | }
124 | }
125 |
126 | .waiting b {
127 | color: #555;
128 | font-weight: normal;
129 | font-size: 1.5em;
130 | }
131 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/css/server.css:
--------------------------------------------------------------------------------
1 | :root {
2 | --server-content-padding-vertical: 20px;
3 | --server-content-padding-horizontal: 30px;
4 | --server-table-height: calc(100% - var(--runs-content-control-panel-height));
5 | }
6 |
7 |
8 | #server-panel {
9 | display: flex;
10 | height: 100%;
11 | width: 100%;
12 | flex-direction: column;
13 | }
14 |
15 | #server-content {
16 | display: flex;
17 | flex-direction: column;
18 | width: 100%;
19 | padding: var(--server-content-padding-vertical) var(--server-content-padding-horizontal);
20 | box-sizing: border-box;
21 | }
22 |
23 | .collapsed {
24 | display: none;
25 | }
26 |
27 | #server-table {
28 | flex-grow: 1;
29 | overflow-y: auto;
30 | max-height: 30vh;
31 | width: 100%;
32 | background-color: #ffffff;
33 | border: 1px solid var(--border-color);
34 | }
35 |
36 | #agent-memory-content {
37 | display: flex;
38 | flex-direction: row;
39 | height: 200px;
40 | width: 100%;
41 | border: 1px solid var(--border-color);
42 | }
43 |
44 | #agent-memory-table {
45 | display: flex;
46 | flex-direction: column;
47 | width: 350px;
48 | box-sizing: border-box;
49 | border: 0;
50 | background-color: #ffffff;
51 | }
52 |
53 | #agent-memory-raw {
54 | display: flex;
55 | flex-direction: column;
56 | width: calc(100% - 350px);
57 | height: 100%;
58 | box-sizing: border-box;
59 | border-left: 1px solid var(--border-color);
60 | }
61 |
62 | #agent-memory-raw .monaco-editor {
63 | display: flex;
64 | height: 100%;
65 | width: 100%;
66 | min-width: 100%;
67 | }
68 |
69 | .server-section-title-bar {
70 | display: flex;
71 | justify-content: flex-start;
72 | font-size: 20px;
73 | padding: 6px 0px;
74 | }
75 |
76 |
77 | .align-right-btn {
78 | margin-left: auto;
79 | }
80 |
81 | #server-content .icon {
82 | display: flex;
83 | height: 20px;
84 | padding: 4px 15px;
85 | cursor: pointer;
86 | }
87 |
88 | #agent-table {
89 | flex-grow: 1;
90 | overflow-y: auto;
91 | max-height: 30vh;
92 | width: 100%;
93 | background-color: #ffffff;
94 | border: 1px solid var(--border-color);
95 | }
96 |
97 | .status-tag {
98 | display: flex;
99 | flex-direction: row;
100 | align-items: center;
101 | height: 26px;
102 | width: fit-content;
103 | border-radius: 13px;
104 | color: var(--base-color);
105 | box-sizing: border-box;
106 | margin: 0 5px;
107 | padding: 0 14px;
108 | }
109 |
110 | .running.status-tag {
111 | background-color: #ccf4dd;
112 | color: #27ae60;
113 | fill: #27ae60;
114 | }
115 |
116 | .dead.status-tag {
117 | background-color: #f5d5d1;
118 | color: #c0392b;
119 | fill: #c0392b;
120 | }
121 |
122 | .loading.status-tag {
123 | background-color: #e1e1e1;
124 | color: #3d4047;
125 | fill: #3d4047;
126 | }
127 |
128 | .unknown.status-tag {
129 | background-color: #e1e1e1;
130 | color: #3d4047;
131 | fill: #3d4047;
132 | }
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/css_third_party/clusterize.css:
--------------------------------------------------------------------------------
1 | /* max-height - the only parameter in this file that needs to be edited.
2 | * Change it to suit your needs. The rest is recommended to leave as is.
3 | */
4 | .clusterize-scroll{
5 | max-height: 200px;
6 | overflow: auto;
7 | }
8 |
9 | /**
10 | * Avoid vertical margins for extra tags
11 | * Necessary for correct calculations when rows have nonzero vertical margins
12 | */
13 | .clusterize-extra-row{
14 | margin-top: 0 !important;
15 | margin-bottom: 0 !important;
16 | }
17 |
18 | /* By default extra tag .clusterize-keep-parity added to keep parity of rows.
19 | * Useful when used :nth-child(even/odd)
20 | */
21 | .clusterize-extra-row.clusterize-keep-parity{
22 | display: none;
23 | }
24 |
25 | /* During initialization clusterize adds tabindex to force the browser to keep focus
26 | * on the scrolling list, see issue #11
27 | * Outline removes default browser's borders for focused elements.
28 | */
29 | .clusterize-content{
30 | outline: 0;
31 | counter-reset: clusterize-counter;
32 | }
33 |
34 | /* Centering message that appears when no data provided
35 | */
36 | .clusterize-no-data td{
37 | text-align: center;
38 | }
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/css_third_party/drawflow.min.css:
--------------------------------------------------------------------------------
1 | .drawflow, .drawflow .parent-node {
2 | position: relative;
3 | }
4 |
5 | .parent-drawflow {
6 | display: flex;
7 | overflow: hidden;
8 | touch-action: none;
9 | outline: 0;
10 | }
11 |
12 | .drawflow {
13 | width: 100%;
14 | height: 100%;
15 | user-select: none;
16 | }
17 |
18 | .drawflow .drawflow-node {
19 | display: flex;
20 | align-items: center;
21 | position: absolute;
22 | background: #fff;
23 | width: 280px;
24 | min-width: 150px;
25 | height: fit-content;
26 | border-radius: 4px;
27 | border: 1px solid var(--border-color);
28 | color: #000;
29 | z-index: 2;
30 | padding: 15px;
31 | box-shadow: 0 2px 10px 2px var(--border-color);
32 | }
33 |
34 | .drawflow .drawflow-node.selected {
35 | background: var(--main-color-very-light);
36 | border: 1px solid var(--main-color-light);
37 | box-shadow: 0 2px 10px 2px var(--main-color-light);
38 | }
39 |
40 | .drawflow .drawflow-node:hover {
41 | cursor: move;
42 | }
43 |
44 | .drawflow .drawflow-node .inputs, .drawflow .drawflow-node .outputs {
45 | width: 0;
46 | }
47 |
48 | .drawflow .drawflow-node .drawflow_content_node {
49 | width: 100%;
50 | display: block;
51 | }
52 |
53 | .drawflow .drawflow-node .input, .drawflow .drawflow-node .output {
54 | position: relative;
55 | width: 15px;
56 | height: 15px;
57 | background: #fff;
58 | border-radius: 50%;
59 | border: 2px solid var(--border-color);
60 | cursor: crosshair;
61 | z-index: 1;
62 | margin-bottom: 5px;
63 | }
64 |
65 | .drawflow .drawflow-node .input {
66 | left: -27px;
67 | top: 2px;
68 | background: #ff0;
69 | }
70 |
71 | .drawflow .drawflow-node .output {
72 | right: -3px;
73 | top: 2px;
74 | }
75 |
76 | .drawflow svg {
77 | z-index: 0;
78 | }
79 |
80 | .drawflow .connection {
81 | position: absolute;
82 | pointer-events: none;
83 | overflow-x: visible;
84 | overflow-y: visible;
85 | }
86 |
87 | .drawflow .connection .main-path {
88 | fill: none;
89 | stroke-width: 3px;
90 | stroke: var(--main-color);
91 | pointer-events: all;
92 | }
93 |
94 | .drawflow .connection .main-path:hover {
95 | stroke: #1266ab;
96 | cursor: pointer;
97 | }
98 |
99 | .drawflow .connection .main-path.selected {
100 | stroke: #43b993;
101 | }
102 |
103 | .drawflow .connection .point {
104 | cursor: move;
105 | stroke: #000;
106 | stroke-width: 2;
107 | fill: #fff;
108 | pointer-events: all;
109 | }
110 |
111 | .drawflow .connection .point.selected, .drawflow .connection .point:hover {
112 | fill: #1266ab;
113 | }
114 |
115 | .drawflow .main-path {
116 | fill: none;
117 | stroke-width: 5px;
118 | stroke: #4682b4;
119 | }
120 |
121 | .drawflow-delete {
122 | position: absolute;
123 | display: block;
124 | width: 30px;
125 | height: 30px;
126 | background: #ffffff;
127 | color: var(--main-color-light);
128 | z-index: 4;
129 | border: 2px solid var(--main-color-light);
130 | box-shadow: 0 2px 20px 2px var(--main-color-light);
131 | line-height: 30px;
132 | font-weight: 700;
133 | text-align: center;
134 | border-radius: 50%;
135 | font-family: monospace;
136 | cursor: pointer;
137 | }
138 |
139 | .drawflow > .drawflow-delete {
140 | margin-left: -15px;
141 | margin-top: 15px;
142 | }
143 |
144 | .parent-node .drawflow-delete {
145 | right: -15px;
146 | top: -15px;
147 | }
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/css_third_party/highlight.min.css:
--------------------------------------------------------------------------------
1 | pre code.hljs{display:block;overflow-x:auto;padding:1em}code.hljs{padding:3px 5px}.hljs{color:#383a42;background:#fafafa}.hljs-comment,.hljs-quote{color:#a0a1a7;font-style:italic}.hljs-doctag,.hljs-formula,.hljs-keyword{color:#a626a4}.hljs-deletion,.hljs-name,.hljs-section,.hljs-selector-tag,.hljs-subst{color:#e45649}.hljs-literal{color:#0184bb}.hljs-addition,.hljs-attribute,.hljs-meta .hljs-string,.hljs-regexp,.hljs-string{color:#50a14f}.hljs-attr,.hljs-number,.hljs-selector-attr,.hljs-selector-class,.hljs-selector-pseudo,.hljs-template-variable,.hljs-type,.hljs-variable{color:#986801}.hljs-bullet,.hljs-link,.hljs-meta,.hljs-selector-id,.hljs-symbol,.hljs-title{color:#4078f2}.hljs-built_in,.hljs-class .hljs-title,.hljs-title.class_{color:#c18401}.hljs-emphasis{font-style:italic}.hljs-strong{font-weight:700}.hljs-link{text-decoration:underline}
2 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/css_third_party/prism-line-numbers.min.css:
--------------------------------------------------------------------------------
1 | pre[class*=language-].line-numbers{position:relative;padding-left:3.8em;counter-reset:linenumber}pre[class*=language-].line-numbers>code{position:relative;white-space:inherit}.line-numbers .line-numbers-rows{position:absolute;pointer-events:none;top:0;font-size:100%;left:-3.8em;width:3em;letter-spacing:-1px;border-right:1px solid #999;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.line-numbers-rows>span{display:block;counter-increment:linenumber}.line-numbers-rows>span:before{content:counter(linenumber);color:#999;display:block;padding-right:.8em;text-align:right}
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/css_third_party/prism.min.css:
--------------------------------------------------------------------------------
1 | code[class*=language-],pre[class*=language-]{color:#000;background:0 0;text-shadow:0 1px #fff;font-family:Consolas,Monaco,'Andale Mono','Ubuntu Mono',monospace;font-size:1em;text-align:left;white-space:pre;word-spacing:normal;word-break:normal;word-wrap:normal;line-height:1.5;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-hyphens:none;-moz-hyphens:none;-ms-hyphens:none;hyphens:none}code[class*=language-] ::-moz-selection,code[class*=language-]::-moz-selection,pre[class*=language-] ::-moz-selection,pre[class*=language-]::-moz-selection{text-shadow:none;background:#b3d4fc}code[class*=language-] ::selection,code[class*=language-]::selection,pre[class*=language-] ::selection,pre[class*=language-]::selection{text-shadow:none;background:#b3d4fc}@media print{code[class*=language-],pre[class*=language-]{text-shadow:none}}pre[class*=language-]{padding:1em;margin:.5em 0;overflow:auto}:not(pre)>code[class*=language-],pre[class*=language-]{background:#f5f2f0}:not(pre)>code[class*=language-]{padding:.1em;border-radius:.3em;white-space:normal}.token.cdata,.token.comment,.token.doctype,.token.prolog{color:#708090}.token.punctuation{color:#999}.token.namespace{opacity:.7}.token.boolean,.token.constant,.token.deleted,.token.number,.token.property,.token.symbol,.token.tag{color:#905}.token.attr-name,.token.builtin,.token.char,.token.inserted,.token.selector,.token.string{color:#690}.language-css .token.string,.style .token.string,.token.entity,.token.operator,.token.url{color:#9a6e3a;background:hsla(0,0%,100%,.5)}.token.atrule,.token.attr-value,.token.keyword{color:#07a}.token.class-name,.token.function{color:#dd4a68}.token.important,.token.regex,.token.variable{color:#e90}.token.bold,.token.important{font-weight:700}.token.italic{font-style:italic}.token.entity{cursor:help}
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/fonts/KRYPTON.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/open-sciencelab/Virtual-Scientists/9a6d0f32f9adbccef68f70f1705fa12fc9d10e23/agentscope-main/src/agentscope/studio/static/fonts/KRYPTON.ttf
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/fonts/SourceSans3-Regular.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/open-sciencelab/Virtual-Scientists/9a6d0f32f9adbccef68f70f1705fa12fc9d10e23/agentscope-main/src/agentscope/studio/static/fonts/SourceSans3-Regular.ttf
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/html-drag-components/agent-dialogagent.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
6 |
7 |
8 |
9 |
DialogAgent
10 |
11 |
Copy
12 |
▲
13 |
14 |
15 | An dialog agent that can interact with users or other agents.
16 |
Node ID: ID_PLACEHOLDER
17 |
18 |
19 |
Name
20 |
22 |
23 |
24 |
System prompt
25 |
27 |
28 |
29 |
Model config name
30 |
32 |
33 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/html-drag-components/agent-dictdialogagent.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
6 |
7 |
8 |
9 |
DictDialogAgent
10 |
11 |
Copy
12 |
▲
13 |
14 |
15 |
16 | Agent that generates response in a dict format
17 |
Node ID: ID_PLACEHOLDER
18 |
19 |
20 |
Name
21 |
23 |
24 |
25 |
System prompt
26 |
28 |
29 |
30 |
Model config name
31 |
33 |
34 |
35 |
Max retries
36 |
37 |
38 |
39 |
Parse function (Optional)
40 |
41 |
42 |
43 |
Fault handler (Optional)
44 |
45 |
46 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/html-drag-components/agent-reactagent.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
6 |
7 |
8 |
9 |
ReActAgent
10 |
11 |
Copy
12 |
▲
13 |
14 |
15 |
16 |
17 |
18 | Agent for ReAct (reasoning and acting) with tools
19 |
Node ID: ID_PLACEHOLDER
20 |
21 |
22 |
Name
23 |
25 |
26 |
27 |
System prompt
28 |
31 |
32 |
33 |
Model config name
34 |
36 |
37 |
38 |
Tools
39 |
Please drag and
40 | drop a Tool module into this area. Inserting other types of modules
41 | may result in errors.
42 |
43 |
44 |
Max reasoning-acting iterations
45 |
46 |
47 |
48 |
Verbose
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/html-drag-components/agent-texttoimageagent.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
6 |
7 |
8 |
9 |
TextToImageAgent
10 |
11 |
Copy
12 |
▲
13 |
14 |
15 |
16 | Agent for text to image generation
17 |
Node ID: ID_PLACEHOLDER
18 |
19 |
20 |
Name
21 |
23 |
24 |
25 |
Model config name
26 |
27 |
28 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/html-drag-components/agent-useragent.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
6 |
7 |
8 |
9 |
UserAgent
10 |
11 |
Copy
12 |
▲
13 |
14 |
15 |
16 | A proxy agent for user
17 |
Node ID: ID_PLACEHOLDER
18 |
19 |
20 |
Name
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/html-drag-components/message-msg.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 |
6 |
7 |
8 |
Msg
9 |
10 |
▲
11 |
12 |
13 |
14 | Name
15 |
17 |
18 |
19 | Content
20 |
22 |
23 |
24 | URL (Optional)
25 |
26 |
27 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/html-drag-components/model-dashscope-chat.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 |
6 |
7 |
DashScope Chat
8 |
9 |
▲
10 |
11 |
12 |
DashScope Chat Configurations (Your API key will
13 | NOT be stored and exposed to the website
14 | maintainer)
15 |
16 |
17 |
18 |
Config Name
19 |
21 |
22 |
23 |
Model Name
24 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
API key
34 |
35 |
36 |
37 |
Temperature
38 |
40 |
41 |
42 |
Seed
43 |
44 |
45 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/html-drag-components/model-post-api-chat.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 |
6 |
7 |
Post API Chat
8 |
9 |
▲
10 |
11 |
12 |
Post API Chat Configuration
13 |
14 |
15 |
Config Name
16 |
18 |
19 |
20 |
Model Name
21 |
23 |
24 |
25 |
Temperature
26 |
28 |
29 |
30 |
Seed
31 |
32 |
33 |
34 |
API url
35 |
36 |
37 |
38 |
Content-Type
39 |
41 |
42 |
43 |
Authorization
44 |
45 |
46 |
47 |
Messages Key
48 |
49 |
50 |
51 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/html-drag-components/pipeline-forlooppipeline.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 |
6 |
7 |
ForLoopPipeline
8 |
9 |
▲
10 |
11 |
12 |
A template pipeline for implementing control flow
13 | like for-loop
14 |
15 |
16 |
Max Loop
17 |
18 |
19 |
20 |
Break Function
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/html-drag-components/pipeline-ifelsepipeline.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 |
6 |
7 |
IfElsePipeline
8 |
9 |
▲
10 |
11 |
12 |
A template pipeline for implementing control flow
13 | with if-else logic
14 |
15 |
16 |
Condition Function
17 |
18 |
19 |
20 |
If condition
21 |
22 |
Else condition
23 |
24 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/html-drag-components/pipeline-msghub.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 |
6 |
7 |
MsgHub
8 |
9 |
▲
10 |
11 |
12 |
MsgHub is used to share messages among a group of
13 | agents
14 |
15 |
16 |
Announcement Name
17 |
18 |
19 |
20 |
Announcement Content
21 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/html-drag-components/pipeline-placeholder.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 |
6 |
7 |
Placeholder
8 |
9 |
▲
10 |
11 |
12 |
A placeholder that do nothing
13 |
14 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/html-drag-components/pipeline-sequentialpipeline.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 |
6 |
7 |
SequentialPipeline
8 |
9 |
▲
10 |
11 |
12 |
A template pipeline for implementing sequential
13 | logic (from top to bottom )
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/html-drag-components/pipeline-switchpipeline.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 |
6 |
7 |
SwitchPipeline
8 |
9 |
▲
10 |
11 |
12 |
A template pipeline for implementing control flow
13 | with switch-case logic
14 |
15 |
16 |
Condition Function
17 |
18 |
19 |
20 |
Add Case
21 |
22 |
Remove Case
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/html-drag-components/pipeline-whilelooppipeline.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 |
6 |
7 |
WhileLoopPipeline
8 |
9 |
▲
10 |
11 |
12 |
A template pipeline for implementing control flow
13 | like while-loop
14 |
15 |
16 |
Condition Function
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/html-drag-components/service-bing-search.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 |
6 |
7 |
8 |
BingSearchService
9 |
10 |
▲
11 |
12 |
13 |
Integrate the Bing Search service within ReActAgent
14 | to enhance agent capabilities
15 |
16 |
17 |
API key
18 |
19 |
20 |
21 |
Results Number
22 |
23 |
24 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/html-drag-components/service-execute-python.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 |
6 |
7 |
8 |
PythonService
9 |
10 |
▲
11 |
12 |
13 |
Integrate the Python Interpreter within ReActAgent
14 | to enhance agent capabilities
15 |
16 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/html-drag-components/service-google-search.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 |
6 |
7 |
8 |
GoogleSearchService
9 |
10 |
▲
11 |
12 |
13 |
Integrate the Google Search service within
14 | ReActAgent to enhance agent capabilities
15 |
16 |
17 |
API key
18 |
19 |
20 |
21 |
CSE ID
22 |
23 |
24 |
25 |
Results Number
26 |
27 |
28 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/html-drag-components/service-read-text.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 |
6 |
7 |
8 |
ReadTextService
9 |
10 |
▲
11 |
12 |
13 |
Integrate the Read Text service within ReActAgent
14 | to enhance agent capabilities
15 |
16 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/html-drag-components/service-write-text.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 |
6 |
7 |
8 |
WriteTextService
9 |
10 |
▲
11 |
12 |
13 |
Integrate the Write Text Service within ReActAgent
14 | to enhance agent capabilities
15 |
16 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/html-drag-components/welcome.html:
--------------------------------------------------------------------------------
1 |
2 | 👏 Welcome!
3 | ▲
4 |
5 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/html/dashboard-detail-code.html:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/html/dashboard-detail-invocation.html:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/html/dashboard-runs.html:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/html/dashboard.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | Dashboard
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/html/index-guide.html:
--------------------------------------------------------------------------------
1 |
2 |
Welcome to AgentScope Studio
3 |
4 | AgentScope Studio is a web-based platform for monitoring, managing and
5 | developing multi-agent applications in AgentScope! Feel free to explore
6 | the platform and its features.
7 |
8 |
9 |
Start to explore AgentScope Studio with
10 |
11 |
15 |
Dashboard
16 |
17 | Monitor and manage your AgentScope running instances.
18 |
19 |
20 |
24 |
Workstation
25 |
26 | Develop your multi-agent applications by dragging.
27 |
28 |
29 |
30 |
31 |
32 |
Gallery
33 |
Coming soon ...
34 |
35 |
39 |
Server Manager
40 |
41 | Manage your agent servers (In development).
42 |
43 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/html/market.html:
--------------------------------------------------------------------------------
1 | Coming soon ...
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/html/server.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | Server Manager
8 |
9 |
10 |
11 |
12 |
Servers
13 |
18 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
34 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
50 |
51 |
55 |
56 |
57 |
58 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/html/workstation_iframe.html:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/js/dashboard-detail-code.js:
--------------------------------------------------------------------------------
1 | let currentCode = null;
2 | let editorInstance = null;
3 |
4 | function initializeDashboardDetailCodePage(codeUrl) {
5 | initializeMonacoEditor();
6 |
7 | fetch("/api/code?run_dir=" + codeUrl)
8 | .then((response) => {
9 | if (!response.ok) {
10 | throw new Error("Connection error, cannot load the web page.");
11 | }
12 | return response.json();
13 | })
14 | .then((data) => {
15 | console.log("Get ", data);
16 | currentCode = data;
17 | constructCodeFileList(codeUrl, data);
18 | })
19 | .catch((error) => {
20 | console.error("Error encountered while loading page: ", error);
21 | });
22 | }
23 |
24 | function constructCodeFileList(codeUrl, code) {
25 | let codeFileRows = [``];
26 |
27 | if (code !== null && code !== undefined) {
28 | if (Object.keys(code).length === 0) {
29 | codeFileRows = [
30 | 'No code available
',
31 | ];
32 | } else {
33 | Object.keys(code).forEach((key) =>
34 | codeFileRows.push(
35 | `${key} `
36 | )
37 | );
38 | }
39 | }
40 |
41 | document.getElementById("code-list").innerHTML = codeFileRows.join("\n");
42 | }
43 |
44 | function initializeMonacoEditor() {
45 | require.config({
46 | paths: {
47 | vs: "https://cdn.jsdelivr.net/npm/monaco-editor@latest/min/vs",
48 | },
49 | });
50 | require(["vs/editor/editor.main"], function () {
51 | editorInstance = monaco.editor.create(
52 | document.getElementById("code-editor"),
53 | {
54 | language: "python",
55 | theme: "vs-light",
56 | scrollBeyondLastLine: false,
57 | readOnly: true,
58 | }
59 | );
60 | }, function (error) {
61 | console.error("Error encountered while loading monaco editor: ", error);
62 | });
63 | }
64 |
65 | function displayCode(codeFileName) {
66 | document.getElementById("code-filename").innerHTML = codeFileName;
67 |
68 | if (editorInstance) {
69 | editorInstance.setValue(currentCode[codeFileName]);
70 | } else {
71 | console.log(
72 | "Monaco editor instance is not available, set text content"
73 | );
74 | document.getElementById("code-editor").textContent =
75 | currentCode[codeFileName];
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/js/dashboard-detail-invocation.js:
--------------------------------------------------------------------------------
1 | let invocationEditor = null;
2 |
3 | function initializeDashboardDetailInvocationPage(runDir) {
4 | // load monaco editor
5 | require.config({
6 | paths: {
7 | vs: "https://cdn.jsdelivr.net/npm/monaco-editor@latest/min/vs",
8 | },
9 | });
10 | require(["vs/editor/editor.main"], function () {
11 | invocationEditor = monaco.editor.create(
12 | document.getElementById("invocation-content"),
13 | {
14 | language: "json",
15 | theme: "vs-light",
16 | minimap: {
17 | enabled: false,
18 | },
19 | scrollBeyondLastLine: false,
20 | readOnly: true,
21 | }
22 | );
23 | });
24 |
25 | // fetch data from server
26 | fetch("/api/invocation?run_dir=" + runDir)
27 | .then((response) => {
28 | if (response.ok) {
29 | return response.json();
30 | } else {
31 | throw new Error("Failed to fetch invocation detail");
32 | }
33 | })
34 | .then((data) => {
35 | console.log(data);
36 | var invocationTable = new Tabulator("#invocation-list", {
37 | data: data,
38 | columns: [
39 | {
40 | title: "Model Wrapper",
41 | field: "model_class",
42 | editor: false,
43 | vertAlign: "middle",
44 | },
45 | {
46 | title: "Timestamp",
47 | field: "timestamp",
48 | editor: false,
49 | vertAlign: "middle",
50 | },
51 | ],
52 | layout: "fitColumns",
53 | placeholder:
54 | "No invocation records available.
",
55 | initialSort: [
56 | {
57 | column: "timestamp",
58 | dir: "asc",
59 | },
60 | ],
61 | });
62 |
63 | // Set up row click event
64 | invocationTable.on("rowClick", function (e, row) {
65 | // Jump to the run detail page
66 | console.log(row.getData());
67 | invocationEditor.setValue(
68 | JSON.stringify(row.getData(), null, 2)
69 | );
70 | });
71 | })
72 | .catch((error) => {
73 | console.error(error);
74 | });
75 | }
76 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/js/workstation_iframe.js:
--------------------------------------------------------------------------------
1 | var iframe = document.getElementById('workstation-iframe');
2 | var currentUrl = window.location.protocol + '//' + window.location.host + '/workstation';
3 | iframe.src = currentUrl;
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/js_third_party/marked-katex-extension.umd.js:
--------------------------------------------------------------------------------
1 | (function (global, factory) {
2 | typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('katex')) :
3 | typeof define === 'function' && define.amd ? define(['katex'], factory) :
4 | (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.markedKatex = factory(global.katex));
5 | })(this, (function (katex) { 'use strict';
6 |
7 | const inlineRule = /^(\${1,2})(?!\$)((?:\\.|[^\\\n])*?(?:\\.|[^\\\n\$]))\1(?=[\s?!\.,:?!。,:]|$)/;
8 | const blockRule = /^(\${1,2})\n((?:\\[^]|[^\\])+?)\n\1(?:\n|$)/;
9 |
10 | function index(options = {}) {
11 | return {
12 | extensions: [
13 | inlineKatex(options, createRenderer(options, false)),
14 | blockKatex(options, createRenderer(options, true))
15 | ]
16 | };
17 | }
18 |
19 | function createRenderer(options, newlineAfter) {
20 | return (token) => katex.renderToString(token.text, { ...options, displayMode: token.displayMode }) + (newlineAfter ? '\n' : '');
21 | }
22 |
23 | function inlineKatex(options, renderer) {
24 | return {
25 | name: 'inlineKatex',
26 | level: 'inline',
27 | start(src) {
28 | let index;
29 | let indexSrc = src;
30 |
31 | while (indexSrc) {
32 | index = indexSrc.indexOf('$');
33 | if (index === -1) {
34 | return;
35 | }
36 |
37 | if (index === 0 || indexSrc.charAt(index - 1) === ' ') {
38 | const possibleKatex = indexSrc.substring(index);
39 |
40 | if (possibleKatex.match(inlineRule)) {
41 | return index;
42 | }
43 | }
44 |
45 | indexSrc = indexSrc.substring(index + 1).replace(/^\$+/, '');
46 | }
47 | },
48 | tokenizer(src, tokens) {
49 | const match = src.match(inlineRule);
50 | if (match) {
51 | return {
52 | type: 'inlineKatex',
53 | raw: match[0],
54 | text: match[2].trim(),
55 | displayMode: match[1].length === 2
56 | };
57 | }
58 | },
59 | renderer
60 | };
61 | }
62 |
63 | function blockKatex(options, renderer) {
64 | return {
65 | name: 'blockKatex',
66 | level: 'block',
67 | tokenizer(src, tokens) {
68 | const match = src.match(blockRule);
69 | if (match) {
70 | return {
71 | type: 'blockKatex',
72 | raw: match[0],
73 | text: match[2].trim(),
74 | displayMode: match[1].length === 2
75 | };
76 | }
77 | },
78 | renderer
79 | };
80 | }
81 |
82 | return index;
83 |
84 | }));
85 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/js_third_party/prism-line-numbers.min.js:
--------------------------------------------------------------------------------
1 | !function(){if("undefined"!=typeof Prism&&"undefined"!=typeof document){var e="line-numbers",n=/\n(?!$)/g,t=Prism.plugins.lineNumbers={getLine:function(n,t){if("PRE"===n.tagName&&n.classList.contains(e)){var i=n.querySelector(".line-numbers-rows");if(i){var r=parseInt(n.getAttribute("data-start"),10)||1,s=r+(i.children.length-1);ts&&(t=s);var l=t-r;return i.children[l]}}},resize:function(e){r([e])},assumeViewportIndependence:!0},i=void 0;window.addEventListener("resize",(function(){t.assumeViewportIndependence&&i===window.innerWidth||(i=window.innerWidth,r(Array.prototype.slice.call(document.querySelectorAll("pre.line-numbers"))))})),Prism.hooks.add("complete",(function(t){if(t.code){var i=t.element,s=i.parentNode;if(s&&/pre/i.test(s.nodeName)&&!i.querySelector(".line-numbers-rows")&&Prism.util.isActive(i,e)){i.classList.remove(e),s.classList.add(e);var l,o=t.code.match(n),a=o?o.length+1:1,u=new Array(a+1).join(" ");(l=document.createElement("span")).setAttribute("aria-hidden","true"),l.className="line-numbers-rows",l.innerHTML=u,s.hasAttribute("data-start")&&(s.style.counterReset="linenumber "+(parseInt(s.getAttribute("data-start"),10)-1)),t.element.appendChild(l),r([s]),Prism.hooks.run("line-numbers",t)}}})),Prism.hooks.add("line-numbers",(function(e){e.plugins=e.plugins||{},e.plugins.lineNumbers=!0}))}function r(e){if(0!=(e=e.filter((function(e){var n,t=(n=e,n?window.getComputedStyle?getComputedStyle(n):n.currentStyle||null:null)["white-space"];return"pre-wrap"===t||"pre-line"===t}))).length){var t=e.map((function(e){var t=e.querySelector("code"),i=e.querySelector(".line-numbers-rows");if(t&&i){var r=e.querySelector(".line-numbers-sizer"),s=t.textContent.split(n);r||((r=document.createElement("span")).className="line-numbers-sizer",t.appendChild(r)),r.innerHTML="0",r.style.display="block";var l=r.getBoundingClientRect().height;return r.innerHTML="",{element:e,lines:s,lineHeights:[],oneLinerHeight:l,sizer:r}}})).filter(Boolean);t.forEach((function(e){var n=e.sizer,t=e.lines,i=e.lineHeights,r=e.oneLinerHeight;i[t.length-1]=void 0,t.forEach((function(e,t){if(e&&e.length>1){var s=n.appendChild(document.createElement("span"));s.style.display="block",s.textContent=e}else i[t]=r}))})),t.forEach((function(e){for(var n=e.sizer,t=e.lineHeights,i=0,r=0;r]?|>[=>]?|[&|^~]/,punctuation:/[{}[\];(),.:]/},Prism.languages.python["string-interpolation"].inside.interpolation.inside.rest=Prism.languages.python,Prism.languages.py=Prism.languages.python;
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/svg/circle-add.svg:
--------------------------------------------------------------------------------
1 |
8 |
12 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/svg/circle-delete.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/svg/flush.svg:
--------------------------------------------------------------------------------
1 |
9 |
13 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/svg/trash-bin.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/studio/static/workstation_templates/en1.json:
--------------------------------------------------------------------------------
1 | {
2 | "drawflow": {
3 | "Home": {
4 | "data": {
5 | "2": {
6 | "id": 2,
7 | "name": "dashscope_chat",
8 | "data": {
9 | "args": {
10 | "config_name": "qwen",
11 | "model_name": "qwen-max",
12 | "api_key": "",
13 | "temperature": 0,
14 | "seed": 0,
15 | "model_type": "dashscope_chat",
16 | "messages_key": "input"
17 | }
18 | },
19 | "class": "dashscope_chat",
20 | "typenode": false,
21 | "inputs": {},
22 | "outputs": {},
23 | "pos_x": 399,
24 | "pos_y": 127
25 | },
26 | "3": {
27 | "id": 3,
28 | "name": "UserAgent",
29 | "data": {
30 | "args": {
31 | "name": "User"
32 | }
33 | },
34 | "class": "UserAgent",
35 | "typenode": false,
36 | "inputs": {
37 | "input_1": {
38 | "connections": []
39 | }
40 | },
41 | "outputs": {
42 | "output_1": {
43 | "connections": [
44 | {
45 | "node": "4",
46 | "output": "input_1"
47 | }
48 | ]
49 | }
50 | },
51 | "pos_x": 716,
52 | "pos_y": 245
53 | },
54 | "4": {
55 | "id": 4,
56 | "name": "DialogAgent",
57 | "data": {
58 | "args": {
59 | "name": "Assistant",
60 | "sys_prompt": "You are an assistant",
61 | "model_config_name": "qwen"
62 | }
63 | },
64 | "class": "DialogAgent",
65 | "typenode": false,
66 | "inputs": {
67 | "input_1": {
68 | "connections": [
69 | {
70 | "node": "3",
71 | "input": "output_1"
72 | }
73 | ]
74 | }
75 | },
76 | "outputs": {
77 | "output_1": {
78 | "connections": []
79 | }
80 | },
81 | "pos_x": 1080,
82 | "pos_y": 173
83 | },
84 | "1": {
85 | "id": 1,
86 | "name": "readme",
87 | "data": {},
88 | "class": "welcome",
89 | "html": " README ▲
\n \n 📖 This is an example of how to program a one-round conversation in AgentScope.
Modules Used: DashScope Chat: - Each application must contain a model configured.UserAgent: - Represents a user in a application.DialogAgent: - Agent for dialog in an application.\n ",
90 | "typenode": false,
91 | "inputs": {},
92 | "outputs": {},
93 | "pos_x": 68,
94 | "pos_y": 67
95 | }
96 | }
97 | }
98 | }
99 | }
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/utils/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/open-sciencelab/Virtual-Scientists/9a6d0f32f9adbccef68f70f1705fa12fc9d10e23/agentscope-main/src/agentscope/utils/__init__.py
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/web/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/open-sciencelab/Virtual-Scientists/9a6d0f32f9adbccef68f70f1705fa12fc9d10e23/agentscope-main/src/agentscope/web/__init__.py
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/web/gradio/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/open-sciencelab/Virtual-Scientists/9a6d0f32f9adbccef68f70f1705fa12fc9d10e23/agentscope-main/src/agentscope/web/gradio/__init__.py
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/web/gradio/constants.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """ Some constants used in the AS studio"""
3 |
4 | _SPEAK = "**speak**"
5 |
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/web/workstation/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/open-sciencelab/Virtual-Scientists/9a6d0f32f9adbccef68f70f1705fa12fc9d10e23/agentscope-main/src/agentscope/web/workstation/__init__.py
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/web/workstation/examples/0_two_agent.json:
--------------------------------------------------------------------------------
1 | {
2 | "4": {
3 | "name": "dashscope_chat",
4 | "data": {
5 | "args": {
6 | "config_name": "qwen",
7 | "model_name": "qwen-max",
8 | "api_key": "************",
9 | "temperature": 0.1,
10 | "seed": 1,
11 | "model_type": "dashscope_chat",
12 | "messages_key": "input"
13 | }
14 | },
15 | "inputs": {},
16 | "outputs": {}
17 | },
18 | "5": {
19 | "name": "Message",
20 | "data": {
21 | "args": {
22 | "name": "Host",
23 | "content": "Hello",
24 | "url": ""
25 | }
26 | },
27 | "inputs": {
28 | "input_1": {
29 | "connections": []
30 | }
31 | },
32 | "outputs": {
33 | "output_1": {
34 | "connections": [
35 | {
36 | "node": "7",
37 | "output": "input_1"
38 | }
39 | ]
40 | }
41 | }
42 | },
43 | "6": {
44 | "name": "UserAgent",
45 | "data": {
46 | "args": {
47 | "name": "User"
48 | }
49 | },
50 | "inputs": {
51 | "input_1": {
52 | "connections": [
53 | {
54 | "node": "7",
55 | "input": "output_1"
56 | }
57 | ]
58 | }
59 | },
60 | "outputs": {
61 | "output_1": {
62 | "connections": []
63 | }
64 | }
65 | },
66 | "7": {
67 | "name": "DialogAgent",
68 | "data": {
69 | "args": {
70 | "name": "Alice",
71 | "sys_prompt": "You are Alice.",
72 | "model_config_name": "qwen"
73 | }
74 | },
75 | "inputs": {
76 | "input_1": {
77 | "connections": [
78 | {
79 | "node": "5",
80 | "input": "output_1"
81 | }
82 | ]
83 | }
84 | },
85 | "outputs": {
86 | "output_1": {
87 | "connections": [
88 | {
89 | "node": "6",
90 | "output": "input_1"
91 | }
92 | ]
93 | }
94 | }
95 | }
96 | }
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/web/workstation/examples/1_conversation.json:
--------------------------------------------------------------------------------
1 | {
2 | "2": {
3 | "name": "dashscope_chat",
4 | "data": {
5 | "args": {
6 | "config_name": "qwen",
7 | "model_name": "qwen-max",
8 | "api_key": "************",
9 | "temperature": 0.1,
10 | "seed": 1,
11 | "model_type": "dashscope_chat",
12 | "messages_key": "input"
13 | }
14 | },
15 | "inputs": {},
16 | "outputs": {}
17 | },
18 | "3": {
19 | "name": "ForLoopPipeline",
20 | "data": {
21 | "elements": [
22 | "4"
23 | ],
24 | "args": {
25 | "max_loop": 3,
26 | "break_func": ""
27 | }
28 | },
29 | "inputs": {
30 | "input_1": {
31 | "connections": [
32 | {
33 | "node": "7",
34 | "input": "output_1"
35 | }
36 | ]
37 | }
38 | },
39 | "outputs": {
40 | "output_1": {
41 | "connections": []
42 | }
43 | }
44 | },
45 | "4": {
46 | "name": "SequentialPipeline",
47 | "data": {
48 | "elements": [
49 | "5",
50 | "6"
51 | ]
52 | },
53 | "inputs": {
54 | "input_1": {
55 | "connections": []
56 | }
57 | },
58 | "outputs": {
59 | "output_1": {
60 | "connections": []
61 | }
62 | }
63 | },
64 | "5": {
65 | "name": "DialogAgent",
66 | "data": {
67 | "args": {
68 | "name": "Alice",
69 | "sys_prompt": "You are Alice.",
70 | "model_config_name": "qwen"
71 | }
72 | },
73 | "inputs": {
74 | "input_1": {
75 | "connections": []
76 | }
77 | },
78 | "outputs": {
79 | "output_1": {
80 | "connections": []
81 | }
82 | }
83 | },
84 | "6": {
85 | "name": "UserAgent",
86 | "data": {
87 | "args": {
88 | "name": "User"
89 | }
90 | },
91 | "inputs": {
92 | "input_1": {
93 | "connections": []
94 | }
95 | },
96 | "outputs": {
97 | "output_1": {
98 | "connections": []
99 | }
100 | }
101 | },
102 | "7": {
103 | "name": "Message",
104 | "data": {
105 | "args": {
106 | "name": "Host",
107 | "content": "Hello",
108 | "url": ""
109 | }
110 | },
111 | "inputs": {
112 | "input_1": {
113 | "connections": []
114 | }
115 | },
116 | "outputs": {
117 | "output_1": {
118 | "connections": [
119 | {
120 | "node": "3",
121 | "output": "input_1"
122 | }
123 | ]
124 | }
125 | }
126 | }
127 | }
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/web/workstation/examples/2_msghub.json:
--------------------------------------------------------------------------------
1 | {
2 | "2": {
3 | "name": "dashscope_chat",
4 | "data": {
5 | "args": {
6 | "config_name": "qwen",
7 | "model_name": "qwen-max",
8 | "api_key": "************",
9 | "temperature": 0.1,
10 | "seed": 1,
11 | "model_type": "dashscope_chat",
12 | "messages_key": "input"
13 | }
14 | },
15 | "inputs": {},
16 | "outputs": {}
17 | },
18 | "3": {
19 | "name": "MsgHub",
20 | "data": {
21 | "elements": [
22 | "4"
23 | ],
24 | "args": {
25 | "announcement": {
26 | "name": "Host",
27 | "content": "Welcome to group chat!"
28 | }
29 | }
30 | },
31 | "inputs": {
32 | "input_1": {
33 | "connections": [
34 | {
35 | "node": "7",
36 | "input": "output_1"
37 | }
38 | ]
39 | }
40 | },
41 | "outputs": {
42 | "output_1": {
43 | "connections": []
44 | }
45 | }
46 | },
47 | "4": {
48 | "name": "SequentialPipeline",
49 | "data": {
50 | "elements": [
51 | "5",
52 | "6"
53 | ]
54 | },
55 | "inputs": {
56 | "input_1": {
57 | "connections": []
58 | }
59 | },
60 | "outputs": {
61 | "output_1": {
62 | "connections": []
63 | }
64 | }
65 | },
66 | "5": {
67 | "name": "DialogAgent",
68 | "data": {
69 | "args": {
70 | "name": "Alice",
71 | "sys_prompt": "You are Alice.",
72 | "model_config_name": "qwen"
73 | }
74 | },
75 | "inputs": {
76 | "input_1": {
77 | "connections": []
78 | }
79 | },
80 | "outputs": {
81 | "output_1": {
82 | "connections": []
83 | }
84 | }
85 | },
86 | "6": {
87 | "name": "UserAgent",
88 | "data": {
89 | "args": {
90 | "name": "User"
91 | }
92 | },
93 | "inputs": {
94 | "input_1": {
95 | "connections": []
96 | }
97 | },
98 | "outputs": {
99 | "output_1": {
100 | "connections": []
101 | }
102 | }
103 | },
104 | "7": {
105 | "name": "Message",
106 | "data": {
107 | "args": {
108 | "name": "Host",
109 | "content": "Hello",
110 | "url": ""
111 | }
112 | },
113 | "inputs": {
114 | "input_1": {
115 | "connections": []
116 | }
117 | },
118 | "outputs": {
119 | "output_1": {
120 | "connections": [
121 | {
122 | "node": "3",
123 | "output": "input_1"
124 | }
125 | ]
126 | }
127 | }
128 | }
129 | }
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/web/workstation/examples/4_copiednode.json:
--------------------------------------------------------------------------------
1 | {
2 | "7": {
3 | "name": "DialogAgent",
4 | "data": {
5 | "args": {
6 | "name": "Alice",
7 | "sys_prompt": "You are Alice.",
8 | "model_config_name": "qwen"
9 | }
10 | },
11 | "inputs": {
12 | "input_1": {
13 | "connections": [
14 | {
15 | "node": "11",
16 | "input": "output_1"
17 | }
18 | ]
19 | }
20 | },
21 | "outputs": {
22 | "output_1": {
23 | "connections": [
24 | {
25 | "node": "8",
26 | "output": "input_1"
27 | }
28 | ]
29 | }
30 | }
31 | },
32 | "8": {
33 | "name": "UserAgent",
34 | "data": {
35 | "args": {
36 | "name": "User"
37 | }
38 | },
39 | "inputs": {
40 | "input_1": {
41 | "connections": [
42 | {
43 | "node": "7",
44 | "input": "output_1"
45 | }
46 | ]
47 | }
48 | },
49 | "outputs": {
50 | "output_1": {
51 | "connections": [
52 | {
53 | "node": "12",
54 | "output": "input_1"
55 | }
56 | ]
57 | }
58 | }
59 | },
60 | "10": {
61 | "name": "dashscope_chat",
62 | "data": {
63 | "args": {
64 | "config_name": "qwen",
65 | "model_name": "qwen-max",
66 | "api_key": "************",
67 | "temperature": 0.1,
68 | "seed": 1,
69 | "model_type": "dashscope_chat",
70 | "messages_key": "input"
71 | }
72 | },
73 | "inputs": {},
74 | "outputs": {}
75 | },
76 | "11": {
77 | "name": "Message",
78 | "data": {
79 | "args": {
80 | "name": "Host",
81 | "content": "Hi"
82 | }
83 | },
84 | "inputs": {
85 | "input_1": {
86 | "connections": []
87 | }
88 | },
89 | "outputs": {
90 | "output_1": {
91 | "connections": [
92 | {
93 | "node": "7",
94 | "output": "input_1"
95 | }
96 | ]
97 | }
98 | }
99 | },
100 | "12": {
101 | "name": "CopyNode",
102 | "data": {
103 | "elements": [
104 | "7"
105 | ]
106 | },
107 | "inputs": {
108 | "input_1": {
109 | "connections": [
110 | {
111 | "node": "8",
112 | "input": "output_1"
113 | }
114 | ]
115 | }
116 | },
117 | "outputs": {
118 | "output_1": {
119 | "connections": []
120 | }
121 | }
122 | }
123 | }
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/web/workstation/examples/6_reactagent.json:
--------------------------------------------------------------------------------
1 | {
2 | "2": {
3 | "name": "dashscope_chat",
4 | "data": {
5 | "args": {
6 | "config_name": "qwen",
7 | "model_name": "qwen-max",
8 | "api_key": "************",
9 | "temperature": 0.1,
10 | "seed": 1,
11 | "model_type": "dashscope_chat",
12 | "messages_key": "input"
13 | }
14 | },
15 | "inputs": {},
16 | "outputs": {}
17 | },
18 | "3": {
19 | "name": "ReActAgent",
20 | "data": {
21 | "elements": [
22 | "7",
23 | "5",
24 | "6",
25 | "8"
26 | ],
27 | "args": {
28 | "name": "Alice",
29 | "sys_prompt": "You are Alice",
30 | "model_config_name": "qwen",
31 | "max_iters": 10,
32 | "verbose": "True"
33 | }
34 | },
35 | "inputs": {
36 | "input_1": {
37 | "connections": [
38 | {
39 | "node": "4",
40 | "input": "output_1"
41 | }
42 | ]
43 | }
44 | },
45 | "outputs": {
46 | "output_1": {
47 | "connections": []
48 | }
49 | }
50 | },
51 | "4": {
52 | "name": "Message",
53 | "data": {
54 | "args": {
55 | "name": "Host",
56 | "content": "Hello",
57 | "url": ""
58 | }
59 | },
60 | "inputs": {
61 | "input_1": {
62 | "connections": []
63 | }
64 | },
65 | "outputs": {
66 | "output_1": {
67 | "connections": [
68 | {
69 | "node": "3",
70 | "output": "input_1"
71 | }
72 | ]
73 | }
74 | }
75 | },
76 | "5": {
77 | "name": "BingSearchService",
78 | "data": {
79 | "args": {
80 | "api_key": "************",
81 | "num_results": 3
82 | }
83 | },
84 | "inputs": {},
85 | "outputs": {}
86 | },
87 | "6": {
88 | "name": "PythonService",
89 | "data": {},
90 | "inputs": {},
91 | "outputs": {}
92 | },
93 | "7": {
94 | "name": "ReadTextService",
95 | "data": {},
96 | "inputs": {},
97 | "outputs": {}
98 | },
99 | "8": {
100 | "name": "WriteTextService",
101 | "data": {},
102 | "inputs": {},
103 | "outputs": {}
104 | }
105 | }
--------------------------------------------------------------------------------
/agentscope-main/src/agentscope/web/workstation/workflow_utils.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """Workflow node utils."""
3 |
4 |
5 | def is_callable_expression(s: str) -> bool:
6 | """Check a expression whether a callable expression"""
7 | try:
8 | # Do not detect exp like this
9 | if s in ["input", "print"]:
10 | return False
11 | result = eval(s)
12 | return callable(result)
13 | except Exception:
14 | return False
15 |
16 |
17 | def kwarg_converter(kwargs: dict) -> str:
18 | """Convert a kwarg dict to a string."""
19 | kwarg_parts = []
20 | for key, value in kwargs.items():
21 | if is_callable_expression(value):
22 | kwarg_parts.append(f"{key}={value}")
23 | else:
24 | kwarg_parts.append(f"{key}={repr(value)}")
25 | return ", ".join(kwarg_parts)
26 |
27 |
28 | def deps_converter(dep_vars: list) -> str:
29 | """Convert a dep_vars list to a string."""
30 | return f"[{', '.join(dep_vars)}]"
31 |
32 |
33 | def dict_converter(dictionary: dict) -> str:
34 | """Convert a dictionary to a string."""
35 | result_parts = []
36 | for key, value in dictionary.items():
37 | result_parts.append(f'"{key}": {value}')
38 | return "{" + ", ".join(result_parts) + "}"
39 |
--------------------------------------------------------------------------------
/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/open-sciencelab/Virtual-Scientists/9a6d0f32f9adbccef68f70f1705fa12fc9d10e23/logo.png
--------------------------------------------------------------------------------
/preprocess_data/CS_data/data_extraction/extract_coauthor2json.py:
--------------------------------------------------------------------------------
1 | import json
2 | import re
3 | from tqdm import tqdm
4 |
5 | def extract_coauthors(output_dir, filename):
6 | with open(filename, 'r') as file:
7 | data = file.read()
8 |
9 | # Split the data into blocks based on the author index
10 | coauthors_blocks = data.split('#')[1:] # Ignore the first empty split
11 |
12 | author2coauthor = {}
13 | for block in tqdm(coauthors_blocks):
14 | info_str = block.strip('\n').split('\t')
15 |
16 | author1 = info_str[0]
17 | author2 = info_str[1]
18 | weight = info_str[2]
19 | if author1 not in author2coauthor.keys():
20 | author2coauthor[author1] = []
21 | if author2 not in author2coauthor.keys():
22 | author2coauthor[author2] = []
23 |
24 | author2coauthor[author1].append({
25 | 'coauthor_id':author2,
26 | 'weight':weight
27 | })
28 |
29 | author2coauthor[author2].append({
30 | 'coauthor_id':author1,
31 | 'weight':weight
32 | })
33 |
34 | with open('{}/author2coauthor.json'.format(output_dir), 'w') as json_file:
35 | json.dump(author2coauthor, json_file, indent=4)
36 |
37 | if __name__=='__main__':
38 | # Example usage
39 | output_dir = '/home/bingxing2/ailab/group/ai4agr/shy/s4s'
40 | filename = 'AMiner-Coauthor.txt'
41 | extract_coauthors(output_dir, filename)
42 |
--------------------------------------------------------------------------------
/preprocess_data/CS_data/data_extraction/extract_publication2json.py:
--------------------------------------------------------------------------------
1 | import json
2 | import re
3 | from tqdm import tqdm
4 |
5 | def extract_papers_authors(output_dir, filename):
6 | with open(filename, 'r') as file:
7 | data = file.read()
8 |
9 | # Split the data into blocks based on the author index
10 | blocks = data.split('\n')[:-1] # Ignore the first empty split
11 |
12 | paper2author = {}
13 | author2paper = {}
14 | for block in tqdm(blocks):
15 | info_str = block.strip('\n').split('\t')
16 |
17 | author = info_str[1]
18 | paper = info_str[2]
19 |
20 | if author not in author2paper.keys():
21 | author2paper[author] = []
22 | if paper not in paper2author.keys():
23 | paper2author[paper] = []
24 |
25 | author2paper[author].append(paper)
26 | paper2author[paper].append(author)
27 |
28 | with open('{}/author2paper.json'.format(output_dir), 'w') as json_file:
29 | json.dump(author2paper, json_file, indent=4)
30 |
31 | with open('{}/paper2author.json'.format(output_dir), 'w') as json_file:
32 | json.dump(paper2author, json_file, indent=4)
33 |
34 | if __name__=='__main__':
35 | # Example usage
36 | output_dir = '/home/bingxing2/ailab/group/ai4agr/shy/s4s'
37 | filename = 'AMiner-Author2Paper.txt'
38 | extract_papers_authors(output_dir, filename)
39 |
--------------------------------------------------------------------------------
/preprocess_data/CS_data/database/add_paper_citation_num.py:
--------------------------------------------------------------------------------
1 | import sqlite3
2 | import os
3 | import json
4 | import re
5 | from tqdm import tqdm
6 | def add_paper_citation_num(root_dir):
7 | global_database_name = 'global_database.db'
8 | # connect to database, if it doesn't exist then build one
9 | conn = sqlite3.connect(os.path.join(root_dir, global_database_name))
10 | # create cursor
11 | cursor = conn.cursor()
12 |
13 | cursor.execute(f"SELECT * FROM papers")
14 | all_papers = cursor.fetchall()
15 |
16 | paper_citation = {}
17 | for paper in tqdm(all_papers):
18 | refs = paper[6].split(';') if paper[6] is not None else None
19 | if refs is None:
20 | continue
21 |
22 | for ref in refs:
23 | ref = ref.strip()
24 | if ref not in paper_citation.keys():
25 | paper_citation[ref] = 1
26 | else:
27 | paper_citation[ref] += 1
28 |
29 | cursor.execute('ALTER TABLE papers ADD COLUMN citation_num INTEGER')
30 | for k, v in tqdm(paper_citation.items()):
31 | cursor.execute(f'UPDATE papers SET citation_num = {v} WHERE id = {int(k)}')
32 |
33 | conn.commit()
34 | cursor.close()
35 | conn.close()
36 |
37 | if __name__=='__main__':
38 | # data dir
39 | root_dir = '/home/bingxing2/ailab/group/ai4agr/shy/s4s'
40 | add_paper_citation_num(root_dir)
--------------------------------------------------------------------------------
/preprocess_data/CS_data/visualization/author_affiliation_distribution.py:
--------------------------------------------------------------------------------
1 | import json
2 | from tqdm import tqdm
3 | import os
4 | import sqlite3
5 |
6 | replace_dict = {
7 | 'univ.':'university',
8 | 'dept.':'department'
9 | }
10 |
11 | def affiliation_str_clean(affiliation):
12 | for k, v in replace_dict.items():
13 | affiliation = affiliation.replace(k, v)
14 | affiliation = affiliation.replace(' ', ' ')
15 | return affiliation
16 |
17 | def extract_affiliations(root_dir, data_dir):
18 | # load database
19 | database_dir = os.path.join(root_dir, 'global_database.db')
20 | conn = sqlite3.connect(database_dir)
21 | cursor = conn.cursor()
22 |
23 | # load authors
24 | with open('{}/agentID2authorID.json'.format(data_dir), 'r') as file:
25 | agentID2authorID = json.load(file)
26 |
27 | # load affiliatioons
28 | affiliations = {}
29 | for agentID, authorID in tqdm(agentID2authorID.items()):
30 | cursor.execute(f'SELECT affiliations FROM authors WHERE id = {authorID}')
31 | rows = cursor.fetchall()
32 | affis = rows[0][0].split(';')
33 | for affi in affis:
34 | affi_split = affi.strip().split(',')
35 | affi1 = affiliation_str_clean(affi_split[0].strip())
36 | try:
37 | affiliations[affi1] += 1
38 | except:
39 | affiliations[affi1] = 1
40 | if len(affi_split)>=3:
41 | affi2 = affiliation_str_clean(affi_split[1].strip())
42 | try:
43 | affiliations[affi2] += 1
44 | except:
45 | affiliations[affi2] = 1
46 |
47 | return affiliations
48 |
49 | if __name__ == '__main__':
50 | # load the karate club graph
51 | root_dir = '/home/bingxing2/ailab/group/ai4agr/shy/s4s'
52 | used_data_dir = 'authors_degree_ge50_from_year2000to2010'
53 | affiliations = extract_affiliations(root_dir, os.path.join(root_dir, used_data_dir))
54 | affiliations = [[k, v] for k, v in affiliations.items()]
55 | affiliations = sorted(affiliations, key=lambda x:x[1], reverse=True)
56 |
57 | # save result
58 | save_dir = 'results'
59 | if not os.path.exists(save_dir):
60 | os.mkdir(save_dir)
61 | with open(f'{save_dir}/affiliation.txt', 'w') as file:
62 | file.write(f"there are {len(affiliations)} affiliations\n")
63 | for affi in affiliations:
64 | file.write(f"{affi[0]}:{affi[1]}\n")
--------------------------------------------------------------------------------
/preprocess_data/CS_data/visualization/author_citation_distribution.py:
--------------------------------------------------------------------------------
1 | import json
2 | from tqdm import tqdm
3 | import os
4 | import sqlite3
5 | import matplotlib.pyplot as plt
6 | import pandas as pd
7 |
8 | def extract_citations(root_dir, used_data_dir):
9 | # load database
10 | database_dir = os.path.join(root_dir, 'database.db')
11 | conn = sqlite3.connect(database_dir)
12 | cursor = conn.cursor()
13 |
14 | # load authors
15 | with open('{}/agentID2authorID.json'.format(os.path.join(root_dir, used_data_dir)), 'r') as file:
16 | agentID2authorID = json.load(file)
17 |
18 | # load affiliatioons
19 | citations = []
20 | for agentID, authorID in tqdm(agentID2authorID.items()):
21 | cursor.execute(f'SELECT citation_num FROM users WHERE id = {authorID}')
22 | rows = cursor.fetchall()
23 | citations.append(rows[0][0])
24 | return citations
25 |
26 | def draw_citation_histogram(citations):
27 | # Create a DataFrame
28 | df = pd.DataFrame(citations, columns=['Citations'])
29 |
30 | # Plot the histogram
31 | plt.figure(figsize=(10, 6))
32 | plt.hist(df['Citations'], bins=range(min(citations), max(citations), 200), edgecolor='black')
33 |
34 | plt.xticks(range(0, 16000, 1000),
35 | labels=range(0, 160, 10))
36 |
37 | # Show the plot
38 | # Add titles and labels
39 | plt.title('Histogram of Authors by Citation Range')
40 | plt.xlabel('Citation Range (x100)')
41 | plt.ylabel('Number of Authors')
42 |
43 | save_dir = 'results'
44 | if not os.path.exists(save_dir):
45 | os.mkdir(save_dir)
46 | plt.savefig(f'{save_dir}/citation.png', bbox_inches='tight')
47 |
48 | if __name__ == '__main__':
49 | # load the karate club graph
50 | root_dir = '/home/bingxing2/ailab/group/ai4agr/shy/s4s'
51 | used_data_dir = '156authors_degree_ge50_from_year2000to2010'
52 | citations = extract_citations(root_dir, used_data_dir)
53 | draw_citation_histogram(citations)
--------------------------------------------------------------------------------
/preprocess_data/CS_data/visualization/author_topic_distrbution.py:
--------------------------------------------------------------------------------
1 | import json
2 | from tqdm import tqdm
3 | import os
4 | import sqlite3
5 |
6 | replace_dict = {
7 | 'univ.':'university',
8 | 'dept.':'department'
9 | }
10 |
11 | def affiliation_str_clean(affiliation):
12 | for k, v in replace_dict.items():
13 | affiliation = affiliation.replace(k, v)
14 | affiliation = affiliation.replace(' ', ' ')
15 | return affiliation
16 |
17 | def extract_topics(root_dir, used_data_dir):
18 | # load database
19 | database_dir = os.path.join(root_dir, 'global_database.db')
20 | conn = sqlite3.connect(database_dir)
21 | cursor = conn.cursor()
22 |
23 | # load authors
24 | with open('{}/agentID2authorID.json'.format(os.path.join(root_dir, used_data_dir)), 'r') as file:
25 | agentID2authorID = json.load(file)
26 |
27 | # load affiliatioons
28 | all_topics = {}
29 | for agentID, authorID in tqdm(agentID2authorID.items()):
30 | cursor.execute(f'SELECT topics FROM users WHERE id = {authorID}')
31 | rows = cursor.fetchall()
32 | topics = rows[0][0].split(';')
33 | for topic in topics:
34 | topic_splits = topic.strip().split(',')
35 | for topic_split in topic_splits:
36 | try:
37 | all_topics[topic_split.strip()] += 1
38 | except:
39 | all_topics[topic_split.strip()] = 1
40 |
41 | return all_topics
42 |
43 | if __name__ == '__main__':
44 | # load the karate club graph
45 | root_dir = '/home/bingxing2/ailab/group/ai4agr/shy/s4s'
46 | used_data_dir = '156authors_degree_ge50_from_year2000to2010'
47 | topics = extract_topics(root_dir, used_data_dir)
48 | topics = [[k, v] for k, v in topics.items()]
49 | topics = sorted(topics, key=lambda x:x[1], reverse=True)
50 |
51 | # save result
52 | save_dir = 'results'
53 | if not os.path.exists(save_dir):
54 | os.mkdir(save_dir)
55 | with open(f'{save_dir}/topic.txt', 'w') as file:
56 | file.write(f"there are {len(topics)} topics\n")
57 | for topic in topics:
58 | file.write(f"{topic[0]}:{topic[1]}\n")
--------------------------------------------------------------------------------
/sci_platform/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/open-sciencelab/Virtual-Scientists/9a6d0f32f9adbccef68f70f1705fa12fc9d10e23/sci_platform/.DS_Store
--------------------------------------------------------------------------------
/sci_platform/__pycache__/platform.cpython-311.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/open-sciencelab/Virtual-Scientists/9a6d0f32f9adbccef68f70f1705fa12fc9d10e23/sci_platform/__pycache__/platform.cpython-311.pyc
--------------------------------------------------------------------------------
/sci_platform/configs/knowledge_config.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "knowledge_id": "professional paper",
4 | "emb_model_config_name": "ollama_embedding-mxbai-embed-large",
5 | "data_processing": [
6 | {
7 | "load_data": {
8 | "loader": {
9 | "create_object": true,
10 | "module": "llama_index.core",
11 | "class": "SimpleDirectoryReader",
12 | "init_args": {
13 | "input_dir": "/home/bingxing2/ailab/group/ai4agr/crq/SciSci/books",
14 | "required_exts": [
15 | ".txt"
16 | ]
17 | }
18 | }
19 | }
20 | }
21 | ]
22 | }
23 | ]
--------------------------------------------------------------------------------
/sci_platform/configs/model_configs.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "config_name": "ollama_llama3.1_8b",
4 | "model_type": "ollama_chat",
5 | "model_name": "llama3.1",
6 | "options": {
7 | "temperature": 0.5,
8 | "seed": 123
9 | },
10 | "keep_alive": "5m"
11 | },
12 | {
13 | "config_name": "ollama_llama3.1_70b",
14 | "model_type": "ollama_chat",
15 | "model_name": "llama3.1:70b",
16 | "options": {
17 | "temperature": 0.5,
18 | "seed": 123
19 | },
20 | "keep_alive": "5m"
21 | },
22 | {
23 | "config_name": "ollama_llama3_8b",
24 | "model_type": "ollama_chat",
25 | "model_name": "llama3",
26 | "options": {
27 | "temperature": 0.5,
28 | "seed": 123
29 | },
30 | "keep_alive": "5m"
31 | },
32 | {
33 | "config_name": "ollama_llama3_70b",
34 | "model_type": "ollama_chat",
35 | "model_name": "llama3:70b",
36 | "options": {
37 | "temperature": 0.5,
38 | "seed": 123
39 | },
40 | "keep_alive": "5m"
41 | },
42 | {
43 | "config_name": "ollama_embedding-qwen:0.5b",
44 | "model_type": "ollama_embedding",
45 | "model_name": "qwen:0.5b",
46 | "options": {
47 | "temperature": 0.7
48 | },
49 | "keep_alive": "5m"
50 | },
51 | {
52 | "config_name": "ollama_embedding-mxbai-embed-large",
53 | "model_type": "ollama_embedding",
54 | "model_name": "mxbai-embed-large",
55 | "options": {
56 | "temperature": 0.7
57 | },
58 | "keep_alive": "5m"
59 | }
60 | ]
--------------------------------------------------------------------------------
/sci_platform/run.py:
--------------------------------------------------------------------------------
1 | from sci_platform import Platform
2 | from utils.scientist_utils import read_txt_files_as_dict
3 | import os
4 | import argparse
5 | def parse_arguments():
6 | parser = argparse.ArgumentParser(description="Run experiments")
7 | # parser.add_argument(
8 | # "--skip-idea-generation",
9 | # action="store_true",
10 | # help="Skip idea generation and load existing ideas",
11 | # )
12 | # parser.add_argument(
13 | # "--skip-novelty-check",
14 | # action="store_true",
15 | # help="Skip novelty check and use existing ideas",
16 | # )
17 |
18 | # how many runs
19 | parser.add_argument(
20 | "--runs",
21 | type=int,
22 | default=10,
23 | help="Calculate average on how many runs.",
24 | )
25 | # team limit
26 | parser.add_argument(
27 | "--team_limit",
28 | type=int,
29 | default=2,
30 | help="Max number of teams for a scientist.",
31 | )
32 | parser.add_argument(
33 | "--max_discuss_iteration",
34 | type=int,
35 | default=2,
36 | help="Max discuss iteration.",
37 | )
38 | parser.add_argument(
39 | "--max_team_member",
40 | type=int,
41 | default=2,
42 | help="Max team mamber of a team, actual team size is max_team_member.",
43 | )
44 | parser.add_argument(
45 | "--epochs",
46 | type=int,
47 | default=6,
48 | help="Epochs.",
49 | )
50 |
51 | return parser.parse_args()
52 |
53 | if __name__ == '__main__':
54 | args = parse_arguments()
55 |
56 | args.save_dir = f'team_info/{args.max_discuss_iteration}_itrs_{args.max_team_member}_members'
57 | args.log_dir = f'team_log/{args.max_discuss_iteration}_itrs_{args.max_team_member}_members'
58 |
59 | end =False
60 | os.makedirs(args.save_dir, exist_ok=True)
61 | os.makedirs(args.log_dir, exist_ok=True)
62 |
63 | while end==False:
64 | print(f'{len(os.listdir(args.save_dir))} files are created...')
65 | platform_example = Platform(
66 | team_limit = args.team_limit,
67 | group_max_discuss_iteration = args.max_discuss_iteration,
68 | max_teammember = args.max_team_member-1,
69 | log_dir = args.log_dir,
70 | info_dir = args.save_dir
71 | )
72 | platform_example.running(args.epochs)
73 | if len(os.listdir(args.save_dir)) >= args.team_limit*args.runs:
74 | end = True
75 |
--------------------------------------------------------------------------------
/sci_platform/sci_team/__init__.py:
--------------------------------------------------------------------------------
1 | from .SciTeam import Team
--------------------------------------------------------------------------------
/sci_platform/utils/__init__.py:
--------------------------------------------------------------------------------
1 | from .prompt import Prompts
2 | from .scientist_utils import *
--------------------------------------------------------------------------------