Compare commits
84 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 39c6c37dee | |||
| 3438f74e60 | |||
| 4f79712570 | |||
| 8e85ce0678 | |||
| ff09e7bf1b | |||
| 46e1c6706c | |||
| d8a59d0726 | |||
| 108d2019cd | |||
| 3682ef2420 | |||
| a066db6624 | |||
| 7458d64c05 | |||
| 2a1787f28f | |||
| de78c229ce | |||
|
|
f386c67acf | ||
|
|
75f98bf349 | ||
|
|
9870fcbc5d | ||
|
|
d2b8379505 | ||
|
|
2dcb97255c | ||
|
|
f7dd227cd0 | ||
| e2c18c3a24 | |||
| 1bc6c6eab8 | |||
|
|
4b39b137de | ||
| e5de293919 | |||
| 8a10374570 | |||
| ad37a041ab | |||
| 44daea4447 | |||
| 6989a4da13 | |||
| de4583691c | |||
| d8c9b07a51 | |||
| 54d31f40b2 | |||
| ec73b5ff34 | |||
| 9fcdcc3aff | |||
| 05ab2b68f4 | |||
| 79330ef8f5 | |||
| 45ed369a78 | |||
| 37c17fc7da | |||
| 23640d2647 | |||
| be54ec8302 | |||
| 638f81a781 | |||
| e00306b6f8 | |||
| 3fec1c38a1 | |||
| edc9e3c150 | |||
| a155122898 | |||
| f0552f38a0 | |||
|
|
f99419371a | ||
|
|
86d47c218b | ||
|
|
bd5cafbad7 | ||
|
|
b71362eb9a | ||
|
|
673d982360 | ||
|
|
712b46864a | ||
|
|
186c3aae59 | ||
|
|
0794fe948b | ||
|
|
ba2d6e4310 | ||
|
|
b9e5d14b48 | ||
|
|
bf26b0af1d | ||
|
|
8e82b2865b | ||
|
|
367340d69d | ||
|
|
0b77c73809 | ||
|
|
51b432d911 | ||
|
|
f7a679b2a3 | ||
|
|
15c9d60760 | ||
|
|
c69b53fd4e | ||
|
|
9cdab1f392 | ||
|
|
34656cf1f9 | ||
|
|
cf98822749 | ||
|
|
2335d14623 | ||
| 4a72698402 | |||
| fcb857f756 | |||
|
|
ba07f85fd8 | ||
|
|
7b621243d0 | ||
| 598b312140 | |||
| 0df10f5cb3 | |||
| 2c748a9fc8 | |||
| a2e1b4fb27 | |||
| 9b0da9f245 | |||
| 5b9426ba11 | |||
|
|
228abe36a3 | ||
|
|
c3fe788a5b | ||
|
|
025e8fba69 | ||
|
|
59a0519b4e | ||
|
|
dfcaeec85f | ||
|
|
e374520654 | ||
| 834c413cfc | |||
| da9965bdc6 |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -39,8 +39,11 @@ data.ms/
|
||||
test_basic
|
||||
cli/hero
|
||||
.aider*
|
||||
storage/
|
||||
.qdrant-initialized
|
||||
.compile_cache
|
||||
compile_results.log
|
||||
tmp
|
||||
compile_summary.log
|
||||
.summary_lock
|
||||
.aider*
|
||||
|
||||
@@ -51,7 +51,7 @@ fn do() ! {
|
||||
mut cmd := Command{
|
||||
name: 'hero'
|
||||
description: 'Your HERO toolset.'
|
||||
version: '1.0.22'
|
||||
version: '1.0.25'
|
||||
}
|
||||
|
||||
// herocmds.cmd_run_add_flags(mut cmd)
|
||||
|
||||
71
examples/aiexamples/groq.vsh
Executable file
71
examples/aiexamples/groq.vsh
Executable file
@@ -0,0 +1,71 @@
|
||||
#!/usr/bin/env -S v -n -w -gc none -cc tcc -d use_openssl -enable-globals run
|
||||
|
||||
module main
|
||||
|
||||
import freeflowuniverse.herolib.clients.openai
|
||||
import os
|
||||
|
||||
fn test1(mut client openai.OpenAI) ! {
|
||||
instruction := '
|
||||
You are a template language converter. You convert Pug templates to Jet templates.
|
||||
|
||||
The target template language, Jet, is defined as follows:
|
||||
'
|
||||
|
||||
// Create a chat completion request
|
||||
res := client.chat_completion(
|
||||
msgs: openai.Messages{
|
||||
messages: [
|
||||
openai.Message{
|
||||
role: .user
|
||||
content: 'What are the key differences between Groq and other AI inference providers?'
|
||||
},
|
||||
]
|
||||
}
|
||||
)!
|
||||
|
||||
// Print the response
|
||||
println('\nGroq AI Response:')
|
||||
println('==================')
|
||||
println(res.choices[0].message.content)
|
||||
println('\nUsage Statistics:')
|
||||
println('Prompt tokens: ${res.usage.prompt_tokens}')
|
||||
println('Completion tokens: ${res.usage.completion_tokens}')
|
||||
println('Total tokens: ${res.usage.total_tokens}')
|
||||
}
|
||||
|
||||
fn test2(mut client openai.OpenAI) ! {
|
||||
// Create a chat completion request
|
||||
res := client.chat_completion(
|
||||
model: 'deepseek-r1-distill-llama-70b'
|
||||
msgs: openai.Messages{
|
||||
messages: [
|
||||
openai.Message{
|
||||
role: .user
|
||||
content: 'A story of 10 lines?'
|
||||
},
|
||||
]
|
||||
}
|
||||
)!
|
||||
|
||||
println('\nGroq AI Response:')
|
||||
println('==================')
|
||||
println(res.choices[0].message.content)
|
||||
println('\nUsage Statistics:')
|
||||
println('Prompt tokens: ${res.usage.prompt_tokens}')
|
||||
println('Completion tokens: ${res.usage.completion_tokens}')
|
||||
println('Total tokens: ${res.usage.total_tokens}')
|
||||
}
|
||||
|
||||
println("
|
||||
TO USE:
|
||||
export AIKEY='gsk_...'
|
||||
export AIURL='https://api.groq.com/openai/v1'
|
||||
export AIMODEL='llama-3.3-70b-versatile'
|
||||
")
|
||||
|
||||
mut client := openai.get(name: 'test')!
|
||||
println(client)
|
||||
|
||||
// test1(mut client)!
|
||||
test2(mut client)!
|
||||
7
examples/aiexamples/jetconvertor.vsh
Executable file
7
examples/aiexamples/jetconvertor.vsh
Executable file
@@ -0,0 +1,7 @@
|
||||
#!/usr/bin/env -S v -n -w -cg -gc none -cc tcc -d use_openssl -enable-globals run
|
||||
|
||||
import freeflowuniverse.herolib.mcp.aitools
|
||||
|
||||
// aitools.convert_pug("/root/code/github/freeflowuniverse/herolauncher/pkg/herolauncher/web/templates/admin")!
|
||||
|
||||
aitools.convert_pug('/root/code/github/freeflowuniverse/herolauncher/pkg/zaz/webui/templates')!
|
||||
@@ -1,69 +0,0 @@
|
||||
#!/usr/bin/env -S v -n -w -gc none -cc tcc -d use_openssl -enable-globals run
|
||||
|
||||
import freeflowuniverse.herolib.clients.jina
|
||||
import freeflowuniverse.herolib.osal
|
||||
import os
|
||||
|
||||
// Example of using the Jina client
|
||||
|
||||
fn main() {
|
||||
// Set environment variable for testing
|
||||
// In production, you would set this in your environment
|
||||
// osal.env_set(key: 'JINAKEY', value: 'your-api-key')
|
||||
|
||||
// Check if JINAKEY environment variable exists
|
||||
if !osal.env_exists('JINAKEY') {
|
||||
println('JINAKEY environment variable not set. Please set it before running this example.')
|
||||
exit(1)
|
||||
}
|
||||
|
||||
// Create a Jina client instance
|
||||
mut client := jina.get(name: 'default')!
|
||||
|
||||
println('Jina client initialized successfully.')
|
||||
|
||||
// Example: Create embeddings
|
||||
model := 'jina-embeddings-v3'
|
||||
texts := ['Hello, world!', 'How are you doing?']
|
||||
|
||||
println('Creating embeddings for texts: ${texts}')
|
||||
result := client.create_embeddings(texts, model, 'retrieval.query')!
|
||||
|
||||
println('Embeddings created successfully.')
|
||||
println('Model: ${result['model']}')
|
||||
println('Data count: ${result['data'].arr().len}')
|
||||
|
||||
// Example: List classifiers
|
||||
println('\nListing classifiers:')
|
||||
classifiers := client.list_classifiers() or {
|
||||
println('Failed to list classifiers: ${err}')
|
||||
return
|
||||
}
|
||||
|
||||
println('Classifiers retrieved successfully.')
|
||||
|
||||
// Example: Create a classifier
|
||||
println('\nTraining a classifier:')
|
||||
examples := [
|
||||
jina.TrainingExample{
|
||||
text: 'This movie was great!'
|
||||
label: 'positive'
|
||||
},
|
||||
jina.TrainingExample{
|
||||
text: 'I did not like this movie.'
|
||||
label: 'negative'
|
||||
},
|
||||
jina.TrainingExample{
|
||||
text: 'The movie was okay.'
|
||||
label: 'neutral'
|
||||
}
|
||||
]
|
||||
|
||||
training_result := client.train(examples, model, 'private') or {
|
||||
println('Failed to train classifier: ${err}')
|
||||
return
|
||||
}
|
||||
|
||||
println('Classifier trained successfully.')
|
||||
println('Classifier ID: ${training_result['classifier_id']}')
|
||||
}
|
||||
128
examples/aiexamples/qdrant.vsh
Executable file
128
examples/aiexamples/qdrant.vsh
Executable file
@@ -0,0 +1,128 @@
|
||||
#!/usr/bin/env -S v -n -w -gc none -cc tcc -d use_openssl -enable-globals run
|
||||
|
||||
import freeflowuniverse.herolib.clients.qdrant
|
||||
import freeflowuniverse.herolib.installers.db.qdrant_installer
|
||||
import freeflowuniverse.herolib.core.httpconnection
|
||||
import rand
|
||||
import os
|
||||
|
||||
println('Starting Qdrant example script')
|
||||
|
||||
// Print environment information
|
||||
println('Current directory: ${os.getwd()}')
|
||||
println('Home directory: ${os.home_dir()}')
|
||||
|
||||
mut i := qdrant_installer.get()!
|
||||
i.install()!
|
||||
|
||||
// 1. Get the qdrant client
|
||||
println('Getting Qdrant client...')
|
||||
mut qdrant_client := qdrant.get()!
|
||||
println('Qdrant client URL: ${qdrant_client.url}')
|
||||
|
||||
// Check if Qdrant server is running
|
||||
println('Checking Qdrant server health...')
|
||||
health := qdrant_client.health_check() or {
|
||||
println('Error checking health: ${err}')
|
||||
false
|
||||
}
|
||||
println('Qdrant server health: ${health}')
|
||||
|
||||
// Get service info
|
||||
println('Getting Qdrant service info...')
|
||||
service_info := qdrant_client.get_service_info() or {
|
||||
println('Error getting service info: ${err}')
|
||||
exit(1)
|
||||
}
|
||||
println('Qdrant service info: ${service_info}')
|
||||
|
||||
// 2. Generate collection name
|
||||
collection_name := 'collection_' + rand.string(4)
|
||||
println('Generated collection name: ${collection_name}')
|
||||
|
||||
// 3. Create a new collection
|
||||
println('Creating collection...')
|
||||
created_collection := qdrant_client.create_collection(
|
||||
collection_name: collection_name
|
||||
size: 15
|
||||
distance: 'Cosine'
|
||||
) or {
|
||||
println('Error creating collection: ${err}')
|
||||
exit(1)
|
||||
}
|
||||
println('Created Collection: ${created_collection}')
|
||||
|
||||
// 4. Get the created collection
|
||||
println('Getting collection...')
|
||||
get_collection := qdrant_client.get_collection(
|
||||
collection_name: collection_name
|
||||
) or {
|
||||
println('Error getting collection: ${err}')
|
||||
exit(1)
|
||||
}
|
||||
println('Get Collection: ${get_collection}')
|
||||
|
||||
// 5. List all collections
|
||||
println('Listing collections...')
|
||||
list_collection := qdrant_client.list_collections() or {
|
||||
println('Error listing collections: ${err}')
|
||||
exit(1)
|
||||
}
|
||||
println('List Collection: ${list_collection}')
|
||||
|
||||
// 6. Check collection existence
|
||||
println('Checking collection existence...')
|
||||
collection_existence := qdrant_client.is_collection_exists(
|
||||
collection_name: collection_name
|
||||
) or {
|
||||
println('Error checking collection existence: ${err}')
|
||||
exit(1)
|
||||
}
|
||||
println('Collection Existence: ${collection_existence}')
|
||||
|
||||
// 7. Retrieve points
|
||||
println('Retrieving points...')
|
||||
collection_points := qdrant_client.retrieve_points(
|
||||
collection_name: collection_name
|
||||
ids: [
|
||||
0,
|
||||
3,
|
||||
100,
|
||||
]
|
||||
) or {
|
||||
println('Error retrieving points: ${err}')
|
||||
exit(1)
|
||||
}
|
||||
println('Collection Points: ${collection_points}')
|
||||
|
||||
// 8. Upsert points
|
||||
println('Upserting points...')
|
||||
upsert_points := qdrant_client.upsert_points(
|
||||
collection_name: collection_name
|
||||
points: [
|
||||
qdrant.Point{
|
||||
payload: {
|
||||
'key': 'value'
|
||||
}
|
||||
vector: [1.0, 2.0, 3.0]
|
||||
},
|
||||
qdrant.Point{
|
||||
payload: {
|
||||
'key': 'value'
|
||||
}
|
||||
vector: [4.0, 5.0, 6.0]
|
||||
},
|
||||
qdrant.Point{
|
||||
payload: {
|
||||
'key': 'value'
|
||||
}
|
||||
vector: [7.0, 8.0, 9.0]
|
||||
},
|
||||
]
|
||||
) or {
|
||||
println('Error upserting points: ${err}')
|
||||
exit(1)
|
||||
}
|
||||
println('Upsert Points: ${upsert_points}')
|
||||
|
||||
println('Qdrant example script completed successfully')
|
||||
@@ -12,12 +12,11 @@ const openrpc_spec_path = os.join_path(example_dir, 'openrpc.json')
|
||||
openrpc_spec := openrpc.new(path: openrpc_spec_path)!
|
||||
actor_spec := specification.from_openrpc(openrpc_spec)!
|
||||
|
||||
actor_module := generator.generate_actor_module(
|
||||
actor_spec,
|
||||
actor_module := generator.generate_actor_module(actor_spec,
|
||||
interfaces: [.openrpc]
|
||||
)!
|
||||
|
||||
actor_module.write(example_dir,
|
||||
format: true
|
||||
format: true
|
||||
overwrite: true
|
||||
)!
|
||||
@@ -14,6 +14,6 @@ actor_spec := specification.from_openrpc(openrpc_spec)!
|
||||
|
||||
methods_file := generator.generate_methods_file(actor_spec)!
|
||||
methods_file.write(example_dir,
|
||||
format: true
|
||||
format: true
|
||||
overwrite: true
|
||||
)!
|
||||
@@ -14,6 +14,6 @@ actor_spec := specification.from_openrpc(openrpc_spec_)!
|
||||
openrpc_spec := actor_spec.to_openrpc()
|
||||
|
||||
openrpc_file := generator.generate_openrpc_file(openrpc_spec)!
|
||||
openrpc_file.write(os.join_path(example_dir,'docs'),
|
||||
openrpc_file.write(os.join_path(example_dir, 'docs'),
|
||||
overwrite: true
|
||||
)!
|
||||
@@ -5,7 +5,6 @@ import freeflowuniverse.herolib.baobab.specification
|
||||
import freeflowuniverse.herolib.schemas.openapi
|
||||
import os
|
||||
|
||||
|
||||
const example_dir = os.dir(@FILE)
|
||||
const specs = ['merchant', 'profiler', 'farmer']
|
||||
|
||||
@@ -13,13 +12,12 @@ for spec in specs {
|
||||
openapi_spec_path := os.join_path(example_dir, '${spec}.json')
|
||||
openapi_spec := openapi.new(path: openapi_spec_path, process: true)!
|
||||
actor_spec := specification.from_openapi(openapi_spec)!
|
||||
actor_module := generator.generate_actor_folder(
|
||||
actor_spec,
|
||||
actor_module := generator.generate_actor_folder(actor_spec,
|
||||
interfaces: [.openapi, .http]
|
||||
)!
|
||||
actor_module.write(example_dir,
|
||||
format: true
|
||||
format: true
|
||||
overwrite: true
|
||||
compile: false
|
||||
compile: false
|
||||
)!
|
||||
}
|
||||
@@ -15,67 +15,67 @@ pub:
|
||||
name string
|
||||
description string
|
||||
// technical specifications
|
||||
specs map[string]string
|
||||
specs map[string]string
|
||||
// price per unit
|
||||
price f64
|
||||
price f64
|
||||
// currency code (e.g., 'USD', 'EUR')
|
||||
currency string
|
||||
currency string
|
||||
}
|
||||
|
||||
pub struct ProductTemplate {
|
||||
pub:
|
||||
id string
|
||||
name string
|
||||
description string
|
||||
id string
|
||||
name string
|
||||
description string
|
||||
// components that make up this product template
|
||||
components []ProductComponentTemplate
|
||||
components []ProductComponentTemplate
|
||||
// merchant who created this template
|
||||
merchant_id string
|
||||
merchant_id string
|
||||
// category of the product (e.g., 'electronics', 'clothing')
|
||||
category string
|
||||
category string
|
||||
// whether this template is available for use
|
||||
active bool
|
||||
active bool
|
||||
}
|
||||
|
||||
pub struct Product {
|
||||
pub:
|
||||
id string
|
||||
template_id string
|
||||
id string
|
||||
template_id string
|
||||
// specific instance details that may differ from template
|
||||
name string
|
||||
description string
|
||||
name string
|
||||
description string
|
||||
// actual price of this product instance
|
||||
price f64
|
||||
currency string
|
||||
price f64
|
||||
currency string
|
||||
// merchant selling this product
|
||||
merchant_id string
|
||||
merchant_id string
|
||||
// current stock level
|
||||
stock_quantity int
|
||||
stock_quantity int
|
||||
// whether this product is available for purchase
|
||||
available bool
|
||||
available bool
|
||||
}
|
||||
|
||||
pub struct OrderItem {
|
||||
pub:
|
||||
product_id string
|
||||
quantity int
|
||||
price f64
|
||||
currency string
|
||||
product_id string
|
||||
quantity int
|
||||
price f64
|
||||
currency string
|
||||
}
|
||||
|
||||
pub struct Order {
|
||||
pub:
|
||||
id string
|
||||
id string
|
||||
// customer identifier
|
||||
customer_id string
|
||||
customer_id string
|
||||
// items in the order
|
||||
items []OrderItem
|
||||
items []OrderItem
|
||||
// total order amount
|
||||
total_amount f64
|
||||
currency string
|
||||
total_amount f64
|
||||
currency string
|
||||
// order status (e.g., 'pending', 'confirmed', 'shipped', 'delivered')
|
||||
status string
|
||||
status string
|
||||
// timestamps
|
||||
created_at string
|
||||
updated_at string
|
||||
created_at string
|
||||
updated_at string
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ module geomind_poc
|
||||
import freeflowuniverse.crystallib.core.playbook { PlayBook }
|
||||
|
||||
// play_commerce processes heroscript actions for the commerce system
|
||||
pub fn play_commerce(mut plbook playbook.PlayBook) ! {
|
||||
pub fn play_commerce(mut plbook PlayBook) ! {
|
||||
commerce_actions := plbook.find(filter: 'commerce.')!
|
||||
mut c := Commerce{}
|
||||
|
||||
@@ -12,20 +12,20 @@ pub fn play_commerce(mut plbook playbook.PlayBook) ! {
|
||||
'merchant' {
|
||||
mut p := action.params
|
||||
merchant := c.create_merchant(
|
||||
name: p.get('name')!,
|
||||
description: p.get_default('description', '')!,
|
||||
contact: p.get('contact')!
|
||||
name: p.get('name')!
|
||||
description: p.get_default('description', '')!
|
||||
contact: p.get('contact')!
|
||||
)!
|
||||
println('Created merchant: ${merchant.name}')
|
||||
}
|
||||
'component' {
|
||||
mut p := action.params
|
||||
component := c.create_product_component_template(
|
||||
name: p.get('name')!,
|
||||
description: p.get_default('description', '')!,
|
||||
specs: p.get_map(),
|
||||
price: p.get_float('price')!,
|
||||
currency: p.get('currency')!
|
||||
name: p.get('name')!
|
||||
description: p.get_default('description', '')!
|
||||
specs: p.get_map()
|
||||
price: p.get_float('price')!
|
||||
currency: p.get('currency')!
|
||||
)!
|
||||
println('Created component: ${component.name}')
|
||||
}
|
||||
@@ -39,30 +39,30 @@ pub fn play_commerce(mut plbook playbook.PlayBook) ! {
|
||||
// In a real implementation, you would fetch the component from storage
|
||||
// For this example, we create a dummy component
|
||||
component := ProductComponentTemplate{
|
||||
id: id
|
||||
name: 'Component'
|
||||
id: id
|
||||
name: 'Component'
|
||||
description: ''
|
||||
specs: map[string]string{}
|
||||
price: 0
|
||||
currency: 'USD'
|
||||
specs: map[string]string{}
|
||||
price: 0
|
||||
currency: 'USD'
|
||||
}
|
||||
components << component
|
||||
}
|
||||
|
||||
template := c.create_product_template(
|
||||
name: p.get('name')!,
|
||||
description: p.get_default('description', '')!,
|
||||
components: components,
|
||||
merchant_id: p.get('merchant_id')!,
|
||||
category: p.get_default('category', 'General')!
|
||||
name: p.get('name')!
|
||||
description: p.get_default('description', '')!
|
||||
components: components
|
||||
merchant_id: p.get('merchant_id')!
|
||||
category: p.get_default('category', 'General')!
|
||||
)!
|
||||
println('Created template: ${template.name}')
|
||||
}
|
||||
'product' {
|
||||
mut p := action.params
|
||||
product := c.create_product(
|
||||
template_id: p.get('template_id')!,
|
||||
merchant_id: p.get('merchant_id')!,
|
||||
template_id: p.get('template_id')!
|
||||
merchant_id: p.get('merchant_id')!
|
||||
stock_quantity: p.get_int('stock_quantity')!
|
||||
)!
|
||||
println('Created product: ${product.name} with stock: ${product.stock_quantity}')
|
||||
@@ -80,23 +80,23 @@ pub fn play_commerce(mut plbook playbook.PlayBook) ! {
|
||||
}
|
||||
item := OrderItem{
|
||||
product_id: parts[0]
|
||||
quantity: parts[1].int()
|
||||
price: parts[2].f64()
|
||||
currency: parts[3]
|
||||
quantity: parts[1].int()
|
||||
price: parts[2].f64()
|
||||
currency: parts[3]
|
||||
}
|
||||
items << item
|
||||
}
|
||||
|
||||
order := c.create_order(
|
||||
customer_id: p.get('customer_id')!,
|
||||
items: items
|
||||
customer_id: p.get('customer_id')!
|
||||
items: items
|
||||
)!
|
||||
println('Created order: ${order.id} with ${order.items.len} items')
|
||||
}
|
||||
'update_order' {
|
||||
mut p := action.params
|
||||
order := c.update_order_status(
|
||||
order_id: p.get('order_id')!,
|
||||
order_id: p.get('order_id')!
|
||||
new_status: p.get('status')!
|
||||
)!
|
||||
println('Updated order ${order.id} status to: ${order.status}')
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
module geomind_poc
|
||||
|
||||
import crypto.rand
|
||||
import time
|
||||
|
||||
// Commerce represents the main e-commerce server handling all operations
|
||||
pub struct Commerce {
|
||||
mut:
|
||||
merchants map[string]Merchant
|
||||
templates map[string]ProductTemplate
|
||||
products map[string]Product
|
||||
orders map[string]Order
|
||||
merchants map[string]Merchant
|
||||
templates map[string]ProductTemplate
|
||||
products map[string]Product
|
||||
orders map[string]Order
|
||||
}
|
||||
|
||||
// generate_id creates a unique identifier
|
||||
@@ -20,11 +21,11 @@ fn generate_id() string {
|
||||
pub fn (mut c Commerce) create_merchant(name string, description string, contact string) !Merchant {
|
||||
merchant_id := generate_id()
|
||||
merchant := Merchant{
|
||||
id: merchant_id
|
||||
name: name
|
||||
id: merchant_id
|
||||
name: name
|
||||
description: description
|
||||
contact: contact
|
||||
active: true
|
||||
contact: contact
|
||||
active: true
|
||||
}
|
||||
c.merchants[merchant_id] = merchant
|
||||
return merchant
|
||||
@@ -33,12 +34,12 @@ pub fn (mut c Commerce) create_merchant(name string, description string, contact
|
||||
// create_product_component_template creates a new component template
|
||||
pub fn (mut c Commerce) create_product_component_template(name string, description string, specs map[string]string, price f64, currency string) !ProductComponentTemplate {
|
||||
component := ProductComponentTemplate{
|
||||
id: generate_id()
|
||||
name: name
|
||||
id: generate_id()
|
||||
name: name
|
||||
description: description
|
||||
specs: specs
|
||||
price: price
|
||||
currency: currency
|
||||
specs: specs
|
||||
price: price
|
||||
currency: currency
|
||||
}
|
||||
return component
|
||||
}
|
||||
@@ -50,13 +51,13 @@ pub fn (mut c Commerce) create_product_template(name string, description string,
|
||||
}
|
||||
|
||||
template := ProductTemplate{
|
||||
id: generate_id()
|
||||
name: name
|
||||
id: generate_id()
|
||||
name: name
|
||||
description: description
|
||||
components: components
|
||||
components: components
|
||||
merchant_id: merchant_id
|
||||
category: category
|
||||
active: true
|
||||
category: category
|
||||
active: true
|
||||
}
|
||||
c.templates[template.id] = template
|
||||
return template
|
||||
@@ -78,15 +79,15 @@ pub fn (mut c Commerce) create_product(template_id string, merchant_id string, s
|
||||
}
|
||||
|
||||
product := Product{
|
||||
id: generate_id()
|
||||
template_id: template_id
|
||||
name: template.name
|
||||
description: template.description
|
||||
price: total_price
|
||||
currency: template.components[0].currency // assuming all components use same currency
|
||||
merchant_id: merchant_id
|
||||
id: generate_id()
|
||||
template_id: template_id
|
||||
name: template.name
|
||||
description: template.description
|
||||
price: total_price
|
||||
currency: template.components[0].currency // assuming all components use same currency
|
||||
merchant_id: merchant_id
|
||||
stock_quantity: stock_quantity
|
||||
available: true
|
||||
available: true
|
||||
}
|
||||
c.products[product.id] = product
|
||||
return product
|
||||
@@ -114,14 +115,14 @@ pub fn (mut c Commerce) create_order(customer_id string, items []OrderItem) !Ord
|
||||
}
|
||||
|
||||
order := Order{
|
||||
id: generate_id()
|
||||
customer_id: customer_id
|
||||
items: items
|
||||
id: generate_id()
|
||||
customer_id: customer_id
|
||||
items: items
|
||||
total_amount: total_amount
|
||||
currency: currency
|
||||
status: 'pending'
|
||||
created_at: time.now().str()
|
||||
updated_at: time.now().str()
|
||||
currency: currency
|
||||
status: 'pending'
|
||||
created_at: time.now().str()
|
||||
updated_at: time.now().str()
|
||||
}
|
||||
c.orders[order.id] = order
|
||||
|
||||
|
||||
@@ -5,20 +5,21 @@ import freeflowuniverse.herolib.baobab.specification
|
||||
import freeflowuniverse.herolib.schemas.openapi
|
||||
import os
|
||||
|
||||
const example_dir = os.join_path('${os.home_dir()}/code/github/freeflowuniverse/herolib/lib/circles/mcc', 'baobab')
|
||||
const openapi_spec_path = os.join_path('${os.home_dir()}/code/github/freeflowuniverse/herolib/lib/circles/mcc', 'openapi.json')
|
||||
const example_dir = os.join_path('${os.home_dir()}/code/github/freeflowuniverse/herolib/lib/circles/mcc',
|
||||
'baobab')
|
||||
const openapi_spec_path = os.join_path('${os.home_dir()}/code/github/freeflowuniverse/herolib/lib/circles/mcc',
|
||||
'openapi.json')
|
||||
|
||||
// the actor specification obtained from the OpenRPC Specification
|
||||
openapi_spec := openapi.new(path: openapi_spec_path)!
|
||||
actor_spec := specification.from_openapi(openapi_spec)!
|
||||
|
||||
actor_module := generator.generate_actor_module(
|
||||
actor_spec,
|
||||
actor_module := generator.generate_actor_module(actor_spec,
|
||||
interfaces: [.openapi, .http]
|
||||
)!
|
||||
|
||||
actor_module.write(example_dir,
|
||||
format: true
|
||||
format: true
|
||||
overwrite: true
|
||||
compile: false
|
||||
compile: false
|
||||
)!
|
||||
@@ -14,15 +14,14 @@ actor_spec := specification.from_openapi(openapi_spec)!
|
||||
|
||||
println(actor_spec)
|
||||
|
||||
actor_module := generator.generate_actor_module(
|
||||
actor_spec,
|
||||
actor_module := generator.generate_actor_module(actor_spec,
|
||||
interfaces: [.openapi, .http]
|
||||
)!
|
||||
|
||||
actor_module.write(example_dir,
|
||||
format: false
|
||||
format: false
|
||||
overwrite: true
|
||||
compile: false
|
||||
compile: false
|
||||
)!
|
||||
|
||||
// os.execvp('bash', ['${example_dir}/meeting_scheduler_actor/scripts/run.sh'])!
|
||||
@@ -7,100 +7,100 @@ import freeflowuniverse.herolib.schemas.openrpc
|
||||
import os
|
||||
|
||||
const actor_specification = specification.ActorSpecification{
|
||||
name: 'PetStore'
|
||||
interfaces: [.openrpc]
|
||||
methods: [
|
||||
specification.ActorMethod{
|
||||
name: 'GetPets'
|
||||
description: 'finds pets in the system that the user has access to by tags and within a limit'
|
||||
parameters: [
|
||||
openrpc.ContentDescriptor{
|
||||
name: 'tags'
|
||||
description: 'tags to filter by'
|
||||
schema: jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'array'
|
||||
items: jsonschema.Items(jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'string'
|
||||
}))
|
||||
})
|
||||
},
|
||||
openrpc.ContentDescriptor{
|
||||
name: 'limit'
|
||||
description: 'maximum number of results to return'
|
||||
schema: jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'integer'
|
||||
})
|
||||
}
|
||||
]
|
||||
result: openrpc.ContentDescriptor{
|
||||
name: 'pet_list'
|
||||
description: 'all pets from the system, that matches the tags'
|
||||
schema: jsonschema.SchemaRef(jsonschema.Reference{
|
||||
ref: '#/components/schemas/Pet'
|
||||
})
|
||||
}
|
||||
},
|
||||
specification.ActorMethod{
|
||||
name: 'CreatePet'
|
||||
description: 'creates a new pet in the store. Duplicates are allowed.'
|
||||
parameters: [
|
||||
openrpc.ContentDescriptor{
|
||||
name: 'new_pet'
|
||||
description: 'Pet to add to the store.'
|
||||
schema: jsonschema.SchemaRef(jsonschema.Reference{
|
||||
ref: '#/components/schemas/NewPet'
|
||||
})
|
||||
}
|
||||
]
|
||||
result: openrpc.ContentDescriptor{
|
||||
name: 'pet'
|
||||
description: 'the newly created pet'
|
||||
schema: jsonschema.SchemaRef(jsonschema.Reference{
|
||||
ref: '#/components/schemas/Pet'
|
||||
})
|
||||
}
|
||||
},
|
||||
specification.ActorMethod{
|
||||
name: 'GetPetById'
|
||||
description: 'gets a pet based on a single ID, if the user has access to the pet'
|
||||
parameters: [
|
||||
openrpc.ContentDescriptor{
|
||||
name: 'id'
|
||||
description: 'ID of pet to fetch'
|
||||
schema: jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'integer'
|
||||
})
|
||||
}
|
||||
]
|
||||
result: openrpc.ContentDescriptor{
|
||||
name: 'pet'
|
||||
description: 'pet response'
|
||||
schema: jsonschema.SchemaRef(jsonschema.Reference{
|
||||
ref: '#/components/schemas/Pet'
|
||||
})
|
||||
}
|
||||
},
|
||||
specification.ActorMethod{
|
||||
name: 'DeletePetById'
|
||||
description: 'deletes a single pet based on the ID supplied'
|
||||
parameters: [
|
||||
openrpc.ContentDescriptor{
|
||||
name: 'id'
|
||||
description: 'ID of pet to delete'
|
||||
schema: jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'integer'
|
||||
})
|
||||
}
|
||||
]
|
||||
result: openrpc.ContentDescriptor{
|
||||
name: 'pet'
|
||||
description: 'pet deleted'
|
||||
schema: jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'null'
|
||||
})
|
||||
}
|
||||
}
|
||||
]
|
||||
name: 'PetStore'
|
||||
interfaces: [.openrpc]
|
||||
methods: [
|
||||
specification.ActorMethod{
|
||||
name: 'GetPets'
|
||||
description: 'finds pets in the system that the user has access to by tags and within a limit'
|
||||
parameters: [
|
||||
openrpc.ContentDescriptor{
|
||||
name: 'tags'
|
||||
description: 'tags to filter by'
|
||||
schema: jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'array'
|
||||
items: jsonschema.Items(jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'string'
|
||||
}))
|
||||
})
|
||||
},
|
||||
openrpc.ContentDescriptor{
|
||||
name: 'limit'
|
||||
description: 'maximum number of results to return'
|
||||
schema: jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'integer'
|
||||
})
|
||||
},
|
||||
]
|
||||
result: openrpc.ContentDescriptor{
|
||||
name: 'pet_list'
|
||||
description: 'all pets from the system, that matches the tags'
|
||||
schema: jsonschema.SchemaRef(jsonschema.Reference{
|
||||
ref: '#/components/schemas/Pet'
|
||||
})
|
||||
}
|
||||
},
|
||||
specification.ActorMethod{
|
||||
name: 'CreatePet'
|
||||
description: 'creates a new pet in the store. Duplicates are allowed.'
|
||||
parameters: [
|
||||
openrpc.ContentDescriptor{
|
||||
name: 'new_pet'
|
||||
description: 'Pet to add to the store.'
|
||||
schema: jsonschema.SchemaRef(jsonschema.Reference{
|
||||
ref: '#/components/schemas/NewPet'
|
||||
})
|
||||
},
|
||||
]
|
||||
result: openrpc.ContentDescriptor{
|
||||
name: 'pet'
|
||||
description: 'the newly created pet'
|
||||
schema: jsonschema.SchemaRef(jsonschema.Reference{
|
||||
ref: '#/components/schemas/Pet'
|
||||
})
|
||||
}
|
||||
},
|
||||
specification.ActorMethod{
|
||||
name: 'GetPetById'
|
||||
description: 'gets a pet based on a single ID, if the user has access to the pet'
|
||||
parameters: [
|
||||
openrpc.ContentDescriptor{
|
||||
name: 'id'
|
||||
description: 'ID of pet to fetch'
|
||||
schema: jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'integer'
|
||||
})
|
||||
},
|
||||
]
|
||||
result: openrpc.ContentDescriptor{
|
||||
name: 'pet'
|
||||
description: 'pet response'
|
||||
schema: jsonschema.SchemaRef(jsonschema.Reference{
|
||||
ref: '#/components/schemas/Pet'
|
||||
})
|
||||
}
|
||||
},
|
||||
specification.ActorMethod{
|
||||
name: 'DeletePetById'
|
||||
description: 'deletes a single pet based on the ID supplied'
|
||||
parameters: [
|
||||
openrpc.ContentDescriptor{
|
||||
name: 'id'
|
||||
description: 'ID of pet to delete'
|
||||
schema: jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'integer'
|
||||
})
|
||||
},
|
||||
]
|
||||
result: openrpc.ContentDescriptor{
|
||||
name: 'pet'
|
||||
description: 'pet deleted'
|
||||
schema: jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'null'
|
||||
})
|
||||
}
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
openapi_specification := actor_specification.to_openapi()
|
||||
|
||||
@@ -8,101 +8,101 @@ import freeflowuniverse.herolib.schemas.openrpc
|
||||
import os
|
||||
|
||||
const actor_specification = specification.ActorSpecification{
|
||||
name: 'PetStore'
|
||||
structure: code.Struct{}
|
||||
interfaces: [.openrpc]
|
||||
methods: [
|
||||
specification.ActorMethod{
|
||||
name: 'GetPets'
|
||||
description: 'finds pets in the system that the user has access to by tags and within a limit'
|
||||
parameters: [
|
||||
openrpc.ContentDescriptor{
|
||||
name: 'tags'
|
||||
description: 'tags to filter by'
|
||||
schema: jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'array'
|
||||
items: jsonschema.Items(jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'string'
|
||||
}))
|
||||
})
|
||||
},
|
||||
openrpc.ContentDescriptor{
|
||||
name: 'limit'
|
||||
description: 'maximum number of results to return'
|
||||
schema: jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'integer'
|
||||
})
|
||||
}
|
||||
]
|
||||
result: openrpc.ContentDescriptor{
|
||||
name: 'pet_list'
|
||||
description: 'all pets from the system, that matches the tags'
|
||||
schema: jsonschema.SchemaRef(jsonschema.Reference{
|
||||
ref: '#/components/schemas/Pet'
|
||||
})
|
||||
}
|
||||
},
|
||||
specification.ActorMethod{
|
||||
name: 'CreatePet'
|
||||
description: 'creates a new pet in the store. Duplicates are allowed.'
|
||||
parameters: [
|
||||
openrpc.ContentDescriptor{
|
||||
name: 'new_pet'
|
||||
description: 'Pet to add to the store.'
|
||||
schema: jsonschema.SchemaRef(jsonschema.Reference{
|
||||
ref: '#/components/schemas/NewPet'
|
||||
})
|
||||
}
|
||||
]
|
||||
result: openrpc.ContentDescriptor{
|
||||
name: 'pet'
|
||||
description: 'the newly created pet'
|
||||
schema: jsonschema.SchemaRef(jsonschema.Reference{
|
||||
ref: '#/components/schemas/Pet'
|
||||
})
|
||||
}
|
||||
},
|
||||
specification.ActorMethod{
|
||||
name: 'GetPetById'
|
||||
description: 'gets a pet based on a single ID, if the user has access to the pet'
|
||||
parameters: [
|
||||
openrpc.ContentDescriptor{
|
||||
name: 'id'
|
||||
description: 'ID of pet to fetch'
|
||||
schema: jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'integer'
|
||||
})
|
||||
}
|
||||
]
|
||||
result: openrpc.ContentDescriptor{
|
||||
name: 'pet'
|
||||
description: 'pet response'
|
||||
schema: jsonschema.SchemaRef(jsonschema.Reference{
|
||||
ref: '#/components/schemas/Pet'
|
||||
})
|
||||
}
|
||||
},
|
||||
specification.ActorMethod{
|
||||
name: 'DeletePetById'
|
||||
description: 'deletes a single pet based on the ID supplied'
|
||||
parameters: [
|
||||
openrpc.ContentDescriptor{
|
||||
name: 'id'
|
||||
description: 'ID of pet to delete'
|
||||
schema: jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'integer'
|
||||
})
|
||||
}
|
||||
]
|
||||
result: openrpc.ContentDescriptor{
|
||||
name: 'pet'
|
||||
description: 'pet deleted'
|
||||
schema: jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'null'
|
||||
})
|
||||
}
|
||||
}
|
||||
]
|
||||
name: 'PetStore'
|
||||
structure: code.Struct{}
|
||||
interfaces: [.openrpc]
|
||||
methods: [
|
||||
specification.ActorMethod{
|
||||
name: 'GetPets'
|
||||
description: 'finds pets in the system that the user has access to by tags and within a limit'
|
||||
parameters: [
|
||||
openrpc.ContentDescriptor{
|
||||
name: 'tags'
|
||||
description: 'tags to filter by'
|
||||
schema: jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'array'
|
||||
items: jsonschema.Items(jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'string'
|
||||
}))
|
||||
})
|
||||
},
|
||||
openrpc.ContentDescriptor{
|
||||
name: 'limit'
|
||||
description: 'maximum number of results to return'
|
||||
schema: jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'integer'
|
||||
})
|
||||
},
|
||||
]
|
||||
result: openrpc.ContentDescriptor{
|
||||
name: 'pet_list'
|
||||
description: 'all pets from the system, that matches the tags'
|
||||
schema: jsonschema.SchemaRef(jsonschema.Reference{
|
||||
ref: '#/components/schemas/Pet'
|
||||
})
|
||||
}
|
||||
},
|
||||
specification.ActorMethod{
|
||||
name: 'CreatePet'
|
||||
description: 'creates a new pet in the store. Duplicates are allowed.'
|
||||
parameters: [
|
||||
openrpc.ContentDescriptor{
|
||||
name: 'new_pet'
|
||||
description: 'Pet to add to the store.'
|
||||
schema: jsonschema.SchemaRef(jsonschema.Reference{
|
||||
ref: '#/components/schemas/NewPet'
|
||||
})
|
||||
},
|
||||
]
|
||||
result: openrpc.ContentDescriptor{
|
||||
name: 'pet'
|
||||
description: 'the newly created pet'
|
||||
schema: jsonschema.SchemaRef(jsonschema.Reference{
|
||||
ref: '#/components/schemas/Pet'
|
||||
})
|
||||
}
|
||||
},
|
||||
specification.ActorMethod{
|
||||
name: 'GetPetById'
|
||||
description: 'gets a pet based on a single ID, if the user has access to the pet'
|
||||
parameters: [
|
||||
openrpc.ContentDescriptor{
|
||||
name: 'id'
|
||||
description: 'ID of pet to fetch'
|
||||
schema: jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'integer'
|
||||
})
|
||||
},
|
||||
]
|
||||
result: openrpc.ContentDescriptor{
|
||||
name: 'pet'
|
||||
description: 'pet response'
|
||||
schema: jsonschema.SchemaRef(jsonschema.Reference{
|
||||
ref: '#/components/schemas/Pet'
|
||||
})
|
||||
}
|
||||
},
|
||||
specification.ActorMethod{
|
||||
name: 'DeletePetById'
|
||||
description: 'deletes a single pet based on the ID supplied'
|
||||
parameters: [
|
||||
openrpc.ContentDescriptor{
|
||||
name: 'id'
|
||||
description: 'ID of pet to delete'
|
||||
schema: jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'integer'
|
||||
})
|
||||
},
|
||||
]
|
||||
result: openrpc.ContentDescriptor{
|
||||
name: 'pet'
|
||||
description: 'pet deleted'
|
||||
schema: jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'null'
|
||||
})
|
||||
}
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
openrpc_specification := actor_specification.to_openrpc()
|
||||
|
||||
@@ -8,13 +8,10 @@ const build_path = os.join_path(os.dir(@FILE), '/docusaurus')
|
||||
|
||||
buildpath := '${os.home_dir()}/hero/var/mdbuild/bizmodel'
|
||||
|
||||
mut model := bizmodel.generate("test", playbook_path)!
|
||||
mut model := bizmodel.generate('test', playbook_path)!
|
||||
|
||||
println(model.sheet)
|
||||
println(model.sheet.export()!)
|
||||
|
||||
model.sheet.export(path:"~/Downloads/test.csv")!
|
||||
model.sheet.export(path:"~/code/github/freeflowuniverse/starlight_template/src/content/test.csv")!
|
||||
|
||||
|
||||
|
||||
model.sheet.export(path: '~/Downloads/test.csv')!
|
||||
model.sheet.export(path: '~/code/github/freeflowuniverse/starlight_template/src/content/test.csv')!
|
||||
|
||||
@@ -6,13 +6,13 @@ import freeflowuniverse.herolib.core.playbook
|
||||
import freeflowuniverse.herolib.core.playcmds
|
||||
import os
|
||||
|
||||
//TODO: need to fix wrong location
|
||||
// TODO: need to fix wrong location
|
||||
const playbook_path = os.dir(@FILE) + '/playbook'
|
||||
const build_path = os.join_path(os.dir(@FILE), '/docusaurus')
|
||||
|
||||
buildpath := '${os.home_dir()}/hero/var/mdbuild/bizmodel'
|
||||
|
||||
mut model := bizmodel.getset("example")!
|
||||
mut model := bizmodel.getset('example')!
|
||||
model.workdir = build_path
|
||||
model.play(mut playbook.new(path: playbook_path)!)!
|
||||
|
||||
@@ -22,16 +22,13 @@ println(model.sheet.export()!)
|
||||
// model.sheet.export(path:"~/Downloads/test.csv")!
|
||||
// model.sheet.export(path:"~/code/github/freeflowuniverse/starlight_template/src/content/test.csv")!
|
||||
|
||||
|
||||
|
||||
|
||||
report := model.new_report(
|
||||
name: 'example_report'
|
||||
name: 'example_report'
|
||||
title: 'Example Business Model'
|
||||
)!
|
||||
|
||||
report.export(
|
||||
path: build_path
|
||||
path: build_path
|
||||
overwrite: true
|
||||
format: .docusaurus
|
||||
format: .docusaurus
|
||||
)!
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
export GROQ_API_KEY="your-groq-api-key-here"
|
||||
@@ -1,64 +0,0 @@
|
||||
# Groq AI Client Example
|
||||
|
||||
This example demonstrates how to use Groq's AI API with the herolib OpenAI client. Groq provides API compatibility with OpenAI's client libraries, allowing you to leverage Groq's fast inference speeds with minimal changes to your existing code.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- V programming language installed
|
||||
- A Groq API key (get one from [Groq's website](https://console.groq.com/keys))
|
||||
|
||||
## Setup
|
||||
|
||||
1. Copy the `.env.example` file to `.env`:
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
2. Edit the `.env` file and replace `your-groq-api-key-here` with your actual Groq API key.
|
||||
|
||||
3. Load the environment variables:
|
||||
|
||||
```bash
|
||||
source .env
|
||||
```
|
||||
|
||||
## Running the Example
|
||||
|
||||
Execute the script with:
|
||||
|
||||
```bash
|
||||
v run groq_client.vsh
|
||||
```
|
||||
|
||||
Or make it executable first:
|
||||
|
||||
```bash
|
||||
chmod +x groq_client.vsh
|
||||
./groq_client.vsh
|
||||
```
|
||||
|
||||
## How It Works
|
||||
|
||||
The example uses the existing OpenAI client from herolib but configures it to use Groq's API endpoint:
|
||||
|
||||
1. It retrieves the Groq API key from the environment variables
|
||||
2. Configures the OpenAI client with the Groq API key
|
||||
3. Overrides the default OpenAI URL with Groq's API URL (`https://api.groq.com/openai/v1`)
|
||||
4. Sends a chat completion request to Groq's API
|
||||
5. Displays the response
|
||||
|
||||
## Supported Models
|
||||
|
||||
Groq supports various models including:
|
||||
|
||||
- llama2-70b-4096
|
||||
- mixtral-8x7b-32768
|
||||
- gemma-7b-it
|
||||
|
||||
For a complete and up-to-date list of supported models, refer to the [Groq API documentation](https://console.groq.com/docs/models).
|
||||
|
||||
## Notes
|
||||
|
||||
- The example uses the `gpt_3_5_turbo` enum from the OpenAI client, but Groq will automatically map this to an appropriate model on their end.
|
||||
- For production use, you may want to explicitly specify one of Groq's supported models.
|
||||
@@ -1,46 +0,0 @@
|
||||
#!/usr/bin/env -S v -n -w -gc none -cc tcc -d use_openssl -enable-globals run
|
||||
|
||||
module main
|
||||
|
||||
import freeflowuniverse.herolib.clients.openai
|
||||
import os
|
||||
|
||||
fn main() {
|
||||
// Get API key from environment variable
|
||||
key := os.getenv('GROQ_API_KEY')
|
||||
if key == '' {
|
||||
println('Error: GROQ_API_KEY environment variable not set')
|
||||
println('Please set it by running: source .env')
|
||||
exit(1)
|
||||
}
|
||||
|
||||
// Get the configured client
|
||||
mut client := openai.OpenAI {
|
||||
name: 'groq'
|
||||
api_key: key
|
||||
server_url: 'https://api.groq.com/openai/v1'
|
||||
}
|
||||
|
||||
// Define the model and message for chat completion
|
||||
// Note: Use a model that Groq supports, like llama2-70b-4096 or mixtral-8x7b-32768
|
||||
model := 'qwen-2.5-coder-32b'
|
||||
|
||||
// Create a chat completion request
|
||||
res := client.chat_completion(model, openai.Messages{
|
||||
messages: [
|
||||
openai.Message{
|
||||
role: .user
|
||||
content: 'What are the key differences between Groq and other AI inference providers?'
|
||||
}
|
||||
]
|
||||
})!
|
||||
|
||||
// Print the response
|
||||
println('\nGroq AI Response:')
|
||||
println('==================')
|
||||
println(res.choices[0].message.content)
|
||||
println('\nUsage Statistics:')
|
||||
println('Prompt tokens: ${res.usage.prompt_tokens}')
|
||||
println('Completion tokens: ${res.usage.completion_tokens}')
|
||||
println('Total tokens: ${res.usage.total_tokens}')
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import json
|
||||
fn main() {
|
||||
// Initialize Jina client
|
||||
mut j := jina.Jina{
|
||||
name: 'test_client'
|
||||
name: 'test_client'
|
||||
secret: os.getenv('JINAKEY')
|
||||
}
|
||||
|
||||
@@ -1,209 +0,0 @@
|
||||
#!/usr/bin/env -S v -n -w -gc none -cc tcc -d use_openssl -enable-globals run
|
||||
|
||||
import freeflowuniverse.herolib.clients.qdrant
|
||||
import os
|
||||
import flag
|
||||
|
||||
mut fp := flag.new_flag_parser(os.args)
|
||||
fp.application('qdrant_example.vsh')
|
||||
fp.version('v0.1.0')
|
||||
fp.description('Example script demonstrating Qdrant client usage')
|
||||
fp.skip_executable()
|
||||
|
||||
help_requested := fp.bool('help', `h`, false, 'Show help message')
|
||||
|
||||
if help_requested {
|
||||
println(fp.usage())
|
||||
exit(0)
|
||||
}
|
||||
|
||||
additional_args := fp.finalize() or {
|
||||
eprintln(err)
|
||||
println(fp.usage())
|
||||
exit(1)
|
||||
}
|
||||
|
||||
// Initialize Qdrant client
|
||||
mut client := qdrant.get(name: 'default') or {
|
||||
// If client doesn't exist, create a new one
|
||||
mut new_client := qdrant.QdrantClient{
|
||||
name: 'default'
|
||||
url: 'http://localhost:6333'
|
||||
}
|
||||
qdrant.set(new_client) or {
|
||||
eprintln('Failed to set Qdrant client: ${err}')
|
||||
exit(1)
|
||||
}
|
||||
new_client
|
||||
}
|
||||
|
||||
println('Connected to Qdrant at ${client.url}')
|
||||
|
||||
// Check if Qdrant is healthy
|
||||
is_healthy := client.health_check() or {
|
||||
eprintln('Failed to check Qdrant health: ${err}')
|
||||
exit(1)
|
||||
}
|
||||
|
||||
if !is_healthy {
|
||||
eprintln('Qdrant is not healthy')
|
||||
exit(1)
|
||||
}
|
||||
|
||||
println('Qdrant is healthy')
|
||||
|
||||
// Get service info
|
||||
service_info := client.get_service_info() or {
|
||||
eprintln('Failed to get service info: ${err}')
|
||||
exit(1)
|
||||
}
|
||||
|
||||
println('Qdrant version: ${service_info.version}')
|
||||
|
||||
// Collection name for our example
|
||||
collection_name := 'example_collection'
|
||||
|
||||
// Check if collection exists and delete it if it does
|
||||
collections := client.list_collections() or {
|
||||
eprintln('Failed to list collections: ${err}')
|
||||
exit(1)
|
||||
}
|
||||
|
||||
if collection_name in collections.result {
|
||||
println('Collection ${collection_name} already exists, deleting it...')
|
||||
client.delete_collection(collection_name: collection_name) or {
|
||||
eprintln('Failed to delete collection: ${err}')
|
||||
exit(1)
|
||||
}
|
||||
println('Collection deleted')
|
||||
}
|
||||
|
||||
// Create a new collection
|
||||
println('Creating collection ${collection_name}...')
|
||||
vectors_config := qdrant.VectorsConfig{
|
||||
size: 4 // Small size for example purposes
|
||||
distance: .cosine
|
||||
}
|
||||
|
||||
client.create_collection(
|
||||
collection_name: collection_name
|
||||
vectors: vectors_config
|
||||
) or {
|
||||
eprintln('Failed to create collection: ${err}')
|
||||
exit(1)
|
||||
}
|
||||
|
||||
println('Collection created')
|
||||
|
||||
// Upsert some points
|
||||
println('Upserting points...')
|
||||
points := [
|
||||
qdrant.PointStruct{
|
||||
id: '1'
|
||||
vector: [f32(0.1), 0.2, 0.3, 0.4]
|
||||
payload: {
|
||||
'color': 'red'
|
||||
'category': 'furniture'
|
||||
'name': 'chair'
|
||||
}
|
||||
},
|
||||
qdrant.PointStruct{
|
||||
id: '2'
|
||||
vector: [f32(0.2), 0.3, 0.4, 0.5]
|
||||
payload: {
|
||||
'color': 'blue'
|
||||
'category': 'electronics'
|
||||
'name': 'laptop'
|
||||
}
|
||||
},
|
||||
qdrant.PointStruct{
|
||||
id: '3'
|
||||
vector: [f32(0.3), 0.4, 0.5, 0.6]
|
||||
payload: {
|
||||
'color': 'green'
|
||||
'category': 'food'
|
||||
'name': 'apple'
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
client.upsert_points(
|
||||
collection_name: collection_name
|
||||
points: points
|
||||
wait: true
|
||||
) or {
|
||||
eprintln('Failed to upsert points: ${err}')
|
||||
exit(1)
|
||||
}
|
||||
|
||||
println('Points upserted')
|
||||
|
||||
// Get collection info to verify points were added
|
||||
collection_info := client.get_collection(collection_name: collection_name) or {
|
||||
eprintln('Failed to get collection info: ${err}')
|
||||
exit(1)
|
||||
}
|
||||
|
||||
println('Collection has ${collection_info.vectors_count} points')
|
||||
|
||||
// Search for points
|
||||
println('Searching for points similar to [0.1, 0.2, 0.3, 0.4]...')
|
||||
search_result := client.search(
|
||||
collection_name: collection_name
|
||||
vector: [f32(0.1), 0.2, 0.3, 0.4]
|
||||
limit: 3
|
||||
) or {
|
||||
eprintln('Failed to search points: ${err}')
|
||||
exit(1)
|
||||
}
|
||||
|
||||
println('Search results:')
|
||||
for i, point in search_result.result {
|
||||
println(' ${i+1}. ID: ${point.id}, Score: ${point.score}')
|
||||
if payload := point.payload {
|
||||
println(' Name: ${payload['name']}')
|
||||
println(' Category: ${payload['category']}')
|
||||
println(' Color: ${payload['color']}')
|
||||
}
|
||||
}
|
||||
|
||||
// Search with filter
|
||||
println('\nSearching for points with category "electronics"...')
|
||||
filter := qdrant.Filter{
|
||||
must: [
|
||||
qdrant.FieldCondition{
|
||||
key: 'category'
|
||||
match: 'electronics'
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
filtered_search := client.search(
|
||||
collection_name: collection_name
|
||||
vector: [f32(0.1), 0.2, 0.3, 0.4]
|
||||
filter: filter
|
||||
limit: 3
|
||||
) or {
|
||||
eprintln('Failed to search with filter: ${err}')
|
||||
exit(1)
|
||||
}
|
||||
|
||||
println('Filtered search results:')
|
||||
for i, point in filtered_search.result {
|
||||
println(' ${i+1}. ID: ${point.id}, Score: ${point.score}')
|
||||
if payload := point.payload {
|
||||
println(' Name: ${payload['name']}')
|
||||
println(' Category: ${payload['category']}')
|
||||
println(' Color: ${payload['color']}')
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up - delete the collection
|
||||
println('\nCleaning up - deleting collection...')
|
||||
client.delete_collection(collection_name: collection_name) or {
|
||||
eprintln('Failed to delete collection: ${err}')
|
||||
exit(1)
|
||||
}
|
||||
|
||||
println('Collection deleted')
|
||||
println('Example completed successfully')
|
||||
@@ -5,44 +5,44 @@ import freeflowuniverse.herolib.core.jobs.model
|
||||
|
||||
// Create a test agent with some sample data
|
||||
mut agent := model.Agent{
|
||||
pubkey: 'ed25519:1234567890abcdef'
|
||||
address: '192.168.1.100'
|
||||
port: 9999
|
||||
pubkey: 'ed25519:1234567890abcdef'
|
||||
address: '192.168.1.100'
|
||||
port: 9999
|
||||
description: 'Test agent for binary encoding'
|
||||
status: model.AgentStatus{
|
||||
guid: 'agent-123'
|
||||
status: model.AgentStatus{
|
||||
guid: 'agent-123'
|
||||
timestamp_first: ourtime.now()
|
||||
timestamp_last: ourtime.now()
|
||||
status: model.AgentState.ok
|
||||
timestamp_last: ourtime.now()
|
||||
status: model.AgentState.ok
|
||||
}
|
||||
services: []
|
||||
signature: 'signature-data-here'
|
||||
services: []
|
||||
signature: 'signature-data-here'
|
||||
}
|
||||
|
||||
// Add a service
|
||||
mut service := model.AgentService{
|
||||
actor: 'vm'
|
||||
actor: 'vm'
|
||||
description: 'Virtual machine management'
|
||||
status: model.AgentServiceState.ok
|
||||
public: true
|
||||
actions: []
|
||||
status: model.AgentServiceState.ok
|
||||
public: true
|
||||
actions: []
|
||||
}
|
||||
|
||||
// Add an action to the service
|
||||
mut action := model.AgentServiceAction{
|
||||
action: 'create'
|
||||
description: 'Create a new virtual machine'
|
||||
status: model.AgentServiceState.ok
|
||||
public: true
|
||||
params: {
|
||||
'name': 'Name of the VM'
|
||||
action: 'create'
|
||||
description: 'Create a new virtual machine'
|
||||
status: model.AgentServiceState.ok
|
||||
public: true
|
||||
params: {
|
||||
'name': 'Name of the VM'
|
||||
'memory': 'Memory in MB'
|
||||
'cpu': 'Number of CPU cores'
|
||||
'cpu': 'Number of CPU cores'
|
||||
}
|
||||
params_example: {
|
||||
'name': 'my-test-vm'
|
||||
'name': 'my-test-vm'
|
||||
'memory': '2048'
|
||||
'cpu': '2'
|
||||
'cpu': '2'
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
module example_actor
|
||||
|
||||
import os
|
||||
import freeflowuniverse.herolib.hero.baobab.stage {IActor, RunParams}
|
||||
import freeflowuniverse.herolib.hero.baobab.stage { IActor, RunParams }
|
||||
import freeflowuniverse.herolib.web.openapi
|
||||
import time
|
||||
|
||||
@@ -10,13 +10,11 @@ const openapi_spec_json = os.read_file(openapi_spec_path) or { panic(err) }
|
||||
const openapi_specification = openapi.json_decode(openapi_spec_json)!
|
||||
|
||||
struct ExampleActor {
|
||||
stage.Actor
|
||||
stage.Actor
|
||||
}
|
||||
|
||||
fn new() !ExampleActor {
|
||||
return ExampleActor{
|
||||
stage.new_actor('example')
|
||||
}
|
||||
return ExampleActor{stage.new_actor('example')}
|
||||
}
|
||||
|
||||
pub fn run() ! {
|
||||
|
||||
@@ -70,74 +70,86 @@ fn (mut actor Actor) listen() ! {
|
||||
|
||||
// Handle method invocations
|
||||
fn (mut actor Actor) handle_method(cmd string, data string) !string {
|
||||
param_anys := json2.raw_decode(data)!.arr()
|
||||
match cmd {
|
||||
'listPets' {
|
||||
pets := if param_anys.len == 0 {
|
||||
actor.data_store.list_pets()
|
||||
} else {
|
||||
params := json.decode(ListPetParams, param_anys[0].str())!
|
||||
actor.data_store.list_pets(params)
|
||||
}
|
||||
return json.encode(pets)
|
||||
}
|
||||
'createPet' {
|
||||
response := if param_anys.len == 0 {
|
||||
return error('at least data expected')
|
||||
} else if param_anys.len == 1 {
|
||||
payload := json.decode(NewPet, param_anys[0].str())!
|
||||
actor.data_store.create_pet(payload)
|
||||
} else {
|
||||
return error('expected 1 param, found too many')
|
||||
}
|
||||
// data := json.decode(NewPet, data) or { return error('Invalid pet data: $err') }
|
||||
// created_pet := actor.data_store.create_pet(pet)
|
||||
return json.encode(response)
|
||||
}
|
||||
'getPet' {
|
||||
response := if param_anys.len == 0 {
|
||||
return error('at least data expected')
|
||||
} else if param_anys.len == 1 {
|
||||
payload := param_anys[0].int()
|
||||
actor.data_store.get_pet(payload)!
|
||||
} else {
|
||||
return error('expected 1 param, found too many')
|
||||
}
|
||||
param_anys := json2.raw_decode(data)!.arr()
|
||||
match cmd {
|
||||
'listPets' {
|
||||
pets := if param_anys.len == 0 {
|
||||
actor.data_store.list_pets()
|
||||
} else {
|
||||
params := json.decode(ListPetParams, param_anys[0].str())!
|
||||
actor.data_store.list_pets(params)
|
||||
}
|
||||
return json.encode(pets)
|
||||
}
|
||||
'createPet' {
|
||||
response := if param_anys.len == 0 {
|
||||
return error('at least data expected')
|
||||
} else if param_anys.len == 1 {
|
||||
payload := json.decode(NewPet, param_anys[0].str())!
|
||||
actor.data_store.create_pet(payload)
|
||||
} else {
|
||||
return error('expected 1 param, found too many')
|
||||
}
|
||||
// data := json.decode(NewPet, data) or { return error('Invalid pet data: $err') }
|
||||
// created_pet := actor.data_store.create_pet(pet)
|
||||
return json.encode(response)
|
||||
}
|
||||
'getPet' {
|
||||
response := if param_anys.len == 0 {
|
||||
return error('at least data expected')
|
||||
} else if param_anys.len == 1 {
|
||||
payload := param_anys[0].int()
|
||||
actor.data_store.get_pet(payload)!
|
||||
} else {
|
||||
return error('expected 1 param, found too many')
|
||||
}
|
||||
|
||||
return json.encode(response)
|
||||
}
|
||||
'deletePet' {
|
||||
params := json.decode(map[string]int, data) or { return error('Invalid params: $err') }
|
||||
actor.data_store.delete_pet(params['petId']) or { return error('Pet not found: $err') }
|
||||
return json.encode({'message': 'Pet deleted'})
|
||||
}
|
||||
'listOrders' {
|
||||
orders := actor.data_store.list_orders()
|
||||
return json.encode(orders)
|
||||
}
|
||||
'getOrder' {
|
||||
params := json.decode(map[string]int, data) or { return error('Invalid params: $err') }
|
||||
order := actor.data_store.get_order(params['orderId']) or {
|
||||
return error('Order not found: $err')
|
||||
}
|
||||
return json.encode(order)
|
||||
}
|
||||
'deleteOrder' {
|
||||
params := json.decode(map[string]int, data) or { return error('Invalid params: $err') }
|
||||
actor.data_store.delete_order(params['orderId']) or {
|
||||
return error('Order not found: $err')
|
||||
}
|
||||
return json.encode({'message': 'Order deleted'})
|
||||
}
|
||||
'createUser' {
|
||||
user := json.decode(NewUser, data) or { return error('Invalid user data: $err') }
|
||||
created_user := actor.data_store.create_user(user)
|
||||
return json.encode(created_user)
|
||||
}
|
||||
else {
|
||||
return error('Unknown method: $cmd')
|
||||
}
|
||||
}
|
||||
return json.encode(response)
|
||||
}
|
||||
'deletePet' {
|
||||
params := json.decode(map[string]int, data) or {
|
||||
return error('Invalid params: ${err}')
|
||||
}
|
||||
actor.data_store.delete_pet(params['petId']) or {
|
||||
return error('Pet not found: ${err}')
|
||||
}
|
||||
return json.encode({
|
||||
'message': 'Pet deleted'
|
||||
})
|
||||
}
|
||||
'listOrders' {
|
||||
orders := actor.data_store.list_orders()
|
||||
return json.encode(orders)
|
||||
}
|
||||
'getOrder' {
|
||||
params := json.decode(map[string]int, data) or {
|
||||
return error('Invalid params: ${err}')
|
||||
}
|
||||
order := actor.data_store.get_order(params['orderId']) or {
|
||||
return error('Order not found: ${err}')
|
||||
}
|
||||
return json.encode(order)
|
||||
}
|
||||
'deleteOrder' {
|
||||
params := json.decode(map[string]int, data) or {
|
||||
return error('Invalid params: ${err}')
|
||||
}
|
||||
actor.data_store.delete_order(params['orderId']) or {
|
||||
return error('Order not found: ${err}')
|
||||
}
|
||||
return json.encode({
|
||||
'message': 'Order deleted'
|
||||
})
|
||||
}
|
||||
'createUser' {
|
||||
user := json.decode(NewUser, data) or { return error('Invalid user data: ${err}') }
|
||||
created_user := actor.data_store.create_user(user)
|
||||
return json.encode(created_user)
|
||||
}
|
||||
else {
|
||||
return error('Unknown method: ${cmd}')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@[params]
|
||||
|
||||
@@ -6,4 +6,4 @@ mut db := qdrant_installer.get()!
|
||||
|
||||
db.install()!
|
||||
db.start()!
|
||||
|
||||
db.destroy()!
|
||||
|
||||
@@ -8,5 +8,5 @@ import freeflowuniverse.herolib.core
|
||||
|
||||
core.interactive_set()! // make sure the sudo works so we can do things even if it requires those rights
|
||||
|
||||
mut i1:=golang.get()!
|
||||
mut i1 := golang.get()!
|
||||
i1.install()!
|
||||
|
||||
@@ -5,6 +5,4 @@ import freeflowuniverse.herolib.installers.lang.python as python_module
|
||||
mut python_installer := python_module.get()!
|
||||
python_installer.install()!
|
||||
|
||||
|
||||
|
||||
// python_installer.destroy()!
|
||||
|
||||
@@ -21,74 +21,64 @@ create_count := fp.int('create', `c`, 5, 'Number of jobs to create')
|
||||
help_requested := fp.bool('help', `h`, false, 'Show help message')
|
||||
|
||||
if help_requested {
|
||||
println(fp.usage())
|
||||
exit(0)
|
||||
println(fp.usage())
|
||||
exit(0)
|
||||
}
|
||||
|
||||
additional_args := fp.finalize() or {
|
||||
eprintln(err)
|
||||
println(fp.usage())
|
||||
exit(1)
|
||||
eprintln(err)
|
||||
println(fp.usage())
|
||||
exit(1)
|
||||
}
|
||||
|
||||
// Create a new HeroRunner instance
|
||||
mut runner := model.new() or {
|
||||
panic('Failed to create HeroRunner: ${err}')
|
||||
}
|
||||
mut runner := model.new() or { panic('Failed to create HeroRunner: ${err}') }
|
||||
|
||||
println('\n---------BEGIN VFS JOBS EXAMPLE')
|
||||
|
||||
// Create some jobs
|
||||
println('\n---------CREATING JOBS')
|
||||
for i in 0..create_count {
|
||||
mut job := runner.jobs.new()
|
||||
job.guid = 'job_${i}_${time.now().unix}'
|
||||
job.actor = 'example_actor'
|
||||
job.action = 'test_action'
|
||||
job.params = {
|
||||
'param1': 'value1'
|
||||
'param2': 'value2'
|
||||
}
|
||||
for i in 0 .. create_count {
|
||||
mut job := runner.jobs.new()
|
||||
job.guid = 'job_${i}_${time.now().unix}'
|
||||
job.actor = 'example_actor'
|
||||
job.action = 'test_action'
|
||||
job.params = {
|
||||
'param1': 'value1'
|
||||
'param2': 'value2'
|
||||
}
|
||||
|
||||
// For demonstration, make some jobs older by adjusting their creation time
|
||||
if i % 2 == 0 {
|
||||
job.status.created.time = time.now().add_days(-(cleanup_days + 1))
|
||||
}
|
||||
// For demonstration, make some jobs older by adjusting their creation time
|
||||
if i % 2 == 0 {
|
||||
job.status.created.time = time.now().add_days(-(cleanup_days + 1))
|
||||
}
|
||||
|
||||
runner.jobs.set(job) or {
|
||||
panic('Failed to set job: ${err}')
|
||||
}
|
||||
println('Created job with GUID: ${job.guid}')
|
||||
runner.jobs.set(job) or { panic('Failed to set job: ${err}') }
|
||||
println('Created job with GUID: ${job.guid}')
|
||||
}
|
||||
|
||||
// List all jobs
|
||||
println('\n---------LISTING ALL JOBS')
|
||||
jobs := runner.jobs.list() or {
|
||||
panic('Failed to list jobs: ${err}')
|
||||
}
|
||||
jobs := runner.jobs.list() or { panic('Failed to list jobs: ${err}') }
|
||||
println('Found ${jobs.len} jobs:')
|
||||
for job in jobs {
|
||||
days_ago := (time.now().unix - job.status.created.time.unix) / (60 * 60 * 24)
|
||||
println('- ${job.guid} (created ${days_ago} days ago)')
|
||||
days_ago := (time.now().unix - job.status.created.time.unix) / (60 * 60 * 24)
|
||||
println('- ${job.guid} (created ${days_ago} days ago)')
|
||||
}
|
||||
|
||||
// Clean up old jobs
|
||||
println('\n---------CLEANING UP OLD JOBS')
|
||||
println('Cleaning up jobs older than ${cleanup_days} days...')
|
||||
deleted_count := runner.cleanup_jobs(cleanup_days) or {
|
||||
panic('Failed to clean up jobs: ${err}')
|
||||
}
|
||||
deleted_count := runner.cleanup_jobs(cleanup_days) or { panic('Failed to clean up jobs: ${err}') }
|
||||
println('Deleted ${deleted_count} old jobs')
|
||||
|
||||
// List remaining jobs
|
||||
println('\n---------LISTING REMAINING JOBS')
|
||||
remaining_jobs := runner.jobs.list() or {
|
||||
panic('Failed to list jobs: ${err}')
|
||||
}
|
||||
remaining_jobs := runner.jobs.list() or { panic('Failed to list jobs: ${err}') }
|
||||
println('Found ${remaining_jobs.len} remaining jobs:')
|
||||
for job in remaining_jobs {
|
||||
days_ago := (time.now().unix - job.status.created.time.unix) / (60 * 60 * 24)
|
||||
println('- ${job.guid} (created ${days_ago} days ago)')
|
||||
days_ago := (time.now().unix - job.status.created.time.unix) / (60 * 60 * 24)
|
||||
println('- ${job.guid} (created ${days_ago} days ago)')
|
||||
}
|
||||
|
||||
println('\n---------END VFS JOBS EXAMPLE')
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
// Calendar Typescript Client Generation Example
|
||||
// This example demonstrates how to generate a typescript client
|
||||
// from a given OpenAPI Specification using the `openapi/codegen` module.
|
||||
|
||||
import os
|
||||
import freeflowuniverse.herolib.schemas.openapi
|
||||
import freeflowuniverse.herolib.schemas.openapi.codegen
|
||||
@@ -15,5 +14,3 @@ const specification = openapi.new(path: '${dir}/meeting_api.json') or {
|
||||
|
||||
// generate typescript client folder and write it in dir
|
||||
codegen.ts_client_folder(specification)!.write(dir, overwrite: true)!
|
||||
|
||||
|
||||
|
||||
20
examples/threefold/tfgrid3deployer/filter.vsh
Executable file
20
examples/threefold/tfgrid3deployer/filter.vsh
Executable file
@@ -0,0 +1,20 @@
|
||||
#!/usr/bin/env -S v -gc none -cc tcc -d use_openssl -enable-globals -cg run
|
||||
|
||||
import freeflowuniverse.herolib.threefold.grid3.deployer
|
||||
|
||||
const gigabyte = u64(1024 * 1024 * 1024)
|
||||
|
||||
// We can use any of the parameters for the corresponding Grid Proxy query
|
||||
// https://gridproxy.grid.tf/swagger/index.html#/GridProxy/get_nodes
|
||||
|
||||
filter := deployer.FilterNodesArgs{
|
||||
size: 5
|
||||
randomize: true
|
||||
free_mru: 8 * gigabyte
|
||||
free_sru: 50 * gigabyte
|
||||
farm_name: 'FreeFarm'
|
||||
status: 'up'
|
||||
}
|
||||
|
||||
nodes := deployer.filter_nodes(filter)!
|
||||
println(nodes)
|
||||
@@ -11,18 +11,18 @@ griddriver.install()!
|
||||
|
||||
v := tfgrid3deployer.get()!
|
||||
println('cred: ${v}')
|
||||
deployment_name := 'herzner_dep'
|
||||
deployment_name := 'hetzner_dep'
|
||||
mut deployment := tfgrid3deployer.new_deployment(deployment_name)!
|
||||
|
||||
// TODO: find a way to filter hetzner nodes
|
||||
deployment.add_machine(
|
||||
name: 'hetzner_vm'
|
||||
cpu: 1
|
||||
memory: 2
|
||||
cpu: 2
|
||||
memory: 5
|
||||
planetary: false
|
||||
public_ip4: true
|
||||
public_ip4: false
|
||||
size: 10 // 10 gig
|
||||
mycelium: tfgrid3deployer.Mycelium{}
|
||||
// mycelium: tfgrid3deployer.Mycelium{}
|
||||
)
|
||||
deployment.deploy()!
|
||||
|
||||
|
||||
@@ -13,8 +13,8 @@ fn main() {
|
||||
// mut deployment := tfgrid3deployer.get_deployment(deployment_name)!
|
||||
deployment.add_machine(
|
||||
name: 'my_vm1'
|
||||
cpu: 1
|
||||
memory: 2
|
||||
cpu: 2
|
||||
memory: 4
|
||||
planetary: false
|
||||
public_ip4: false
|
||||
nodes: [167]
|
||||
@@ -32,10 +32,10 @@ fn main() {
|
||||
deployment.add_webname(name: 'mywebname2', backend: 'http://37.27.132.47:8000')
|
||||
deployment.deploy()!
|
||||
|
||||
deployment.remove_machine('my_vm1')!
|
||||
deployment.remove_webname('mywebname2')!
|
||||
deployment.remove_zdb('my_zdb')!
|
||||
deployment.deploy()!
|
||||
// deployment.remove_machine('my_vm1')!
|
||||
// deployment.remove_webname('mywebname2')!
|
||||
// deployment.remove_zdb('my_zdb')!
|
||||
// deployment.deploy()!
|
||||
|
||||
tfgrid3deployer.delete_deployment(deployment_name)!
|
||||
// tfgrid3deployer.delete_deployment(deployment_name)!
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ fn deploy_vm() ! {
|
||||
memory: 2
|
||||
planetary: false
|
||||
public_ip4: true
|
||||
nodes: [node_id]
|
||||
nodes: [node_id]
|
||||
)
|
||||
deployment.deploy()!
|
||||
println(deployment)
|
||||
@@ -27,13 +27,13 @@ fn delete_vm() ! {
|
||||
}
|
||||
|
||||
fn main() {
|
||||
if os.args.len < 2 {
|
||||
println('Please provide a command: "deploy" or "delete"')
|
||||
return
|
||||
}
|
||||
match os.args[1] {
|
||||
'deploy' { deploy_vm()! }
|
||||
'delete' { delete_vm()! }
|
||||
else { println('Invalid command. Use "deploy" or "delete"') }
|
||||
}
|
||||
if os.args.len < 2 {
|
||||
println('Please provide a command: "deploy" or "delete"')
|
||||
return
|
||||
}
|
||||
match os.args[1] {
|
||||
'deploy' { deploy_vm()! }
|
||||
'delete' { delete_vm()! }
|
||||
else { println('Invalid command. Use "deploy" or "delete"') }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
#!/usr/bin/env -S v -gc none -d use_openssl -enable-globals -cg run
|
||||
#!/usr/bin/env -S v -gc none -cc tcc -d use_openssl -enable-globals -cg run
|
||||
|
||||
//#!/usr/bin/env -S v -gc none -cc tcc -d use_openssl -enable-globals -cg run
|
||||
import freeflowuniverse.herolib.threefold.grid3.gridproxy
|
||||
import freeflowuniverse.herolib.threefold.grid3.deployer
|
||||
import freeflowuniverse.herolib.installers.threefold.griddriver
|
||||
@@ -26,7 +25,7 @@ deployment.add_machine(
|
||||
public_ip4: false
|
||||
size: 10 // 10 gig
|
||||
mycelium: deployer.Mycelium{}
|
||||
nodes: [vm_node]
|
||||
nodes: [vm_node]
|
||||
)
|
||||
deployment.deploy()!
|
||||
|
||||
|
||||
@@ -11,13 +11,14 @@ pub struct VFSDedupeDB {
|
||||
}
|
||||
|
||||
pub fn (mut db VFSDedupeDB) set(args ourdb.OurDBSetArgs) !u32 {
|
||||
return db.store(args.data,
|
||||
dedupestor.Reference{owner: u16(1), id: args.id or {panic('VFS Must provide id')}}
|
||||
)!
|
||||
return db.store(args.data, dedupestor.Reference{
|
||||
owner: u16(1)
|
||||
id: args.id or { panic('VFS Must provide id') }
|
||||
})!
|
||||
}
|
||||
|
||||
pub fn (mut db VFSDedupeDB) delete(id u32) ! {
|
||||
db.DedupeStore.delete(id, dedupestor.Reference{owner: u16(1), id: id})!
|
||||
db.DedupeStore.delete(id, dedupestor.Reference{ owner: u16(1), id: id })!
|
||||
}
|
||||
|
||||
example_data_dir := os.join_path(os.dir(@FILE), 'example_db')
|
||||
@@ -33,35 +34,23 @@ mut db_data := VFSDedupeDB{
|
||||
}
|
||||
|
||||
mut db_metadata := ourdb.new(
|
||||
path: os.join_path(example_data_dir, 'metadata')
|
||||
path: os.join_path(example_data_dir, 'metadata')
|
||||
incremental_mode: false
|
||||
)!
|
||||
|
||||
// Create VFS with separate databases for data and metadata
|
||||
mut vfs := vfs_db.new(mut db_data, mut db_metadata) or {
|
||||
panic('Failed to create VFS: ${err}')
|
||||
}
|
||||
mut vfs := vfs_db.new(mut db_data, mut db_metadata) or { panic('Failed to create VFS: ${err}') }
|
||||
|
||||
println('\n---------BEGIN EXAMPLE')
|
||||
println('---------WRITING FILES')
|
||||
vfs.file_create('/some_file.txt') or {
|
||||
panic('Failed to create file: ${err}')
|
||||
}
|
||||
vfs.file_create('/another_file.txt') or {
|
||||
panic('Failed to create file: ${err}')
|
||||
}
|
||||
vfs.file_create('/some_file.txt') or { panic('Failed to create file: ${err}') }
|
||||
vfs.file_create('/another_file.txt') or { panic('Failed to create file: ${err}') }
|
||||
|
||||
vfs.file_write('/some_file.txt', 'gibberish'.bytes()) or {
|
||||
panic('Failed to write file: ${err}')
|
||||
}
|
||||
vfs.file_write('/another_file.txt', 'abcdefg'.bytes()) or {
|
||||
panic('Failed to write file: ${err}')
|
||||
}
|
||||
vfs.file_write('/some_file.txt', 'gibberish'.bytes()) or { panic('Failed to write file: ${err}') }
|
||||
vfs.file_write('/another_file.txt', 'abcdefg'.bytes()) or { panic('Failed to write file: ${err}') }
|
||||
|
||||
println('\n---------READING FILES')
|
||||
some_file_content := vfs.file_read('/some_file.txt') or {
|
||||
panic('Failed to read file: ${err}')
|
||||
}
|
||||
some_file_content := vfs.file_read('/some_file.txt') or { panic('Failed to read file: ${err}') }
|
||||
println(some_file_content.bytestr())
|
||||
|
||||
another_file_content := vfs.file_read('/another_file.txt') or {
|
||||
@@ -69,19 +58,15 @@ another_file_content := vfs.file_read('/another_file.txt') or {
|
||||
}
|
||||
println(another_file_content.bytestr())
|
||||
|
||||
println("\n---------WRITING DUPLICATE FILE (DB SIZE: ${os.file_size(os.join_path(example_data_dir, 'data/0.db'))})")
|
||||
vfs.file_create('/duplicate.txt') or {
|
||||
panic('Failed to create file: ${err}')
|
||||
}
|
||||
vfs.file_write('/duplicate.txt', 'gibberish'.bytes()) or {
|
||||
panic('Failed to write file: ${err}')
|
||||
}
|
||||
println('\n---------WRITING DUPLICATE FILE (DB SIZE: ${os.file_size(os.join_path(example_data_dir,
|
||||
'data/0.db'))})')
|
||||
vfs.file_create('/duplicate.txt') or { panic('Failed to create file: ${err}') }
|
||||
vfs.file_write('/duplicate.txt', 'gibberish'.bytes()) or { panic('Failed to write file: ${err}') }
|
||||
|
||||
println("\n---------WROTE DUPLICATE FILE (DB SIZE: ${os.file_size(os.join_path(example_data_dir, 'data/0.db'))})")
|
||||
println('\n---------WROTE DUPLICATE FILE (DB SIZE: ${os.file_size(os.join_path(example_data_dir,
|
||||
'data/0.db'))})')
|
||||
println('---------READING FILES')
|
||||
some_file_content3 := vfs.file_read('/some_file.txt') or {
|
||||
panic('Failed to read file: ${err}')
|
||||
}
|
||||
some_file_content3 := vfs.file_read('/some_file.txt') or { panic('Failed to read file: ${err}') }
|
||||
println(some_file_content3.bytestr())
|
||||
|
||||
another_file_content3 := vfs.file_read('/another_file.txt') or {
|
||||
@@ -89,22 +74,21 @@ another_file_content3 := vfs.file_read('/another_file.txt') or {
|
||||
}
|
||||
println(another_file_content3.bytestr())
|
||||
|
||||
duplicate_content := vfs.file_read('/duplicate.txt') or {
|
||||
panic('Failed to read file: ${err}')
|
||||
}
|
||||
duplicate_content := vfs.file_read('/duplicate.txt') or { panic('Failed to read file: ${err}') }
|
||||
println(duplicate_content.bytestr())
|
||||
|
||||
println("\n---------DELETING DUPLICATE FILE (DB SIZE: ${os.file_size(os.join_path(example_data_dir, 'data/0.db'))})")
|
||||
vfs.file_delete('/duplicate.txt') or {
|
||||
panic('Failed to delete file: ${err}')
|
||||
}
|
||||
println('\n---------DELETING DUPLICATE FILE (DB SIZE: ${os.file_size(os.join_path(example_data_dir,
|
||||
'data/0.db'))})')
|
||||
vfs.file_delete('/duplicate.txt') or { panic('Failed to delete file: ${err}') }
|
||||
|
||||
data_path := os.join_path(example_data_dir, 'data/0.db')
|
||||
db_file_path := os.join_path(data_path, '0.db')
|
||||
println("---------READING FILES (DB SIZE: ${if os.exists(db_file_path) { os.file_size(db_file_path) } else { 0 }})")
|
||||
some_file_content2 := vfs.file_read('/some_file.txt') or {
|
||||
panic('Failed to read file: ${err}')
|
||||
}
|
||||
data_path2 := os.join_path(example_data_dir, 'data/0.db')
|
||||
db_file_path := os.join_path(data_path2, '0.db')
|
||||
println('---------READING FILES (DB SIZE: ${if os.exists(db_file_path) {
|
||||
os.file_size(db_file_path)
|
||||
} else {
|
||||
0
|
||||
}})')
|
||||
some_file_content2 := vfs.file_read('/some_file.txt') or { panic('Failed to read file: ${err}') }
|
||||
println(some_file_content2.bytestr())
|
||||
|
||||
another_file_content2 := vfs.file_read('/another_file.txt') or {
|
||||
|
||||
@@ -16,26 +16,24 @@ os.mkdir_all(metadata_dir)!
|
||||
|
||||
// Create separate databases for data and metadata
|
||||
mut db_data := ourdb.new(
|
||||
path: data_dir
|
||||
path: data_dir
|
||||
incremental_mode: false
|
||||
)!
|
||||
|
||||
mut db_metadata := ourdb.new(
|
||||
path: metadata_dir
|
||||
path: metadata_dir
|
||||
incremental_mode: false
|
||||
)!
|
||||
|
||||
// Create VFS with separate databases for data and metadata
|
||||
mut vfs := vfs_db.new_with_separate_dbs(
|
||||
mut db_data,
|
||||
mut db_metadata,
|
||||
data_dir: data_dir,
|
||||
mut vfs := vfs_db.new_with_separate_dbs(mut db_data, mut db_metadata,
|
||||
data_dir: data_dir
|
||||
metadata_dir: metadata_dir
|
||||
)!
|
||||
|
||||
// Create a root directory if it doesn't exist
|
||||
if !vfs.exists('/') {
|
||||
vfs.dir_create('/')!
|
||||
vfs.dir_create('/')!
|
||||
}
|
||||
|
||||
// Create some files and directories
|
||||
@@ -55,13 +53,13 @@ println('Nested file content: ${vfs.file_read('/test_dir/nested_file.txt')!.byte
|
||||
println('Root directory contents:')
|
||||
root_entries := vfs.dir_list('/')!
|
||||
for entry in root_entries {
|
||||
println('- ${entry.get_metadata().name} (${entry.get_metadata().file_type})')
|
||||
println('- ${entry.get_metadata().name} (${entry.get_metadata().file_type})')
|
||||
}
|
||||
|
||||
println('Test directory contents:')
|
||||
test_dir_entries := vfs.dir_list('/test_dir')!
|
||||
for entry in test_dir_entries {
|
||||
println('- ${entry.get_metadata().name} (${entry.get_metadata().file_type})')
|
||||
println('- ${entry.get_metadata().name} (${entry.get_metadata().file_type})')
|
||||
}
|
||||
|
||||
// Create a duplicate file with the same content
|
||||
|
||||
@@ -16,59 +16,43 @@ os.mkdir_all(example_data_dir)!
|
||||
|
||||
// Create separate databases for data and metadata
|
||||
mut db_data := ourdb.new(
|
||||
path: os.join_path(example_data_dir, 'data')
|
||||
path: os.join_path(example_data_dir, 'data')
|
||||
incremental_mode: false
|
||||
)!
|
||||
|
||||
mut db_metadata := ourdb.new(
|
||||
path: os.join_path(example_data_dir, 'metadata')
|
||||
path: os.join_path(example_data_dir, 'metadata')
|
||||
incremental_mode: false
|
||||
)!
|
||||
|
||||
// Create VFS with separate databases for data and metadata
|
||||
mut vfs := vfs_db.new(mut db_data, mut db_metadata) or {
|
||||
panic('Failed to create VFS: ${err}')
|
||||
}
|
||||
mut vfs := vfs_db.new(mut db_data, mut db_metadata) or { panic('Failed to create VFS: ${err}') }
|
||||
|
||||
println('\n---------BEGIN DIRECTORY OPERATIONS EXAMPLE')
|
||||
|
||||
// Create directories with subdirectories
|
||||
println('\n---------CREATING DIRECTORIES')
|
||||
vfs.dir_create('/dir1') or {
|
||||
panic('Failed to create directory: ${err}')
|
||||
}
|
||||
vfs.dir_create('/dir1') or { panic('Failed to create directory: ${err}') }
|
||||
println('Created directory: /dir1')
|
||||
|
||||
vfs.dir_create('/dir1/subdir1') or {
|
||||
panic('Failed to create directory: ${err}')
|
||||
}
|
||||
vfs.dir_create('/dir1/subdir1') or { panic('Failed to create directory: ${err}') }
|
||||
println('Created directory: /dir1/subdir1')
|
||||
|
||||
vfs.dir_create('/dir1/subdir2') or {
|
||||
panic('Failed to create directory: ${err}')
|
||||
}
|
||||
vfs.dir_create('/dir1/subdir2') or { panic('Failed to create directory: ${err}') }
|
||||
println('Created directory: /dir1/subdir2')
|
||||
|
||||
vfs.dir_create('/dir2') or {
|
||||
panic('Failed to create directory: ${err}')
|
||||
}
|
||||
vfs.dir_create('/dir2') or { panic('Failed to create directory: ${err}') }
|
||||
println('Created directory: /dir2')
|
||||
|
||||
vfs.dir_create('/dir2/subdir1') or {
|
||||
panic('Failed to create directory: ${err}')
|
||||
}
|
||||
vfs.dir_create('/dir2/subdir1') or { panic('Failed to create directory: ${err}') }
|
||||
println('Created directory: /dir2/subdir1')
|
||||
|
||||
vfs.dir_create('/dir2/subdir1/subsubdir1') or {
|
||||
panic('Failed to create directory: ${err}')
|
||||
}
|
||||
vfs.dir_create('/dir2/subdir1/subsubdir1') or { panic('Failed to create directory: ${err}') }
|
||||
println('Created directory: /dir2/subdir1/subsubdir1')
|
||||
|
||||
// List directories
|
||||
println('\n---------LISTING ROOT DIRECTORY')
|
||||
root_entries := vfs.dir_list('/') or {
|
||||
panic('Failed to list directory: ${err}')
|
||||
}
|
||||
root_entries := vfs.dir_list('/') or { panic('Failed to list directory: ${err}') }
|
||||
println('Root directory contains:')
|
||||
for entry in root_entries {
|
||||
entry_type := if entry.get_metadata().file_type == .directory { 'directory' } else { 'file' }
|
||||
@@ -76,9 +60,7 @@ for entry in root_entries {
|
||||
}
|
||||
|
||||
println('\n---------LISTING /dir1 DIRECTORY')
|
||||
dir1_entries := vfs.dir_list('/dir1') or {
|
||||
panic('Failed to list directory: ${err}')
|
||||
}
|
||||
dir1_entries := vfs.dir_list('/dir1') or { panic('Failed to list directory: ${err}') }
|
||||
println('/dir1 directory contains:')
|
||||
for entry in dir1_entries {
|
||||
entry_type := if entry.get_metadata().file_type == .directory { 'directory' } else { 'file' }
|
||||
@@ -87,9 +69,7 @@ for entry in dir1_entries {
|
||||
|
||||
// Write a file in a subdirectory
|
||||
println('\n---------WRITING FILE IN SUBDIRECTORY')
|
||||
vfs.file_create('/dir1/subdir1/test_file.txt') or {
|
||||
panic('Failed to create file: ${err}')
|
||||
}
|
||||
vfs.file_create('/dir1/subdir1/test_file.txt') or { panic('Failed to create file: ${err}') }
|
||||
println('Created file: /dir1/subdir1/test_file.txt')
|
||||
|
||||
test_content := 'This is a test file in a subdirectory'
|
||||
@@ -104,13 +84,15 @@ file_content := vfs.file_read('/dir1/subdir1/test_file.txt') or {
|
||||
panic('Failed to read file: ${err}')
|
||||
}
|
||||
println('File content: ${file_content.bytestr()}')
|
||||
println('Content verification: ${if file_content.bytestr() == test_content { 'SUCCESS' } else { 'FAILED' }}')
|
||||
println('Content verification: ${if file_content.bytestr() == test_content {
|
||||
'SUCCESS'
|
||||
} else {
|
||||
'FAILED'
|
||||
}}')
|
||||
|
||||
// List the subdirectory to see the file
|
||||
println('\n---------LISTING /dir1/subdir1 DIRECTORY')
|
||||
subdir1_entries := vfs.dir_list('/dir1/subdir1') or {
|
||||
panic('Failed to list directory: ${err}')
|
||||
}
|
||||
subdir1_entries := vfs.dir_list('/dir1/subdir1') or { panic('Failed to list directory: ${err}') }
|
||||
println('/dir1/subdir1 directory contains:')
|
||||
for entry in subdir1_entries {
|
||||
entry_type := if entry.get_metadata().file_type == .directory { 'directory' } else { 'file' }
|
||||
@@ -119,9 +101,7 @@ for entry in subdir1_entries {
|
||||
|
||||
// Delete the file
|
||||
println('\n---------DELETING FILE')
|
||||
vfs.file_delete('/dir1/subdir1/test_file.txt') or {
|
||||
panic('Failed to delete file: ${err}')
|
||||
}
|
||||
vfs.file_delete('/dir1/subdir1/test_file.txt') or { panic('Failed to delete file: ${err}') }
|
||||
println('Deleted file: /dir1/subdir1/test_file.txt')
|
||||
|
||||
// List the subdirectory again to verify the file is gone
|
||||
@@ -158,7 +138,11 @@ deep_file_content := vfs.file_read('/dir2/subdir1/subsubdir1/deep_file.txt') or
|
||||
panic('Failed to read file: ${err}')
|
||||
}
|
||||
println('File content: ${deep_file_content.bytestr()}')
|
||||
println('Content verification: ${if deep_file_content.bytestr() == deep_content { 'SUCCESS' } else { 'FAILED' }}')
|
||||
println('Content verification: ${if deep_file_content.bytestr() == deep_content {
|
||||
'SUCCESS'
|
||||
} else {
|
||||
'FAILED'
|
||||
}}')
|
||||
|
||||
// Clean up by deleting directories (optional)
|
||||
println('\n---------CLEANING UP')
|
||||
|
||||
1
examples/webdav/.gitignore
vendored
Normal file
1
examples/webdav/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
webdav_vfs
|
||||
@@ -1,69 +0,0 @@
|
||||
#!/usr/bin/env -S v -n -w -gc none -cc tcc -d use_openssl -enable-globals run
|
||||
|
||||
import freeflowuniverse.herolib.vfs.webdav
|
||||
import cli { Command, Flag }
|
||||
import os
|
||||
|
||||
fn main() {
|
||||
mut cmd := Command{
|
||||
name: 'webdav'
|
||||
description: 'Vlang Webdav Server'
|
||||
}
|
||||
|
||||
mut app := Command{
|
||||
name: 'webdav'
|
||||
description: 'Vlang Webdav Server'
|
||||
execute: fn (cmd Command) ! {
|
||||
port := cmd.flags.get_int('port')!
|
||||
directory := cmd.flags.get_string('directory')!
|
||||
user := cmd.flags.get_string('user')!
|
||||
password := cmd.flags.get_string('password')!
|
||||
|
||||
mut server := webdav.new_app(
|
||||
root_dir: directory
|
||||
server_port: port
|
||||
user_db: {
|
||||
user: password
|
||||
}
|
||||
)!
|
||||
|
||||
server.run()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
app.add_flag(Flag{
|
||||
flag: .int
|
||||
name: 'port'
|
||||
abbrev: 'p'
|
||||
description: 'server port'
|
||||
default_value: ['8000']
|
||||
})
|
||||
|
||||
app.add_flag(Flag{
|
||||
flag: .string
|
||||
required: true
|
||||
name: 'directory'
|
||||
abbrev: 'd'
|
||||
description: 'server directory'
|
||||
})
|
||||
|
||||
app.add_flag(Flag{
|
||||
flag: .string
|
||||
required: true
|
||||
name: 'user'
|
||||
abbrev: 'u'
|
||||
description: 'username'
|
||||
})
|
||||
|
||||
app.add_flag(Flag{
|
||||
flag: .string
|
||||
required: true
|
||||
name: 'password'
|
||||
abbrev: 'pw'
|
||||
description: 'user password'
|
||||
})
|
||||
|
||||
app.setup()
|
||||
app.parse(os.args)
|
||||
}
|
||||
@@ -6,14 +6,17 @@ import freeflowuniverse.herolib.data.ourdb
|
||||
import os
|
||||
import log
|
||||
|
||||
const database_path := os.join_path(os.dir(@FILE), 'database')
|
||||
const database_path = os.join_path(os.dir(@FILE), 'database')
|
||||
|
||||
mut metadata_db := ourdb.new(path:os.join_path(database_path, 'metadata'))!
|
||||
mut data_db := ourdb.new(path:os.join_path(database_path, 'data'))!
|
||||
mut metadata_db := ourdb.new(path: os.join_path(database_path, 'metadata'), reset: true)!
|
||||
mut data_db := ourdb.new(path: os.join_path(database_path, 'data', reset: true))!
|
||||
mut vfs := vfs_db.new(mut metadata_db, mut data_db)!
|
||||
mut server := webdav.new_server(vfs: vfs, user_db: {
|
||||
'admin': '123'
|
||||
})!
|
||||
mut server := webdav.new_server(
|
||||
vfs: vfs
|
||||
user_db: {
|
||||
'admin': '123'
|
||||
}
|
||||
)!
|
||||
|
||||
log.set_level(.debug)
|
||||
|
||||
|
||||
8
examples/webtools/docusaurus_example.vsh
Executable file
8
examples/webtools/docusaurus_example.vsh
Executable file
@@ -0,0 +1,8 @@
|
||||
#!/usr/bin/env -S v -n -w -gc none -cg -cc tcc -d use_openssl -enable-globals run
|
||||
|
||||
import freeflowuniverse.herolib.web.docusaurus
|
||||
|
||||
// Create a new docusaurus factory
|
||||
mut docs := docusaurus.new(
|
||||
build_path: '/tmp/docusaurus_build'
|
||||
)!
|
||||
238
examples/webtools/docusaurus_example_complete.vsh
Executable file
238
examples/webtools/docusaurus_example_complete.vsh
Executable file
@@ -0,0 +1,238 @@
|
||||
#!/usr/bin/env -S v -n -w -gc none -cg -cc tcc -d use_openssl -enable-globals run
|
||||
|
||||
import freeflowuniverse.herolib.web.docusaurus
|
||||
import freeflowuniverse.herolib.core.pathlib
|
||||
import freeflowuniverse.herolib.core.playbook
|
||||
import os
|
||||
|
||||
fn main() {
|
||||
println('Starting Docusaurus Example with HeroScript')
|
||||
|
||||
// Define the HeroScript that configures our Docusaurus site
|
||||
hero_script := '
|
||||
!!docusaurus.config
|
||||
name:"my-documentation"
|
||||
title:"My Documentation Site"
|
||||
tagline:"Documentation made simple with V and Docusaurus"
|
||||
url:"https://docs.example.com"
|
||||
url_home:"docs/"
|
||||
base_url:"/"
|
||||
favicon:"img/favicon.png"
|
||||
image:"img/hero.png"
|
||||
copyright:"© 2025 Example Organization"
|
||||
|
||||
!!docusaurus.config_meta
|
||||
description:"Comprehensive documentation for our amazing project"
|
||||
image:"https://docs.example.com/img/social-card.png"
|
||||
title:"My Documentation | Official Docs"
|
||||
|
||||
!!docusaurus.ssh_connection
|
||||
name:"production"
|
||||
host:"example.com"
|
||||
login:"deploy"
|
||||
port:22
|
||||
key_path:"~/.ssh/id_rsa"
|
||||
|
||||
!!docusaurus.build_dest
|
||||
ssh_name:"production"
|
||||
path:"/var/www/docs"
|
||||
|
||||
!!docusaurus.navbar
|
||||
title:"My Project"
|
||||
|
||||
!!docusaurus.navbar_item
|
||||
label:"Documentation"
|
||||
href:"/docs"
|
||||
position:"left"
|
||||
|
||||
!!docusaurus.navbar_item
|
||||
label:"API"
|
||||
href:"/api"
|
||||
position:"left"
|
||||
|
||||
!!docusaurus.navbar_item
|
||||
label:"GitHub"
|
||||
href:"https://github.com/example/repo"
|
||||
position:"right"
|
||||
|
||||
!!docusaurus.footer
|
||||
style:"dark"
|
||||
|
||||
!!docusaurus.footer_item
|
||||
title:"Documentation"
|
||||
label:"Introduction"
|
||||
to:"/docs"
|
||||
|
||||
!!docusaurus.footer_item
|
||||
title:"Documentation"
|
||||
label:"API Reference"
|
||||
to:"/api"
|
||||
|
||||
!!docusaurus.footer_item
|
||||
title:"Community"
|
||||
label:"GitHub"
|
||||
href:"https://github.com/example/repo"
|
||||
|
||||
!!docusaurus.footer_item
|
||||
title:"Community"
|
||||
label:"Discord"
|
||||
href:"https://discord.gg/example"
|
||||
|
||||
!!docusaurus.footer_item
|
||||
title:"More"
|
||||
label:"Blog"
|
||||
href:"https://blog.example.com"
|
||||
|
||||
!!docusaurus.import_source
|
||||
url:"https://github.com/example/external-docs"
|
||||
dest:"external"
|
||||
replace:"PROJECT_NAME:My Project, VERSION:1.0.0"
|
||||
'
|
||||
|
||||
mut docs := docusaurus.new(
|
||||
build_path: os.join_path(os.home_dir(), 'hero/var/docusaurus_demo1')
|
||||
update: true // Update the templates
|
||||
heroscript: hero_script
|
||||
) or {
|
||||
eprintln('Error creating docusaurus factory with inline script: ${err}')
|
||||
exit(1)
|
||||
}
|
||||
|
||||
// Create a site directory if it doesn't exist
|
||||
site_path := os.join_path(os.home_dir(), 'hero/var/docusaurus_demo_src')
|
||||
os.mkdir_all(site_path) or {
|
||||
eprintln('Error creating site directory: ${err}')
|
||||
exit(1)
|
||||
}
|
||||
|
||||
// Get or create a site using the factory
|
||||
println('Creating site...')
|
||||
mut site := docs.get(
|
||||
name: 'my-documentation'
|
||||
path: site_path
|
||||
init: true // Create if it doesn't exist
|
||||
// Note: The site will use the config from the previously processed HeroScript
|
||||
) or {
|
||||
eprintln('Error creating site: ${err}')
|
||||
exit(1)
|
||||
}
|
||||
|
||||
// Generate a sample markdown file for the docs
|
||||
println('Creating sample markdown content...')
|
||||
mut docs_dir := pathlib.get_dir(path: os.join_path(site_path, 'docs'), create: true) or {
|
||||
eprintln('Error creating docs directory: ${err}')
|
||||
exit(1)
|
||||
}
|
||||
|
||||
// Create intro.md file
|
||||
mut intro_file := docs_dir.file_get_new('intro.md') or {
|
||||
eprintln('Error creating intro file: ${err}')
|
||||
exit(1)
|
||||
}
|
||||
|
||||
intro_content := '---
|
||||
title: Introduction
|
||||
slug: /
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# Welcome to My Documentation
|
||||
|
||||
This is a sample documentation site created with Docusaurus and HeroLib V using HeroScript configuration.
|
||||
|
||||
## Features
|
||||
|
||||
- Easy to use
|
||||
- Markdown support
|
||||
- Customizable
|
||||
- Search functionality
|
||||
|
||||
## Getting Started
|
||||
|
||||
Follow these steps to get started:
|
||||
|
||||
1. Installation
|
||||
2. Configuration
|
||||
3. Adding content
|
||||
4. Deployment
|
||||
'
|
||||
intro_file.write(intro_content) or {
|
||||
eprintln('Error writing to intro file: ${err}')
|
||||
exit(1)
|
||||
}
|
||||
|
||||
// Create quick-start.md file
|
||||
mut quickstart_file := docs_dir.file_get_new('quick-start.md') or {
|
||||
eprintln('Error creating quickstart file: ${err}')
|
||||
exit(1)
|
||||
}
|
||||
|
||||
quickstart_content := '---
|
||||
title: Quick Start
|
||||
sidebar_position: 2
|
||||
---
|
||||
|
||||
# Quick Start Guide
|
||||
|
||||
This guide will help you get up and running quickly.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
$ npm install my-project
|
||||
```
|
||||
|
||||
## Basic Usage
|
||||
|
||||
```javascript
|
||||
import { myFunction } from "my-project";
|
||||
|
||||
// Use the function
|
||||
const result = myFunction();
|
||||
console.log(result);
|
||||
```
|
||||
'
|
||||
quickstart_file.write(quickstart_content) or {
|
||||
eprintln('Error writing to quickstart file: ${err}')
|
||||
exit(1)
|
||||
}
|
||||
|
||||
// Generate the site
|
||||
println('Generating site...')
|
||||
site.generate() or {
|
||||
eprintln('Error generating site: ${err}')
|
||||
exit(1)
|
||||
}
|
||||
|
||||
println('Site generated successfully!')
|
||||
|
||||
// Choose which operation to perform:
|
||||
|
||||
// Option 1: Run in development mode
|
||||
// This will start a development server in a screen session
|
||||
println('Starting development server...')
|
||||
site.dev() or {
|
||||
eprintln('Error starting development server: ${err}')
|
||||
exit(1)
|
||||
}
|
||||
|
||||
// Option 2: Build for production (uncomment to use)
|
||||
/*
|
||||
println('Building site for production...')
|
||||
site.build() or {
|
||||
eprintln('Error building site: ${err}')
|
||||
exit(1)
|
||||
}
|
||||
println('Site built successfully!')
|
||||
*/
|
||||
|
||||
// Option 3: Build and publish to the remote server (uncomment to use)
|
||||
/*
|
||||
println('Building and publishing site...')
|
||||
site.build_publish() or {
|
||||
eprintln('Error publishing site: ${err}')
|
||||
exit(1)
|
||||
}
|
||||
println('Site published successfully!')
|
||||
*/
|
||||
}
|
||||
@@ -91,4 +91,3 @@ println('\nFootnotes:')
|
||||
for id, footnote in nav.footnotes() {
|
||||
println(' [^${id}]: ${footnote.content}')
|
||||
}
|
||||
|
||||
|
||||
@@ -7,8 +7,8 @@ import os
|
||||
import markdown
|
||||
import freeflowuniverse.herolib.data.markdownparser2
|
||||
|
||||
path2:="${os.home_dir()}/code/github/freeflowuniverse/herolib/examples/webtools/mdbook_markdown/content/links.md"
|
||||
path1:="${os.home_dir()}/code/github/freeflowuniverse/herolib/examples/webtools/mdbook_markdown/content/test.md"
|
||||
path2 := '${os.home_dir()}/code/github/freeflowuniverse/herolib/examples/webtools/mdbook_markdown/content/links.md'
|
||||
path1 := '${os.home_dir()}/code/github/freeflowuniverse/herolib/examples/webtools/mdbook_markdown/content/test.md'
|
||||
|
||||
text := os.read_file(path1)!
|
||||
|
||||
|
||||
@@ -18,10 +18,9 @@ for project in 'projectinca, legal, why'.split(',').map(it.trim_space()) {
|
||||
)!
|
||||
}
|
||||
|
||||
|
||||
tree.export(
|
||||
destination: '/tmp/mdexport'
|
||||
reset: true
|
||||
//keep_structure: true
|
||||
destination: '/tmp/mdexport'
|
||||
reset: true
|
||||
// keep_structure: true
|
||||
exclude_errors: false
|
||||
)!
|
||||
|
||||
@@ -10,8 +10,8 @@ mut docs := starlight.new(
|
||||
|
||||
// Create a new starlight site
|
||||
mut site := docs.get(
|
||||
url: 'https://git.ourworld.tf/tfgrid/docs_aibox'
|
||||
init:true //init means we put config files if not there
|
||||
url: 'https://git.ourworld.tf/tfgrid/docs_aibox'
|
||||
init: true // init means we put config files if not there
|
||||
)!
|
||||
|
||||
site.dev()!
|
||||
@@ -4,7 +4,7 @@ set -e
|
||||
|
||||
os_name="$(uname -s)"
|
||||
arch_name="$(uname -m)"
|
||||
version='1.0.22'
|
||||
version='1.0.25'
|
||||
|
||||
|
||||
# Base URL for GitHub releases
|
||||
|
||||
132
install_v.sh
132
install_v.sh
@@ -60,6 +60,22 @@ command_exists() {
|
||||
command -v "$1" >/dev/null 2>&1
|
||||
}
|
||||
|
||||
# Function to run commands with sudo if needed
|
||||
function run_sudo() {
|
||||
# Check if we're already root
|
||||
if [ "$(id -u)" -eq 0 ]; then
|
||||
# We are root, run the command directly
|
||||
"$@"
|
||||
# Check if sudo is installed
|
||||
elif command_exists sudo; then
|
||||
# Use sudo to run the command
|
||||
sudo "$@"
|
||||
else
|
||||
# No sudo available, try to run directly
|
||||
"$@"
|
||||
fi
|
||||
}
|
||||
|
||||
export DIR_BASE="$HOME"
|
||||
export DIR_BUILD="/tmp"
|
||||
export DIR_CODE="$DIR_BASE/code"
|
||||
@@ -93,7 +109,7 @@ function package_install {
|
||||
local command_name="$1"
|
||||
if [[ "${OSNAME}" == "ubuntu" ]]; then
|
||||
if is_github_actions; then
|
||||
sudo apt -o Dpkg::Options::="--force-confold" -o Dpkg::Options::="--force-confdef" install $1 -q -y --allow-downgrades --allow-remove-essential
|
||||
run_sudo apt -o Dpkg::Options::="--force-confold" -o Dpkg::Options::="--force-confdef" install $1 -q -y --allow-downgrades --allow-remove-essential
|
||||
else
|
||||
apt -o Dpkg::Options::="--force-confold" -o Dpkg::Options::="--force-confdef" install $1 -q -y --allow-downgrades --allow-remove-essential
|
||||
fi
|
||||
@@ -167,8 +183,8 @@ function os_update {
|
||||
fi
|
||||
export TERM=xterm
|
||||
export DEBIAN_FRONTEND=noninteractive
|
||||
sudo dpkg --configure -a
|
||||
sudo apt update -y
|
||||
run_sudo dpkg --configure -a
|
||||
run_sudo apt update -y
|
||||
if is_github_actions; then
|
||||
echo "** IN GITHUB ACTIONS, DON'T DO UPDATE"
|
||||
else
|
||||
@@ -242,8 +258,11 @@ function hero_lib_get {
|
||||
}
|
||||
|
||||
function install_secp256k1 {
|
||||
|
||||
echo "Installing secp256k1..."
|
||||
if [[ "${OSNAME}" == "darwin"* ]]; then
|
||||
# Attempt installation only if not already found
|
||||
echo "Attempting secp256k1 installation via Homebrew..."
|
||||
brew install secp256k1
|
||||
elif [[ "${OSNAME}" == "ubuntu" ]]; then
|
||||
# Install build dependencies
|
||||
@@ -260,7 +279,7 @@ function install_secp256k1 {
|
||||
./configure
|
||||
make -j 5
|
||||
if is_github_actions; then
|
||||
sudo make install
|
||||
run_sudo make install
|
||||
else
|
||||
make install
|
||||
fi
|
||||
@@ -281,16 +300,16 @@ remove_all() {
|
||||
# Set reset to true to use existing reset functionality
|
||||
RESET=true
|
||||
# Call reset functionality
|
||||
sudo rm -rf ~/code/v
|
||||
sudo rm -rf ~/_code/v
|
||||
sudo rm -rf ~/.config/v-analyzer
|
||||
run_sudo rm -rf ~/code/v
|
||||
run_sudo rm -rf ~/_code/v
|
||||
run_sudo rm -rf ~/.config/v-analyzer
|
||||
if command_exists v; then
|
||||
echo "Removing V from system..."
|
||||
sudo rm -f $(which v)
|
||||
run_sudo rm -f $(which v)
|
||||
fi
|
||||
if command_exists v-analyzer; then
|
||||
echo "Removing v-analyzer from system..."
|
||||
sudo rm -f $(which v-analyzer)
|
||||
run_sudo rm -f $(which v-analyzer)
|
||||
fi
|
||||
|
||||
# Remove v-analyzer path from rc files
|
||||
@@ -317,8 +336,6 @@ remove_all() {
|
||||
# Function to check if a service is running and start it if needed
|
||||
check_and_start_redis() {
|
||||
|
||||
|
||||
|
||||
# Normal service management for non-container environments
|
||||
if [[ "${OSNAME}" == "ubuntu" ]] || [[ "${OSNAME}" == "debian" ]]; then
|
||||
|
||||
@@ -326,12 +343,12 @@ check_and_start_redis() {
|
||||
if is_github_actions; then
|
||||
|
||||
# Import Redis GPG key
|
||||
curl -fsSL https://packages.redis.io/gpg | sudo gpg --dearmor -o /usr/share/keyrings/redis-archive-keyring.gpg
|
||||
curl -fsSL https://packages.redis.io/gpg | run_sudo gpg --dearmor -o /usr/share/keyrings/redis-archive-keyring.gpg
|
||||
# Add Redis repository
|
||||
echo "deb [signed-by=/usr/share/keyrings/redis-archive-keyring.gpg] https://packages.redis.io/deb $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/redis.list
|
||||
echo "deb [signed-by=/usr/share/keyrings/redis-archive-keyring.gpg] https://packages.redis.io/deb $(lsb_release -cs) main" | run_sudo tee /etc/apt/sources.list.d/redis.list
|
||||
# Install Redis
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y redis
|
||||
run_sudo apt-get update
|
||||
run_sudo apt-get install -y redis
|
||||
|
||||
# Start Redis
|
||||
redis-server --daemonize yes
|
||||
@@ -366,7 +383,7 @@ check_and_start_redis() {
|
||||
echo "redis is already running."
|
||||
else
|
||||
echo "redis is not running. Starting it..."
|
||||
sudo systemctl start "redis"
|
||||
run_sudo systemctl start "redis"
|
||||
if systemctl is-active --quiet "redis"; then
|
||||
echo "redis started successfully."
|
||||
else
|
||||
@@ -375,11 +392,29 @@ check_and_start_redis() {
|
||||
fi
|
||||
fi
|
||||
elif [[ "${OSNAME}" == "darwin"* ]]; then
|
||||
if brew services list | grep -q "^redis.*started"; then
|
||||
echo "redis is already running."
|
||||
# Check if we're in GitHub Actions
|
||||
if is_github_actions; then
|
||||
echo "Running in GitHub Actions on macOS. Starting redis directly..."
|
||||
if pgrep redis-server > /dev/null; then
|
||||
echo "redis is already running."
|
||||
else
|
||||
echo "redis is not running. Starting it in the background..."
|
||||
redis-server --daemonize yes
|
||||
if pgrep redis-server > /dev/null; then
|
||||
echo "redis started successfully."
|
||||
else
|
||||
echo "Failed to start redis. Please check logs for details."
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
else
|
||||
echo "redis is not running. Starting it..."
|
||||
brew services start redis
|
||||
# For regular macOS environments, use brew services
|
||||
if brew services list | grep -q "^redis.*started"; then
|
||||
echo "redis is already running."
|
||||
else
|
||||
echo "redis is not running. Starting it..."
|
||||
brew services start redis
|
||||
fi
|
||||
fi
|
||||
elif [[ "${OSNAME}" == "alpine"* ]]; then
|
||||
if rc-service "redis" status | grep -q "running"; then
|
||||
@@ -393,7 +428,7 @@ check_and_start_redis() {
|
||||
echo "redis is already running."
|
||||
else
|
||||
echo "redis is not running. Starting it..."
|
||||
sudo systemctl start "redis"
|
||||
run_sudo systemctl start "redis"
|
||||
fi
|
||||
else
|
||||
echo "Service management for redis is not implemented for platform: $OSNAME"
|
||||
@@ -403,17 +438,48 @@ check_and_start_redis() {
|
||||
|
||||
v-install() {
|
||||
|
||||
# Check if v is already installed and in PATH
|
||||
if command_exists v; then
|
||||
echo "V is already installed and in PATH."
|
||||
# Optionally, verify the installation location or version if needed
|
||||
# For now, just exit the function assuming it's okay
|
||||
return 0
|
||||
fi
|
||||
|
||||
|
||||
# Only clone and install if directory doesn't exist
|
||||
if [ ! -d ~/code/v ]; then
|
||||
echo "Installing V..."
|
||||
# Note: The original check was for ~/code/v, but the installation happens in ~/_code/v.
|
||||
if [ ! -d ~/_code/v ]; then
|
||||
echo "Cloning V..."
|
||||
mkdir -p ~/_code
|
||||
cd ~/_code
|
||||
git clone --depth=1 https://github.com/vlang/v
|
||||
cd v
|
||||
make
|
||||
sudo ./v symlink
|
||||
if ! git clone --depth=1 https://github.com/vlang/v; then
|
||||
echo "❌ Failed to clone V. Cleaning up..."
|
||||
rm -rf "$V_DIR"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
|
||||
# Only clone and install if directory doesn't exist
|
||||
# Note: The original check was for ~/code/v, but the installation happens in ~/_code/v.
|
||||
# Adjusting the check to the actual installation directory.
|
||||
echo "Building V..."
|
||||
cd ~/_code/v
|
||||
make
|
||||
# Verify the build produced the executable
|
||||
if [ ! -x ~/_code/v/v ]; then
|
||||
echo "Error: V build failed, executable ~/_code/v/v not found or not executable."
|
||||
exit 1
|
||||
fi
|
||||
# Check if the built executable can report its version
|
||||
if ! ~/_code/v/v -version > /dev/null 2>&1; then
|
||||
echo "Error: Built V executable (~/_code/v/v) failed to report version."
|
||||
exit 1
|
||||
fi
|
||||
echo "V built successfully. Creating symlink..."
|
||||
run_sudo ./v symlink
|
||||
|
||||
# Verify v is in path
|
||||
if ! command_exists v; then
|
||||
echo "Error: V installation failed or not in PATH"
|
||||
@@ -428,9 +494,12 @@ v-install() {
|
||||
|
||||
v-analyzer() {
|
||||
|
||||
set -ex
|
||||
|
||||
# Install v-analyzer if requested
|
||||
if [ "$INSTALL_ANALYZER" = true ]; then
|
||||
echo "Installing v-analyzer..."
|
||||
cd /tmp
|
||||
v download -RD https://raw.githubusercontent.com/vlang/v-analyzer/main/install.vsh
|
||||
|
||||
# Check if v-analyzer bin directory exists
|
||||
@@ -499,10 +568,7 @@ if [ "$RESET" = true ] || ! command_exists v; then
|
||||
|
||||
v-install
|
||||
|
||||
# Only install v-analyzer if not in GitHub Actions environment
|
||||
if ! is_github_actions; then
|
||||
v-analyzer
|
||||
fi
|
||||
|
||||
|
||||
fi
|
||||
|
||||
@@ -516,6 +582,10 @@ fi
|
||||
|
||||
|
||||
if [ "$INSTALL_ANALYZER" = true ]; then
|
||||
# Only install v-analyzer if not in GitHub Actions environment
|
||||
if ! is_github_actions; then
|
||||
v-analyzer
|
||||
fi
|
||||
echo "Run 'source ~/.bashrc' or 'source ~/.zshrc' to update PATH for v-analyzer"
|
||||
fi
|
||||
|
||||
|
||||
BIN
jina.so.dylib
BIN
jina.so.dylib
Binary file not shown.
123
lib/ai/escalayer/README.md
Normal file
123
lib/ai/escalayer/README.md
Normal file
@@ -0,0 +1,123 @@
|
||||
# Escalayer
|
||||
|
||||
Escalayer is a module for executing AI tasks with automatic escalation to more powerful models when needed. It provides a framework for creating complex AI workflows by breaking them down into sequential unit tasks.
|
||||
|
||||
## Overview
|
||||
|
||||
Escalayer allows you to:
|
||||
|
||||
1. Create complex AI tasks composed of multiple sequential unit tasks
|
||||
2. Execute each unit task with a cheap AI model first
|
||||
3. Automatically retry with a more powerful model if the task fails
|
||||
4. Process and validate AI responses with custom callback functions
|
||||
|
||||
## Architecture
|
||||
|
||||
The module is organized into the following components:
|
||||
|
||||
- **Task**: Represents a complete AI task composed of multiple sequential unit tasks
|
||||
- **UnitTask**: Represents a single step in the task with prompt generation and response processing
|
||||
- **ModelConfig**: Defines the configuration for an AI model
|
||||
- **OpenRouter Integration**: Uses OpenRouter to access a wide range of AI models
|
||||
|
||||
## Usage
|
||||
|
||||
### Basic Example
|
||||
|
||||
```v
|
||||
import freeflowuniverse.herolib.ai.mcp.aitools.escalayer
|
||||
|
||||
fn main() {
|
||||
// Create a new task
|
||||
mut task := escalayer.new_task(
|
||||
name: 'rhai_wrapper_creator'
|
||||
description: 'Create Rhai wrappers for Rust functions'
|
||||
)
|
||||
|
||||
// Define the unit tasks
|
||||
task.new_unit_task(
|
||||
name: 'separate_functions'
|
||||
prompt_function: separate_functions
|
||||
callback_function: process_functions
|
||||
)
|
||||
|
||||
// Initiate the task
|
||||
result := task.initiate('path/to/rust/file.rs') or {
|
||||
println('Task failed: ${err}')
|
||||
return
|
||||
}
|
||||
|
||||
println('Task completed successfully')
|
||||
println(result)
|
||||
}
|
||||
|
||||
// Define the prompt function
|
||||
fn separate_functions(input string) string {
|
||||
return 'Read rust file and separate it into functions ${input}'
|
||||
}
|
||||
|
||||
// Define the callback function
|
||||
fn process_functions(response string)! string {
|
||||
// Process the AI response
|
||||
// Return error if processing fails
|
||||
if response.contains('error') {
|
||||
return error('Failed to process functions: Invalid response format')
|
||||
}
|
||||
return response
|
||||
}
|
||||
```
|
||||
|
||||
### Advanced Configuration
|
||||
|
||||
You can configure each unit task with different models, retry counts, and other parameters:
|
||||
|
||||
```v
|
||||
// Configure with custom parameters
|
||||
task.new_unit_task(
|
||||
name: 'create_wrappers'
|
||||
prompt_function: create_wrappers
|
||||
callback_function: process_wrappers
|
||||
retry_count: 2
|
||||
base_model: escalayer.ModelConfig{
|
||||
name: 'claude-3-haiku-20240307'
|
||||
provider: 'anthropic'
|
||||
temperature: 0.5
|
||||
max_tokens: 4000
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
## How It Works
|
||||
|
||||
1. When you call `task.initiate(input)`, the first unit task is executed with its prompt function.
|
||||
2. The prompt is sent to the base AI model.
|
||||
3. The response is processed by the callback function.
|
||||
4. If the callback returns an error, the task is retried with the same model.
|
||||
5. After a specified number of retries, the task escalates to a more powerful model.
|
||||
6. Once a unit task succeeds, its result is passed as input to the next unit task.
|
||||
7. This process continues until all unit tasks are completed.
|
||||
|
||||
## Environment Setup
|
||||
|
||||
Escalayer uses OpenRouter for AI model access. Set the following environment variable:
|
||||
|
||||
```
|
||||
OPENROUTER_API_KEY=your_api_key_here
|
||||
```
|
||||
|
||||
You can get an API key from [OpenRouter](https://openrouter.ai/).
|
||||
|
||||
## Original Requirements
|
||||
|
||||
This module was designed based on the following requirements:
|
||||
|
||||
- Create a system for executing AI tasks with a retry mechanism
|
||||
- Escalate to more powerful models if cheaper models fail
|
||||
- Use OpenAI client over OpenRouter for AI calls
|
||||
- Break down complex tasks into sequential unit tasks
|
||||
- Each unit task has a function that generates a prompt and a callback that processes the response
|
||||
- Retry if the callback returns an error, with the error message prepended to the input string
|
||||
|
||||
For a detailed architecture overview, see [escalayer_architecture.md](./escalayer_architecture.md).
|
||||
|
||||
For a complete example, see [example.v](../servers/rhai).
|
||||
40
lib/ai/escalayer/escalayer.v
Normal file
40
lib/ai/escalayer/escalayer.v
Normal file
@@ -0,0 +1,40 @@
|
||||
module escalayer
|
||||
|
||||
import freeflowuniverse.herolib.clients.openai
|
||||
|
||||
// TaskParams defines the parameters for creating a new task
|
||||
@[params]
|
||||
pub struct TaskParams {
|
||||
pub:
|
||||
name string
|
||||
description string
|
||||
}
|
||||
|
||||
// Create a new task
|
||||
pub fn new_task(params TaskParams) &Task {
|
||||
return &Task{
|
||||
name: params.name
|
||||
description: params.description
|
||||
unit_tasks: []
|
||||
current_result: ''
|
||||
}
|
||||
}
|
||||
|
||||
// Default model configurations
|
||||
pub fn default_base_model() ModelConfig {
|
||||
return ModelConfig{
|
||||
name: 'qwen2.5-7b-instruct'
|
||||
provider: 'openai'
|
||||
temperature: 0.7
|
||||
max_tokens: 2000
|
||||
}
|
||||
}
|
||||
|
||||
pub fn default_retry_model() ModelConfig {
|
||||
return ModelConfig{
|
||||
name: 'gpt-4'
|
||||
provider: 'openai'
|
||||
temperature: 0.7
|
||||
max_tokens: 4000
|
||||
}
|
||||
}
|
||||
342
lib/ai/escalayer/escalayer_architecture.md
Normal file
342
lib/ai/escalayer/escalayer_architecture.md
Normal file
@@ -0,0 +1,342 @@
|
||||
# Escalayer Architecture
|
||||
|
||||
This document outlines the architecture for the Escalayer module, which provides a framework for executing AI tasks with automatic escalation to more powerful models when needed.
|
||||
|
||||
## 1. Module Structure
|
||||
|
||||
```
|
||||
lib/mcp/aitools/escalayer/
|
||||
├── escalayer.v # Main module file with public API
|
||||
├── task.v # Task implementation
|
||||
├── unit_task.v # Unit task implementation
|
||||
├── models.v # Model definitions and configurations
|
||||
├── openrouter.v # OpenRouter API client
|
||||
└── README.md # Documentation
|
||||
```
|
||||
|
||||
## 2. Core Components
|
||||
|
||||
### 2.1 Data Structures
|
||||
|
||||
```mermaid
|
||||
classDiagram
|
||||
class Task {
|
||||
+string name
|
||||
+string description
|
||||
+[]UnitTask unit_tasks
|
||||
+string current_result
|
||||
+new_unit_task(params UnitTaskParams) UnitTask
|
||||
+initiate(input string)! string
|
||||
}
|
||||
|
||||
class UnitTask {
|
||||
+string name
|
||||
+Function prompt_function
|
||||
+Function callback_function
|
||||
+ModelConfig base_model
|
||||
+ModelConfig retry_model
|
||||
+int retry_count
|
||||
+execute(input string)! string
|
||||
}
|
||||
|
||||
class ModelConfig {
|
||||
+string name
|
||||
+string provider
|
||||
+float temperature
|
||||
+int max_tokens
|
||||
}
|
||||
|
||||
Task "1" *-- "many" UnitTask : contains
|
||||
UnitTask "1" *-- "1" ModelConfig : base_model
|
||||
UnitTask "1" *-- "1" ModelConfig : retry_model
|
||||
```
|
||||
|
||||
### 2.2 Component Descriptions
|
||||
|
||||
#### Task
|
||||
- Represents a complete AI task composed of multiple sequential unit tasks
|
||||
- Manages the flow of data between unit tasks
|
||||
- Tracks overall task progress and results
|
||||
|
||||
#### UnitTask
|
||||
- Represents a single step in the task
|
||||
- Contains a prompt function that generates the AI prompt
|
||||
- Contains a callback function that processes the AI response
|
||||
- Manages retries and model escalation
|
||||
|
||||
#### ModelConfig
|
||||
- Defines the configuration for an AI model
|
||||
- Includes model name, provider, and parameters like temperature and max tokens
|
||||
|
||||
#### OpenRouter Client
|
||||
- Handles communication with the OpenRouter API
|
||||
- Sends prompts to AI models and receives responses
|
||||
|
||||
## 3. Implementation Details
|
||||
|
||||
### 3.1 escalayer.v (Main Module)
|
||||
|
||||
```v
|
||||
module escalayer
|
||||
|
||||
import freeflowuniverse.herolib.clients.openai
|
||||
|
||||
// TaskParams defines the parameters for creating a new task
|
||||
@[params]
|
||||
pub struct TaskParams {
|
||||
pub:
|
||||
name string
|
||||
description string
|
||||
}
|
||||
|
||||
// Create a new task
|
||||
pub fn new_task(params TaskParams) &Task {
|
||||
return &Task{
|
||||
name: params.name
|
||||
description: params.description
|
||||
unit_tasks: []
|
||||
current_result: ''
|
||||
}
|
||||
}
|
||||
|
||||
// Default model configurations
|
||||
pub fn default_base_model() ModelConfig {
|
||||
return ModelConfig{
|
||||
name: 'gpt-3.5-turbo'
|
||||
provider: 'openai'
|
||||
temperature: 0.7
|
||||
max_tokens: 20000
|
||||
}
|
||||
}
|
||||
|
||||
pub fn default_retry_model() ModelConfig {
|
||||
return ModelConfig{
|
||||
name: 'gpt-4'
|
||||
provider: 'openai'
|
||||
temperature: 0.7
|
||||
max_tokens: 40000
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 3.2 task.v
|
||||
|
||||
```v
|
||||
module escalayer
|
||||
|
||||
// Task represents a complete AI task composed of multiple sequential unit tasks
|
||||
pub struct Task {
|
||||
pub mut:
|
||||
name string
|
||||
description string
|
||||
unit_tasks []UnitTask
|
||||
current_result string
|
||||
}
|
||||
|
||||
// UnitTaskParams defines the parameters for creating a new unit task
|
||||
struct UnitTaskParams {
|
||||
name string
|
||||
prompt_function fn(string) string
|
||||
callback_function fn(string)! string
|
||||
base_model ?ModelConfig
|
||||
retry_model ?ModelConfig
|
||||
retry_count ?int
|
||||
}
|
||||
|
||||
// Add a new unit task to the task
|
||||
pub fn (mut t Task) new_unit_task(params UnitTaskParams) &UnitTask {
|
||||
}
|
||||
|
||||
// Initiate the task execution
|
||||
pub fn (mut t Task) initiate(input string)! string {
|
||||
|
||||
```
|
||||
|
||||
### 3.3 unit_task.v
|
||||
|
||||
```v
|
||||
module escalayer
|
||||
|
||||
import freeflowuniverse.herolib.clients.openai
|
||||
|
||||
// UnitTask represents a single step in the task
|
||||
pub struct UnitTask {
|
||||
pub mut:
|
||||
name string
|
||||
prompt_function fn(string) string
|
||||
callback_function fn(string)! string
|
||||
base_model ModelConfig
|
||||
retry_model ModelConfig
|
||||
retry_count int
|
||||
}
|
||||
|
||||
// Execute the unit task
|
||||
pub fn (mut ut UnitTask) execute(input string)! string {
|
||||
}
|
||||
```
|
||||
|
||||
### 3.4 models.v
|
||||
|
||||
```v
|
||||
module escalayer
|
||||
|
||||
// ModelConfig defines the configuration for an AI model
|
||||
pub struct ModelConfig {
|
||||
pub mut:
|
||||
name string
|
||||
provider string
|
||||
temperature f32
|
||||
max_tokens int
|
||||
}
|
||||
|
||||
// Call an AI model using OpenRouter
|
||||
fn call_ai_model(prompt string, model ModelConfig)! string {
|
||||
// Get OpenAI client (configured for OpenRouter)
|
||||
mut client := get_openrouter_client()!
|
||||
|
||||
// Create the message for the AI
|
||||
mut m := openai.Messages{
|
||||
messages: [
|
||||
openai.Message{
|
||||
role: .system
|
||||
content: 'You are a helpful assistant.'
|
||||
},
|
||||
openai.Message{
|
||||
role: .user
|
||||
content: prompt
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
// Call the AI model
|
||||
res := client.chat_completion(
|
||||
msgs: m,
|
||||
model: model.name,
|
||||
temperature: model.temperature,
|
||||
max_completion_tokens: model.max_tokens
|
||||
)!
|
||||
|
||||
// Extract the response content
|
||||
if res.choices.len > 0 {
|
||||
return res.choices[0].message.content
|
||||
}
|
||||
|
||||
return error('No response from AI model')
|
||||
}
|
||||
```
|
||||
|
||||
### 3.5 openrouter.v
|
||||
|
||||
```v
|
||||
module escalayer
|
||||
|
||||
import freeflowuniverse.herolib.clients.openai
|
||||
import os
|
||||
|
||||
// Get an OpenAI client configured for OpenRouter
|
||||
fn get_openrouter_client()! &openai.OpenAI {
|
||||
// Get API key from environment variable
|
||||
api_key := os.getenv('OPENROUTER_API_KEY')
|
||||
if api_key == '' {
|
||||
return error('OPENROUTER_API_KEY environment variable not set')
|
||||
}
|
||||
|
||||
// Create OpenAI client with OpenRouter base URL
|
||||
mut client := openai.new(
|
||||
api_key: api_key,
|
||||
base_url: 'https://openrouter.ai/api/v1'
|
||||
)!
|
||||
|
||||
return client
|
||||
}
|
||||
```
|
||||
|
||||
## 4. Usage Example
|
||||
|
||||
```v
|
||||
import freeflowuniverse.herolib.ai.mcp.aitools.escalayer
|
||||
|
||||
fn main() {
|
||||
// Create a new task
|
||||
mut task := escalayer.new_task(
|
||||
name: 'rhai_wrapper_creator'
|
||||
description: 'Create Rhai wrappers for Rust functions'
|
||||
)
|
||||
|
||||
// Define the unit tasks
|
||||
task.new_unit_task(
|
||||
name: 'separate_functions'
|
||||
prompt_function: separate_functions
|
||||
callback_function: process_functions
|
||||
)
|
||||
|
||||
task.new_unit_task(
|
||||
name: 'create_wrappers'
|
||||
prompt_function: create_wrappers
|
||||
callback_function: process_wrappers
|
||||
retry_count: 2
|
||||
)
|
||||
|
||||
task.new_unit_task(
|
||||
name: 'create_tests'
|
||||
prompt_function: create_tests
|
||||
callback_function: process_tests
|
||||
base_model: escalayer.ModelConfig{
|
||||
name: 'claude-3-haiku-20240307'
|
||||
provider: 'anthropic'
|
||||
temperature: 0.5
|
||||
max_tokens: 4000
|
||||
}
|
||||
)
|
||||
|
||||
// Initiate the task
|
||||
result := task.initiate('path/to/rust/file.rs') or {
|
||||
println('Task failed: ${err}')
|
||||
return
|
||||
}
|
||||
|
||||
println('Task completed successfully')
|
||||
println(result)
|
||||
}
|
||||
|
||||
// Define the prompt functions
|
||||
fn separate_functions(input string) string {
|
||||
return 'Read rust file and separate it into functions ${input}'
|
||||
}
|
||||
|
||||
fn create_wrappers(input string) string {
|
||||
return 'Create rhai wrappers for rust functions ${input}'
|
||||
}
|
||||
|
||||
fn create_tests(input string) string {
|
||||
return 'Create tests for rhai wrappers ${input}'
|
||||
}
|
||||
|
||||
// Define the callback functions
|
||||
fn process_functions(response string)! string {
|
||||
// Process the AI response
|
||||
// Return error if processing fails
|
||||
if response.contains('error') {
|
||||
return error('Failed to process functions: Invalid response format')
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
fn process_wrappers(response string)! string {
|
||||
// Process the AI response
|
||||
// Return error if processing fails
|
||||
if !response.contains('fn') {
|
||||
return error('Failed to process wrappers: No functions found')
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
fn process_tests(response string)! string {
|
||||
// Process the AI response
|
||||
// Return error if processing fails
|
||||
if !response.contains('test') {
|
||||
return error('Failed to process tests: No tests found')
|
||||
}
|
||||
return response
|
||||
}
|
||||
```
|
||||
62
lib/ai/escalayer/models.v
Normal file
62
lib/ai/escalayer/models.v
Normal file
@@ -0,0 +1,62 @@
|
||||
module escalayer
|
||||
|
||||
import freeflowuniverse.herolib.clients.openai
|
||||
|
||||
// ModelConfig defines the configuration for an AI model
|
||||
pub struct ModelConfig {
|
||||
pub mut:
|
||||
name string
|
||||
provider string
|
||||
temperature f32
|
||||
max_tokens int
|
||||
}
|
||||
|
||||
// Create model configs
|
||||
const claude_3_sonnet = ModelConfig{
|
||||
name: 'anthropic/claude-3.7-sonnet'
|
||||
provider: 'anthropic'
|
||||
temperature: 0.7
|
||||
max_tokens: 25000
|
||||
}
|
||||
|
||||
const gpt4 = ModelConfig{
|
||||
name: 'gpt-4'
|
||||
provider: 'openai'
|
||||
temperature: 0.7
|
||||
max_tokens: 25000
|
||||
}
|
||||
|
||||
// Call an AI model using OpenRouter
|
||||
fn call_ai_model(prompt string, model ModelConfig) !string {
|
||||
// Get OpenAI client (configured for OpenRouter)
|
||||
mut client := get_openrouter_client()!
|
||||
|
||||
// Create the message for the AI
|
||||
mut m := openai.Messages{
|
||||
messages: [
|
||||
openai.Message{
|
||||
role: .system
|
||||
content: 'You are a helpful assistant.'
|
||||
},
|
||||
openai.Message{
|
||||
role: .user
|
||||
content: prompt
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
// Call the AI model
|
||||
res := client.chat_completion(
|
||||
msgs: m
|
||||
model: model.name
|
||||
temperature: model.temperature
|
||||
max_completion_tokens: model.max_tokens
|
||||
)!
|
||||
|
||||
// Extract the response content
|
||||
if res.choices.len > 0 {
|
||||
return res.choices[0].message.content
|
||||
}
|
||||
|
||||
return error('No response from AI model')
|
||||
}
|
||||
22
lib/ai/escalayer/openrouter.v
Normal file
22
lib/ai/escalayer/openrouter.v
Normal file
@@ -0,0 +1,22 @@
|
||||
module escalayer
|
||||
|
||||
import freeflowuniverse.herolib.clients.openai
|
||||
import freeflowuniverse.herolib.osal
|
||||
import os
|
||||
|
||||
// Get an OpenAI client configured for OpenRouter
|
||||
fn get_openrouter_client() !&openai.OpenAI {
|
||||
osal.env_set(key: 'OPENROUTER_API_KEY', value: '')
|
||||
// Get API key from environment variable
|
||||
api_key := os.getenv('OPENROUTER_API_KEY')
|
||||
if api_key == '' {
|
||||
return error('OPENROUTER_API_KEY environment variable not set')
|
||||
}
|
||||
|
||||
// Create OpenAI client with OpenRouter base URL
|
||||
mut client := openai.get(
|
||||
name: 'openrouter'
|
||||
)!
|
||||
|
||||
return client
|
||||
}
|
||||
65
lib/ai/escalayer/task.v
Normal file
65
lib/ai/escalayer/task.v
Normal file
@@ -0,0 +1,65 @@
|
||||
module escalayer
|
||||
|
||||
import log
|
||||
|
||||
// Task represents a complete AI task composed of multiple sequential unit tasks
|
||||
pub struct Task {
|
||||
pub mut:
|
||||
name string
|
||||
description string
|
||||
unit_tasks []UnitTask
|
||||
current_result string
|
||||
}
|
||||
|
||||
// UnitTaskParams defines the parameters for creating a new unit task
|
||||
@[params]
|
||||
pub struct UnitTaskParams {
|
||||
pub:
|
||||
name string
|
||||
prompt_function fn (string) string
|
||||
callback_function fn (string) !string
|
||||
base_model ?ModelConfig
|
||||
retry_model ?ModelConfig
|
||||
retry_count ?int
|
||||
}
|
||||
|
||||
// Add a new unit task to the task
|
||||
pub fn (mut t Task) new_unit_task(params UnitTaskParams) &UnitTask {
|
||||
mut unit_task := UnitTask{
|
||||
name: params.name
|
||||
prompt_function: params.prompt_function
|
||||
callback_function: params.callback_function
|
||||
base_model: if base_model := params.base_model {
|
||||
base_model
|
||||
} else {
|
||||
default_base_model()
|
||||
}
|
||||
retry_model: if retry_model := params.retry_model {
|
||||
retry_model
|
||||
} else {
|
||||
default_retry_model()
|
||||
}
|
||||
retry_count: if retry_count := params.retry_count { retry_count } else { 3 }
|
||||
}
|
||||
|
||||
t.unit_tasks << unit_task
|
||||
return &t.unit_tasks[t.unit_tasks.len - 1]
|
||||
}
|
||||
|
||||
// Initiate the task execution
|
||||
pub fn (mut t Task) initiate(input string) !string {
|
||||
mut current_input := input
|
||||
|
||||
for i, mut unit_task in t.unit_tasks {
|
||||
log.error('Executing unit task ${i + 1}/${t.unit_tasks.len}: ${unit_task.name}')
|
||||
|
||||
// Execute the unit task with the current input
|
||||
result := unit_task.execute(current_input)!
|
||||
|
||||
// Update the current input for the next unit task
|
||||
current_input = result
|
||||
t.current_result = result
|
||||
}
|
||||
|
||||
return t.current_result
|
||||
}
|
||||
71
lib/ai/escalayer/unit_task.v
Normal file
71
lib/ai/escalayer/unit_task.v
Normal file
@@ -0,0 +1,71 @@
|
||||
module escalayer
|
||||
|
||||
import log
|
||||
import freeflowuniverse.herolib.clients.openai
|
||||
|
||||
// UnitTask represents a single step in the task
|
||||
pub struct UnitTask {
|
||||
pub mut:
|
||||
name string
|
||||
prompt_function fn (string) string
|
||||
callback_function fn (string) !string
|
||||
base_model ModelConfig
|
||||
retry_model ModelConfig
|
||||
retry_count int
|
||||
}
|
||||
|
||||
// Execute the unit task
|
||||
pub fn (mut ut UnitTask) execute(input string) !string {
|
||||
// Generate the prompt using the prompt function
|
||||
prompt := ut.prompt_function(input)
|
||||
|
||||
// Try with the base model first
|
||||
mut current_model := ut.base_model
|
||||
mut attempts := 0
|
||||
mut max_attempts := ut.retry_count + 1 // +1 for the initial attempt
|
||||
mut absolute_max_attempts := 1 // Hard limit on total attempts
|
||||
mut last_error := ''
|
||||
|
||||
for attempts < max_attempts && attempts < absolute_max_attempts {
|
||||
attempts++
|
||||
|
||||
// If we've exhausted retries with the base model, switch to the retry model
|
||||
if attempts > ut.retry_count {
|
||||
log.error('Escalating to more powerful model: ${ut.retry_model.name}')
|
||||
current_model = ut.retry_model
|
||||
// Calculate remaining attempts but don't exceed absolute max
|
||||
max_attempts = attempts + ut.retry_count
|
||||
if max_attempts > absolute_max_attempts {
|
||||
max_attempts = absolute_max_attempts
|
||||
}
|
||||
}
|
||||
|
||||
log.error('Attempt ${attempts} with model ${current_model.name}')
|
||||
|
||||
// Prepare the prompt with error feedback if this is a retry
|
||||
mut current_prompt := prompt
|
||||
if last_error != '' {
|
||||
current_prompt = 'Previous attempt failed with error: ${last_error}\n\n${prompt}'
|
||||
}
|
||||
|
||||
// Call the AI model
|
||||
response := call_ai_model(current_prompt, current_model) or {
|
||||
log.error('AI call failed: ${err}')
|
||||
last_error = err.str()
|
||||
continue // Try again
|
||||
}
|
||||
|
||||
// Process the response with the callback function
|
||||
result := ut.callback_function(response) or {
|
||||
// If callback returns an error, retry with the error message
|
||||
log.error('Callback returned error: ${err}')
|
||||
last_error = err.str()
|
||||
continue // Try again
|
||||
}
|
||||
|
||||
// If we get here, the callback was successful
|
||||
return result
|
||||
}
|
||||
|
||||
return error('Failed to execute unit task after ${attempts} attempts. Last error: ${last_error}')
|
||||
}
|
||||
68
lib/ai/mcp/README.md
Normal file
68
lib/ai/mcp/README.md
Normal file
@@ -0,0 +1,68 @@
|
||||
# Model Context Protocol (MCP) Implementation
|
||||
|
||||
This module provides a V language implementation of the [Model Context Protocol (MCP)](https://spec.modelcontextprotocol.io/specification/2024-11-05/) specification. MCP is a protocol designed to standardize communication between AI models and their context providers.
|
||||
|
||||
## Overview
|
||||
|
||||
The MCP module serves as a core library for building MCP-compliant servers in V. Its main purpose is to provide all the boilerplate MCP functionality, so implementers only need to define and register their specific handlers. The module handles the Standard Input/Output (stdio) transport as described in the [MCP transport specification](https://modelcontextprotocol.io/docs/concepts/transports), enabling standardized communication between AI models and their context providers.
|
||||
|
||||
The module implements all the required MCP protocol methods (resources/list, tools/list, prompts/list, etc.) and manages the underlying JSON-RPC communication, allowing developers to focus solely on implementing their specific tools and handlers. The module itself is not a standalone server but rather a framework that can be used to build different MCP server implementations. The subdirectories within this module (such as `baobab` and `developer`) contain specific implementations of MCP servers that utilize this core framework.
|
||||
|
||||
## to test
|
||||
|
||||
```
|
||||
curl -fsSL https://bun.sh/install | bash
|
||||
source /root/.bashrc
|
||||
```
|
||||
|
||||
## Key Components
|
||||
|
||||
- **Server**: The main MCP server struct that handles JSON-RPC requests and responses
|
||||
- **Backend Interface**: Abstraction for different backend implementations (memory-based by default)
|
||||
- **Model Configuration**: Structures representing client and server capabilities according to the MCP specification
|
||||
- **Protocol Handlers**: Implementation of MCP protocol handlers for resources, prompts, tools, and initialization
|
||||
- **Factory**: Functions to create and configure an MCP server with custom backends and handlers
|
||||
|
||||
## Features
|
||||
|
||||
- Complete implementation of the MCP protocol version 2024-11-05
|
||||
- Handles all boilerplate protocol methods (resources/list, tools/list, prompts/list, etc.)
|
||||
- JSON-RPC based communication layer with automatic request/response handling
|
||||
- Support for client-server capability negotiation
|
||||
- Pluggable backend system for different storage and processing needs
|
||||
- Generic type conversion utilities for MCP tool content
|
||||
- Comprehensive error handling
|
||||
- Logging capabilities
|
||||
- Minimal implementation requirements for server developers
|
||||
|
||||
## Usage
|
||||
|
||||
To create a new MCP server using the core module:
|
||||
|
||||
```v
|
||||
import freeflowuniverse.herolib.ai.mcp
|
||||
import freeflowuniverse.herolib.schemas.jsonrpc
|
||||
|
||||
// Create a backend (memory-based or custom implementation)
|
||||
backend := mcp.MemoryBackend{
|
||||
tools: {
|
||||
'my_tool': my_tool_definition
|
||||
}
|
||||
tool_handlers: {
|
||||
'my_tool': my_tool_handler
|
||||
}
|
||||
}
|
||||
|
||||
// Create and configure the server
|
||||
mut server := mcp.new_server(backend, mcp.ServerParams{
|
||||
config: mcp.ServerConfiguration{
|
||||
server_info: mcp.ServerInfo{
|
||||
name: 'my_mcp_server'
|
||||
version: '1.0.0'
|
||||
}
|
||||
}
|
||||
})!
|
||||
|
||||
// Start the server
|
||||
server.start()!
|
||||
```
|
||||
3
lib/ai/mcp/README2.md
Normal file
3
lib/ai/mcp/README2.md
Normal file
@@ -0,0 +1,3 @@
|
||||
|
||||
|
||||
If logic is implemented in mcp module, than structure with folders logic and mcp, where logic residers in /logic and mcp related code (like tool and prompt handlers and server code) in /mcp
|
||||
32
lib/ai/mcp/backend_interface.v
Normal file
32
lib/ai/mcp/backend_interface.v
Normal file
@@ -0,0 +1,32 @@
|
||||
module mcp
|
||||
|
||||
import x.json2
|
||||
|
||||
interface Backend {
|
||||
// Resource methods
|
||||
resource_exists(uri string) !bool
|
||||
resource_get(uri string) !Resource
|
||||
resource_list() ![]Resource
|
||||
resource_subscribed(uri string) !bool
|
||||
resource_contents_get(uri string) ![]ResourceContent
|
||||
resource_templates_list() ![]ResourceTemplate
|
||||
|
||||
// Prompt methods
|
||||
prompt_exists(name string) !bool
|
||||
prompt_get(name string) !Prompt
|
||||
prompt_call(name string, arguments []string) ![]PromptMessage
|
||||
prompt_list() ![]Prompt
|
||||
prompt_messages_get(name string, arguments map[string]string) ![]PromptMessage
|
||||
|
||||
// Tool methods
|
||||
tool_exists(name string) !bool
|
||||
tool_get(name string) !Tool
|
||||
tool_list() ![]Tool
|
||||
tool_call(name string, arguments map[string]json2.Any) !ToolCallResult
|
||||
|
||||
// Sampling methods
|
||||
sampling_create_message(params map[string]json2.Any) !SamplingCreateMessageResult
|
||||
mut:
|
||||
resource_subscribe(uri string) !
|
||||
resource_unsubscribe(uri string) !
|
||||
}
|
||||
183
lib/ai/mcp/backend_memory.v
Normal file
183
lib/ai/mcp/backend_memory.v
Normal file
@@ -0,0 +1,183 @@
|
||||
module mcp
|
||||
|
||||
import x.json2
|
||||
|
||||
pub struct MemoryBackend {
|
||||
pub mut:
|
||||
// Resource related fields
|
||||
resources map[string]Resource
|
||||
subscriptions []string // list of subscribed resource uri's
|
||||
resource_contents map[string][]ResourceContent
|
||||
resource_templates map[string]ResourceTemplate
|
||||
|
||||
// Prompt related fields
|
||||
prompts map[string]Prompt
|
||||
prompt_messages map[string][]PromptMessage
|
||||
prompt_handlers map[string]PromptHandler
|
||||
|
||||
// Tool related fields
|
||||
tools map[string]Tool
|
||||
tool_handlers map[string]ToolHandler
|
||||
|
||||
// Sampling related fields
|
||||
sampling_handler SamplingHandler
|
||||
}
|
||||
|
||||
pub type ToolHandler = fn (arguments map[string]json2.Any) !ToolCallResult
|
||||
|
||||
pub type PromptHandler = fn (arguments []string) ![]PromptMessage
|
||||
|
||||
pub type SamplingHandler = fn (params map[string]json2.Any) !SamplingCreateMessageResult
|
||||
|
||||
fn (b &MemoryBackend) resource_exists(uri string) !bool {
|
||||
return uri in b.resources
|
||||
}
|
||||
|
||||
fn (b &MemoryBackend) resource_get(uri string) !Resource {
|
||||
return b.resources[uri] or { return error('resource not found') }
|
||||
}
|
||||
|
||||
fn (b &MemoryBackend) resource_list() ![]Resource {
|
||||
return b.resources.values()
|
||||
}
|
||||
|
||||
fn (mut b MemoryBackend) resource_subscribe(uri string) ! {
|
||||
if uri !in b.subscriptions {
|
||||
b.subscriptions << uri
|
||||
}
|
||||
}
|
||||
|
||||
fn (b &MemoryBackend) resource_subscribed(uri string) !bool {
|
||||
return uri in b.subscriptions
|
||||
}
|
||||
|
||||
fn (mut b MemoryBackend) resource_unsubscribe(uri string) ! {
|
||||
b.subscriptions = b.subscriptions.filter(it != uri)
|
||||
}
|
||||
|
||||
fn (b &MemoryBackend) resource_contents_get(uri string) ![]ResourceContent {
|
||||
return b.resource_contents[uri] or { return error('resource contents not found') }
|
||||
}
|
||||
|
||||
fn (b &MemoryBackend) resource_templates_list() ![]ResourceTemplate {
|
||||
return b.resource_templates.values()
|
||||
}
|
||||
|
||||
// Prompt related methods
|
||||
|
||||
fn (b &MemoryBackend) prompt_exists(name string) !bool {
|
||||
return name in b.prompts
|
||||
}
|
||||
|
||||
fn (b &MemoryBackend) prompt_get(name string) !Prompt {
|
||||
return b.prompts[name] or { return error('prompt not found') }
|
||||
}
|
||||
|
||||
fn (b &MemoryBackend) prompt_list() ![]Prompt {
|
||||
return b.prompts.values()
|
||||
}
|
||||
|
||||
fn (b &MemoryBackend) prompt_messages_get(name string, arguments map[string]string) ![]PromptMessage {
|
||||
// Get the base messages for this prompt
|
||||
base_messages := b.prompt_messages[name] or { return error('prompt messages not found') }
|
||||
|
||||
// Apply arguments to the messages
|
||||
mut messages := []PromptMessage{}
|
||||
|
||||
for msg in base_messages {
|
||||
mut content := msg.content
|
||||
|
||||
// If the content is text, replace argument placeholders
|
||||
if content.typ == 'text' {
|
||||
mut text := content.text
|
||||
|
||||
// Replace each argument in the text
|
||||
for arg_name, arg_value in arguments {
|
||||
text = text.replace('{{${arg_name}}}', arg_value)
|
||||
}
|
||||
|
||||
content = PromptContent{
|
||||
typ: content.typ
|
||||
text: text
|
||||
data: content.data
|
||||
mimetype: content.mimetype
|
||||
resource: content.resource
|
||||
}
|
||||
}
|
||||
|
||||
messages << PromptMessage{
|
||||
role: msg.role
|
||||
content: content
|
||||
}
|
||||
}
|
||||
|
||||
return messages
|
||||
}
|
||||
|
||||
fn (b &MemoryBackend) prompt_call(name string, arguments []string) ![]PromptMessage {
|
||||
// Get the tool handler
|
||||
handler := b.prompt_handlers[name] or { return error('tool handler not found') }
|
||||
|
||||
// Call the handler with the provided arguments
|
||||
return handler(arguments) or { panic(err) }
|
||||
}
|
||||
|
||||
// Tool related methods
|
||||
|
||||
fn (b &MemoryBackend) tool_exists(name string) !bool {
|
||||
return name in b.tools
|
||||
}
|
||||
|
||||
fn (b &MemoryBackend) tool_get(name string) !Tool {
|
||||
return b.tools[name] or { return error('tool not found') }
|
||||
}
|
||||
|
||||
fn (b &MemoryBackend) tool_list() ![]Tool {
|
||||
return b.tools.values()
|
||||
}
|
||||
|
||||
fn (b &MemoryBackend) tool_call(name string, arguments map[string]json2.Any) !ToolCallResult {
|
||||
// Get the tool handler
|
||||
handler := b.tool_handlers[name] or { return error('tool handler not found') }
|
||||
|
||||
// Call the handler with the provided arguments
|
||||
return handler(arguments) or {
|
||||
// If the handler throws an error, return it as a tool error
|
||||
return ToolCallResult{
|
||||
is_error: true
|
||||
content: [
|
||||
ToolContent{
|
||||
typ: 'text'
|
||||
text: 'Error: ${err.msg()}'
|
||||
},
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Sampling related methods
|
||||
|
||||
fn (b &MemoryBackend) sampling_create_message(params map[string]json2.Any) !SamplingCreateMessageResult {
|
||||
// Check if a sampling handler is registered
|
||||
if isnil(b.sampling_handler) {
|
||||
// Return a default implementation that just echoes back a message
|
||||
// indicating that no sampling handler is registered
|
||||
return SamplingCreateMessageResult{
|
||||
model: 'default'
|
||||
stop_reason: 'endTurn'
|
||||
role: 'assistant'
|
||||
content: MessageContent{
|
||||
typ: 'text'
|
||||
text: 'Sampling is not configured on this server. Please register a sampling handler.'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Call the sampling handler with the provided parameters
|
||||
return b.sampling_handler(params)!
|
||||
}
|
||||
|
||||
// register_sampling_handler registers a handler for sampling requests
|
||||
pub fn (mut b MemoryBackend) register_sampling_handler(handler SamplingHandler) {
|
||||
b.sampling_handler = handler
|
||||
}
|
||||
3
lib/ai/mcp/baobab/README.md
Normal file
3
lib/ai/mcp/baobab/README.md
Normal file
@@ -0,0 +1,3 @@
|
||||
## Baobab MCP
|
||||
|
||||
The Base Object and Actor Backend MCP Server provides tools to easily generate BaObAB modules for a given OpenAPI or OpenRPC Schema.
|
||||
172
lib/ai/mcp/baobab/baobab_tools.v
Normal file
172
lib/ai/mcp/baobab/baobab_tools.v
Normal file
@@ -0,0 +1,172 @@
|
||||
module baobab
|
||||
|
||||
import freeflowuniverse.herolib.ai.mcp
|
||||
import freeflowuniverse.herolib.schemas.jsonschema
|
||||
import freeflowuniverse.herolib.core.code
|
||||
import x.json2 as json { Any }
|
||||
import freeflowuniverse.herolib.baobab.generator
|
||||
import freeflowuniverse.herolib.baobab.specification
|
||||
|
||||
// generate_methods_file MCP Tool
|
||||
//
|
||||
|
||||
const generate_methods_file_tool = mcp.Tool{
|
||||
name: 'generate_methods_file'
|
||||
description: 'Generates a methods file with methods for a backend corresponding to thos specified in an OpenAPI or OpenRPC specification'
|
||||
input_schema: jsonschema.Schema{
|
||||
typ: 'object'
|
||||
properties: {
|
||||
'source': jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'object'
|
||||
properties: {
|
||||
'openapi_path': jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'string'
|
||||
})
|
||||
'openrpc_path': jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'string'
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
required: ['source']
|
||||
}
|
||||
}
|
||||
|
||||
pub fn (d &Baobab) generate_methods_file_tool_handler(arguments map[string]Any) !mcp.ToolCallResult {
|
||||
source := json.decode[generator.Source](arguments['source'].str())!
|
||||
result := generator.generate_methods_file_str(source) or {
|
||||
return mcp.error_tool_call_result(err)
|
||||
}
|
||||
return mcp.ToolCallResult{
|
||||
is_error: false
|
||||
content: mcp.result_to_mcp_tool_contents[string](result)
|
||||
}
|
||||
}
|
||||
|
||||
// generate_module_from_openapi MCP Tool
|
||||
const generate_module_from_openapi_tool = mcp.Tool{
|
||||
name: 'generate_module_from_openapi'
|
||||
description: ''
|
||||
input_schema: jsonschema.Schema{
|
||||
typ: 'object'
|
||||
properties: {
|
||||
'openapi_path': jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'string'
|
||||
})
|
||||
}
|
||||
required: ['openapi_path']
|
||||
}
|
||||
}
|
||||
|
||||
pub fn (d &Baobab) generate_module_from_openapi_tool_handler(arguments map[string]Any) !mcp.ToolCallResult {
|
||||
openapi_path := arguments['openapi_path'].str()
|
||||
result := generator.generate_module_from_openapi(openapi_path) or {
|
||||
return mcp.error_tool_call_result(err)
|
||||
}
|
||||
return mcp.ToolCallResult{
|
||||
is_error: false
|
||||
content: mcp.result_to_mcp_tool_contents[string](result)
|
||||
}
|
||||
}
|
||||
|
||||
// generate_methods_interface_file MCP Tool
|
||||
const generate_methods_interface_file_tool = mcp.Tool{
|
||||
name: 'generate_methods_interface_file'
|
||||
description: 'Generates a methods interface file with method interfaces for a backend corresponding to those specified in an OpenAPI or OpenRPC specification'
|
||||
input_schema: jsonschema.Schema{
|
||||
typ: 'object'
|
||||
properties: {
|
||||
'source': jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'object'
|
||||
properties: {
|
||||
'openapi_path': jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'string'
|
||||
})
|
||||
'openrpc_path': jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'string'
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
required: ['source']
|
||||
}
|
||||
}
|
||||
|
||||
pub fn (d &Baobab) generate_methods_interface_file_tool_handler(arguments map[string]Any) !mcp.ToolCallResult {
|
||||
source := json.decode[generator.Source](arguments['source'].str())!
|
||||
result := generator.generate_methods_interface_file_str(source) or {
|
||||
return mcp.error_tool_call_result(err)
|
||||
}
|
||||
return mcp.ToolCallResult{
|
||||
is_error: false
|
||||
content: mcp.result_to_mcp_tool_contents[string](result)
|
||||
}
|
||||
}
|
||||
|
||||
// generate_model_file MCP Tool
|
||||
const generate_model_file_tool = mcp.Tool{
|
||||
name: 'generate_model_file'
|
||||
description: 'Generates a model file with data structures for a backend corresponding to those specified in an OpenAPI or OpenRPC specification'
|
||||
input_schema: jsonschema.Schema{
|
||||
typ: 'object'
|
||||
properties: {
|
||||
'source': jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'object'
|
||||
properties: {
|
||||
'openapi_path': jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'string'
|
||||
})
|
||||
'openrpc_path': jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'string'
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
required: ['source']
|
||||
}
|
||||
}
|
||||
|
||||
pub fn (d &Baobab) generate_model_file_tool_handler(arguments map[string]Any) !mcp.ToolCallResult {
|
||||
source := json.decode[generator.Source](arguments['source'].str())!
|
||||
result := generator.generate_model_file_str(source) or {
|
||||
return mcp.error_tool_call_result(err)
|
||||
}
|
||||
return mcp.ToolCallResult{
|
||||
is_error: false
|
||||
content: mcp.result_to_mcp_tool_contents[string](result)
|
||||
}
|
||||
}
|
||||
|
||||
// generate_methods_example_file MCP Tool
|
||||
const generate_methods_example_file_tool = mcp.Tool{
|
||||
name: 'generate_methods_example_file'
|
||||
description: 'Generates a methods example file with example implementations for a backend corresponding to those specified in an OpenAPI or OpenRPC specification'
|
||||
input_schema: jsonschema.Schema{
|
||||
typ: 'object'
|
||||
properties: {
|
||||
'source': jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'object'
|
||||
properties: {
|
||||
'openapi_path': jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'string'
|
||||
})
|
||||
'openrpc_path': jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'string'
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
required: ['source']
|
||||
}
|
||||
}
|
||||
|
||||
pub fn (d &Baobab) generate_methods_example_file_tool_handler(arguments map[string]Any) !mcp.ToolCallResult {
|
||||
source := json.decode[generator.Source](arguments['source'].str())!
|
||||
result := generator.generate_methods_example_file_str(source) or {
|
||||
return mcp.error_tool_call_result(err)
|
||||
}
|
||||
return mcp.ToolCallResult{
|
||||
is_error: false
|
||||
content: mcp.result_to_mcp_tool_contents[string](result)
|
||||
}
|
||||
}
|
||||
101
lib/ai/mcp/baobab/baobab_tools_test.v
Normal file
101
lib/ai/mcp/baobab/baobab_tools_test.v
Normal file
@@ -0,0 +1,101 @@
|
||||
module baobab
|
||||
|
||||
import freeflowuniverse.herolib.ai.mcp
|
||||
import freeflowuniverse.herolib.schemas.jsonrpc
|
||||
import json
|
||||
import x.json2
|
||||
import os
|
||||
|
||||
// This file contains tests for the Baobab tools implementation.
|
||||
// It tests the tools' ability to handle tool calls and return expected results.
|
||||
|
||||
// test_generate_module_from_openapi_tool tests the generate_module_from_openapi tool definition
|
||||
fn test_generate_module_from_openapi_tool() {
|
||||
// Verify the tool definition
|
||||
assert generate_module_from_openapi_tool.name == 'generate_module_from_openapi', 'Tool name should be "generate_module_from_openapi"'
|
||||
|
||||
// Verify the input schema
|
||||
assert generate_module_from_openapi_tool.input_schema.typ == 'object', 'Input schema type should be "object"'
|
||||
assert 'openapi_path' in generate_module_from_openapi_tool.input_schema.properties, 'Input schema should have "openapi_path" property'
|
||||
assert generate_module_from_openapi_tool.input_schema.properties['openapi_path'].typ == 'string', 'openapi_path property should be of type "string"'
|
||||
assert 'openapi_path' in generate_module_from_openapi_tool.input_schema.required, 'openapi_path should be a required property'
|
||||
}
|
||||
|
||||
// test_generate_module_from_openapi_tool_handler_error tests the error handling of the generate_module_from_openapi tool handler
|
||||
fn test_generate_module_from_openapi_tool_handler_error() {
|
||||
// Create arguments with a non-existent file path
|
||||
mut arguments := map[string]json2.Any{}
|
||||
arguments['openapi_path'] = json2.Any('non_existent_file.yaml')
|
||||
|
||||
// Call the handler
|
||||
result := generate_module_from_openapi_tool_handler(arguments) or {
|
||||
// If the handler returns an error, that's expected
|
||||
assert err.msg().contains(''), 'Error message should not be empty'
|
||||
return
|
||||
}
|
||||
|
||||
// If we get here, the handler should have returned an error result
|
||||
assert result.is_error, 'Result should indicate an error'
|
||||
assert result.content.len > 0, 'Error content should not be empty'
|
||||
assert result.content[0].typ == 'text', 'Error content should be of type "text"'
|
||||
assert result.content[0].text.contains('failed to open file'), 'Error content should contain "failed to open file", instead ${result.content[0].text}'
|
||||
}
|
||||
|
||||
// test_mcp_tool_call_integration tests the integration of the tool with the MCP server
|
||||
fn test_mcp_tool_call_integration() {
|
||||
// Create a new MCP server
|
||||
mut server := new_mcp_server() or {
|
||||
assert false, 'Failed to create MCP server: ${err}'
|
||||
return
|
||||
}
|
||||
|
||||
// Create a temporary OpenAPI file for testing
|
||||
temp_dir := os.temp_dir()
|
||||
temp_file := os.join_path(temp_dir, 'test_openapi.yaml')
|
||||
os.write_file(temp_file, 'openapi: 3.0.0\ninfo:\n title: Test API\n version: 1.0.0\npaths:\n /test:\n get:\n summary: Test endpoint\n responses:\n "200":\n description: OK') or {
|
||||
assert false, 'Failed to create temporary file: ${err}'
|
||||
return
|
||||
}
|
||||
|
||||
// Sample tool call request
|
||||
tool_call_request := '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"generate_module_from_openapi","arguments":{"openapi_path":"${temp_file}"}}}'
|
||||
|
||||
// Process the request through the handler
|
||||
response := server.handler.handle(tool_call_request) or {
|
||||
// Clean up the temporary file
|
||||
os.rm(temp_file) or {}
|
||||
|
||||
// If the handler returns an error, that's expected in this test environment
|
||||
// since we might not have all dependencies set up
|
||||
return
|
||||
}
|
||||
|
||||
// Clean up the temporary file
|
||||
os.rm(temp_file) or {}
|
||||
|
||||
// Decode the response to verify its structure
|
||||
decoded_response := jsonrpc.decode_response(response) or {
|
||||
// In a test environment, we might get an error due to missing dependencies
|
||||
// This is acceptable for this test
|
||||
return
|
||||
}
|
||||
|
||||
// If we got a successful response, verify it
|
||||
if !decoded_response.is_error() {
|
||||
// Parse the result to verify its contents
|
||||
result_json := decoded_response.result() or {
|
||||
assert false, 'Failed to get result: ${err}'
|
||||
return
|
||||
}
|
||||
|
||||
// Decode the result to check the content
|
||||
result_map := json2.raw_decode(result_json) or {
|
||||
assert false, 'Failed to decode result: ${err}'
|
||||
return
|
||||
}.as_map()
|
||||
|
||||
// Verify the result structure
|
||||
assert 'isError' in result_map, 'Result should have isError field'
|
||||
assert 'content' in result_map, 'Result should have content field'
|
||||
}
|
||||
}
|
||||
22
lib/ai/mcp/baobab/command.v
Normal file
22
lib/ai/mcp/baobab/command.v
Normal file
@@ -0,0 +1,22 @@
|
||||
module baobab
|
||||
|
||||
import cli
|
||||
|
||||
pub const command = cli.Command{
|
||||
sort_flags: true
|
||||
name: 'baobab'
|
||||
// execute: cmd_mcpgen
|
||||
description: 'baobab command'
|
||||
commands: [
|
||||
cli.Command{
|
||||
name: 'start'
|
||||
execute: cmd_start
|
||||
description: 'start the Baobab server'
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
fn cmd_start(cmd cli.Command) ! {
|
||||
mut server := new_mcp_server(&Baobab{})!
|
||||
server.start()!
|
||||
}
|
||||
128
lib/ai/mcp/baobab/mcp_test.v
Normal file
128
lib/ai/mcp/baobab/mcp_test.v
Normal file
@@ -0,0 +1,128 @@
|
||||
module baobab
|
||||
|
||||
import freeflowuniverse.herolib.ai.mcp
|
||||
import freeflowuniverse.herolib.schemas.jsonrpc
|
||||
import json
|
||||
import x.json2
|
||||
|
||||
// This file contains tests for the Baobab MCP server implementation.
|
||||
// It tests the server's ability to initialize and handle tool calls.
|
||||
|
||||
// test_new_mcp_server tests the creation of a new MCP server for the Baobab module
|
||||
fn test_new_mcp_server() {
|
||||
// Create a new MCP server
|
||||
mut server := new_mcp_server() or {
|
||||
assert false, 'Failed to create MCP server: ${err}'
|
||||
return
|
||||
}
|
||||
|
||||
// Verify server info
|
||||
assert server.server_info.name == 'developer', 'Server name should be "developer"'
|
||||
assert server.server_info.version == '1.0.0', 'Server version should be 1.0.0'
|
||||
|
||||
// Verify server capabilities
|
||||
assert server.capabilities.prompts.list_changed == true, 'Prompts capability should have list_changed set to true'
|
||||
assert server.capabilities.resources.subscribe == true, 'Resources capability should have subscribe set to true'
|
||||
assert server.capabilities.resources.list_changed == true, 'Resources capability should have list_changed set to true'
|
||||
assert server.capabilities.tools.list_changed == true, 'Tools capability should have list_changed set to true'
|
||||
}
|
||||
|
||||
// test_mcp_server_initialize tests the initialize handler with a sample initialize request
|
||||
fn test_mcp_server_initialize() {
|
||||
// Create a new MCP server
|
||||
mut server := new_mcp_server() or {
|
||||
assert false, 'Failed to create MCP server: ${err}'
|
||||
return
|
||||
}
|
||||
|
||||
// Sample initialize request from the MCP specification
|
||||
initialize_request := '{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{"sampling":{},"roots":{"listChanged":true}},"clientInfo":{"name":"mcp-inspector","version":"0.0.1"}}}'
|
||||
|
||||
// Process the request through the handler
|
||||
response := server.handler.handle(initialize_request) or {
|
||||
assert false, 'Handler failed to process request: ${err}'
|
||||
return
|
||||
}
|
||||
|
||||
// Decode the response to verify its structure
|
||||
decoded_response := jsonrpc.decode_response(response) or {
|
||||
assert false, 'Failed to decode response: ${err}'
|
||||
return
|
||||
}
|
||||
|
||||
// Verify that the response is not an error
|
||||
assert !decoded_response.is_error(), 'Response should not be an error'
|
||||
|
||||
// Parse the result to verify its contents
|
||||
result_json := decoded_response.result() or {
|
||||
assert false, 'Failed to get result: ${err}'
|
||||
return
|
||||
}
|
||||
|
||||
// Decode the result into an ServerConfiguration struct
|
||||
result := json.decode(mcp.ServerConfiguration, result_json) or {
|
||||
assert false, 'Failed to decode result: ${err}'
|
||||
return
|
||||
}
|
||||
|
||||
// Verify the protocol version matches what was requested
|
||||
assert result.protocol_version == '2024-11-05', 'Protocol version should match the request'
|
||||
|
||||
// Verify server info
|
||||
assert result.server_info.name == 'developer', 'Server name should be "developer"'
|
||||
}
|
||||
|
||||
// test_tools_list tests the tools/list handler to verify tool registration
|
||||
fn test_tools_list() {
|
||||
// Create a new MCP server
|
||||
mut server := new_mcp_server() or {
|
||||
assert false, 'Failed to create MCP server: ${err}'
|
||||
return
|
||||
}
|
||||
|
||||
// Sample tools/list request
|
||||
tools_list_request := '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{"cursor":""}}'
|
||||
|
||||
// Process the request through the handler
|
||||
response := server.handler.handle(tools_list_request) or {
|
||||
assert false, 'Handler failed to process request: ${err}'
|
||||
return
|
||||
}
|
||||
|
||||
// Decode the response to verify its structure
|
||||
decoded_response := jsonrpc.decode_response(response) or {
|
||||
assert false, 'Failed to decode response: ${err}'
|
||||
return
|
||||
}
|
||||
|
||||
// Verify that the response is not an error
|
||||
assert !decoded_response.is_error(), 'Response should not be an error'
|
||||
|
||||
// Parse the result to verify its contents
|
||||
result_json := decoded_response.result() or {
|
||||
assert false, 'Failed to get result: ${err}'
|
||||
return
|
||||
}
|
||||
|
||||
// Decode the result into a map to check the tools
|
||||
result_map := json2.raw_decode(result_json) or {
|
||||
assert false, 'Failed to decode result: ${err}'
|
||||
return
|
||||
}.as_map()
|
||||
|
||||
// Verify that the tools array exists and contains the expected tool
|
||||
tools := result_map['tools'].arr()
|
||||
assert tools.len > 0, 'Tools list should not be empty'
|
||||
|
||||
// Find the generate_module_from_openapi tool
|
||||
mut found_tool := false
|
||||
for tool in tools {
|
||||
tool_map := tool.as_map()
|
||||
if tool_map['name'].str() == 'generate_module_from_openapi' {
|
||||
found_tool = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
assert found_tool, 'generate_module_from_openapi tool should be registered'
|
||||
}
|
||||
38
lib/ai/mcp/baobab/server.v
Normal file
38
lib/ai/mcp/baobab/server.v
Normal file
@@ -0,0 +1,38 @@
|
||||
module baobab
|
||||
|
||||
import freeflowuniverse.herolib.ai.mcp
|
||||
import freeflowuniverse.herolib.ai.mcp.logger
|
||||
import freeflowuniverse.herolib.schemas.jsonrpc
|
||||
|
||||
@[heap]
|
||||
pub struct Baobab {}
|
||||
|
||||
pub fn new_mcp_server(v &Baobab) !&mcp.Server {
|
||||
logger.info('Creating new Baobab MCP server')
|
||||
|
||||
// Initialize the server with the empty handlers map
|
||||
mut server := mcp.new_server(mcp.MemoryBackend{
|
||||
tools: {
|
||||
'generate_module_from_openapi': generate_module_from_openapi_tool
|
||||
'generate_methods_file': generate_methods_file_tool
|
||||
'generate_methods_interface_file': generate_methods_interface_file_tool
|
||||
'generate_model_file': generate_model_file_tool
|
||||
'generate_methods_example_file': generate_methods_example_file_tool
|
||||
}
|
||||
tool_handlers: {
|
||||
'generate_module_from_openapi': v.generate_module_from_openapi_tool_handler
|
||||
'generate_methods_file': v.generate_methods_file_tool_handler
|
||||
'generate_methods_interface_file': v.generate_methods_interface_file_tool_handler
|
||||
'generate_model_file': v.generate_model_file_tool_handler
|
||||
'generate_methods_example_file': v.generate_methods_example_file_tool_handler
|
||||
}
|
||||
}, mcp.ServerParams{
|
||||
config: mcp.ServerConfiguration{
|
||||
server_info: mcp.ServerInfo{
|
||||
name: 'baobab'
|
||||
version: '1.0.0'
|
||||
}
|
||||
}
|
||||
})!
|
||||
return server
|
||||
}
|
||||
68
lib/ai/mcp/cmd/compile.vsh
Executable file
68
lib/ai/mcp/cmd/compile.vsh
Executable file
@@ -0,0 +1,68 @@
|
||||
#!/usr/bin/env -S v -n -cg -w -parallel-cc -enable-globals run
|
||||
|
||||
import os
|
||||
import flag
|
||||
|
||||
mut fp := flag.new_flag_parser(os.args)
|
||||
fp.application('compile.vsh')
|
||||
fp.version('v0.1.0')
|
||||
fp.description('Compile MCP binary in debug or production mode')
|
||||
fp.skip_executable()
|
||||
|
||||
prod_mode := fp.bool('prod', `p`, false, 'Build production version (optimized)')
|
||||
help_requested := fp.bool('help', `h`, false, 'Show help message')
|
||||
|
||||
if help_requested {
|
||||
println(fp.usage())
|
||||
exit(0)
|
||||
}
|
||||
|
||||
additional_args := fp.finalize() or {
|
||||
eprintln(err)
|
||||
println(fp.usage())
|
||||
exit(1)
|
||||
}
|
||||
|
||||
if additional_args.len > 0 {
|
||||
eprintln('Unexpected arguments: ${additional_args.join(' ')}')
|
||||
println(fp.usage())
|
||||
exit(1)
|
||||
}
|
||||
|
||||
// Change to the mcp directory
|
||||
mcp_dir := os.dir(os.real_path(os.executable()))
|
||||
os.chdir(mcp_dir) or { panic('Failed to change directory to ${mcp_dir}: ${err}') }
|
||||
|
||||
// Set MCPPATH based on OS
|
||||
mut mcppath := '/usr/local/bin/mcp'
|
||||
if os.user_os() == 'macos' {
|
||||
mcppath = os.join_path(os.home_dir(), 'hero/bin/mcp')
|
||||
}
|
||||
|
||||
// Set compilation command based on OS and mode
|
||||
compile_cmd := if prod_mode {
|
||||
'v -enable-globals -w -n -prod mcp.v'
|
||||
} else {
|
||||
'v -w -cg -gc none -cc tcc -d use_openssl -enable-globals mcp.v'
|
||||
}
|
||||
|
||||
println('Building MCP in ${if prod_mode { 'production' } else { 'debug' }} mode...')
|
||||
|
||||
if os.system(compile_cmd) != 0 {
|
||||
panic('Failed to compile mcp.v with command: ${compile_cmd}')
|
||||
}
|
||||
|
||||
// Make executable
|
||||
os.chmod('mcp', 0o755) or { panic('Failed to make mcp binary executable: ${err}') }
|
||||
|
||||
// Ensure destination directory exists
|
||||
os.mkdir_all(os.dir(mcppath)) or { panic('Failed to create directory ${os.dir(mcppath)}: ${err}') }
|
||||
|
||||
// Copy to destination paths
|
||||
os.cp('mcp', mcppath) or { panic('Failed to copy mcp binary to ${mcppath}: ${err}') }
|
||||
os.cp('mcp', '/tmp/mcp') or { panic('Failed to copy mcp binary to /tmp/mcp: ${err}') }
|
||||
|
||||
// Clean up
|
||||
os.rm('mcp') or { panic('Failed to remove temporary mcp binary: ${err}') }
|
||||
|
||||
println('**MCP COMPILE OK**')
|
||||
93
lib/ai/mcp/cmd/mcp.v
Normal file
93
lib/ai/mcp/cmd/mcp.v
Normal file
@@ -0,0 +1,93 @@
|
||||
module main
|
||||
|
||||
import os
|
||||
import cli { Command, Flag }
|
||||
import freeflowuniverse.herolib.osal
|
||||
// import freeflowuniverse.herolib.ai.mcp.vcode
|
||||
// import freeflowuniverse.herolib.ai.mcp.mcpgen
|
||||
// import freeflowuniverse.herolib.ai.mcp.baobab
|
||||
import freeflowuniverse.herolib.ai.mcp.rhai.mcp as rhai_mcp
|
||||
import freeflowuniverse.herolib.ai.mcp.rust
|
||||
|
||||
fn main() {
|
||||
do() or { panic(err) }
|
||||
}
|
||||
|
||||
pub fn do() ! {
|
||||
mut cmd_mcp := Command{
|
||||
name: 'mcp'
|
||||
usage: '
|
||||
## Manage your MCPs
|
||||
|
||||
example:
|
||||
|
||||
mcp
|
||||
'
|
||||
description: 'create, edit, show mdbooks'
|
||||
required_args: 0
|
||||
}
|
||||
|
||||
// cmd_run_add_flags(mut cmd_publisher)
|
||||
|
||||
cmd_mcp.add_flag(Flag{
|
||||
flag: .bool
|
||||
required: false
|
||||
name: 'debug'
|
||||
abbrev: 'd'
|
||||
description: 'show debug output'
|
||||
})
|
||||
|
||||
cmd_mcp.add_flag(Flag{
|
||||
flag: .bool
|
||||
required: false
|
||||
name: 'verbose'
|
||||
abbrev: 'v'
|
||||
description: 'show verbose output'
|
||||
})
|
||||
|
||||
mut cmd_inspector := Command{
|
||||
sort_flags: true
|
||||
name: 'inspector'
|
||||
execute: cmd_inspector_execute
|
||||
description: 'will list existing mdbooks'
|
||||
}
|
||||
|
||||
cmd_inspector.add_flag(Flag{
|
||||
flag: .string
|
||||
required: false
|
||||
name: 'name'
|
||||
abbrev: 'n'
|
||||
description: 'name of the MCP'
|
||||
})
|
||||
|
||||
cmd_inspector.add_flag(Flag{
|
||||
flag: .bool
|
||||
required: false
|
||||
name: 'open'
|
||||
abbrev: 'o'
|
||||
description: 'open inspector'
|
||||
})
|
||||
|
||||
cmd_mcp.add_command(rhai_mcp.command)
|
||||
cmd_mcp.add_command(rust.command)
|
||||
// cmd_mcp.add_command(baobab.command)
|
||||
// cmd_mcp.add_command(vcode.command)
|
||||
cmd_mcp.add_command(cmd_inspector)
|
||||
// cmd_mcp.add_command(vcode.command)
|
||||
cmd_mcp.setup()
|
||||
cmd_mcp.parse(os.args)
|
||||
}
|
||||
|
||||
fn cmd_inspector_execute(cmd Command) ! {
|
||||
open := cmd.flags.get_bool('open') or { false }
|
||||
if open {
|
||||
osal.exec(cmd: 'open http://localhost:5173')!
|
||||
}
|
||||
name := cmd.flags.get_string('name') or { '' }
|
||||
if name.len > 0 {
|
||||
println('starting inspector for MCP ${name}')
|
||||
osal.exec(cmd: 'npx @modelcontextprotocol/inspector mcp ${name} start')!
|
||||
} else {
|
||||
osal.exec(cmd: 'npx @modelcontextprotocol/inspector')!
|
||||
}
|
||||
}
|
||||
49
lib/ai/mcp/factory.v
Normal file
49
lib/ai/mcp/factory.v
Normal file
@@ -0,0 +1,49 @@
|
||||
module mcp
|
||||
|
||||
import time
|
||||
import os
|
||||
import log
|
||||
import x.json2
|
||||
import freeflowuniverse.herolib.schemas.jsonrpc
|
||||
|
||||
@[params]
|
||||
pub struct ServerParams {
|
||||
pub:
|
||||
handlers map[string]jsonrpc.ProcedureHandler
|
||||
config ServerConfiguration
|
||||
}
|
||||
|
||||
// new_server creates a new MCP server
|
||||
pub fn new_server(backend Backend, params ServerParams) !&Server {
|
||||
mut server := &Server{
|
||||
ServerConfiguration: params.config
|
||||
backend: backend
|
||||
}
|
||||
|
||||
// Create a handler with the core MCP procedures registered
|
||||
handler := jsonrpc.new_handler(jsonrpc.Handler{
|
||||
procedures: {
|
||||
//...params.handlers,
|
||||
// Core handlers
|
||||
'initialize': server.initialize_handler
|
||||
'notifications/initialized': initialized_notification_handler
|
||||
// Resource handlers
|
||||
'resources/list': server.resources_list_handler
|
||||
'resources/read': server.resources_read_handler
|
||||
'resources/templates/list': server.resources_templates_list_handler
|
||||
'resources/subscribe': server.resources_subscribe_handler
|
||||
// Prompt handlers
|
||||
'prompts/list': server.prompts_list_handler
|
||||
'prompts/get': server.prompts_get_handler
|
||||
'completion/complete': server.prompts_get_handler
|
||||
// Tool handlers
|
||||
'tools/list': server.tools_list_handler
|
||||
'tools/call': server.tools_call_handler
|
||||
// Sampling handlers
|
||||
'sampling/createMessage': server.sampling_create_message_handler
|
||||
}
|
||||
})!
|
||||
|
||||
server.handler = *handler
|
||||
return server
|
||||
}
|
||||
52
lib/ai/mcp/generics.v
Normal file
52
lib/ai/mcp/generics.v
Normal file
@@ -0,0 +1,52 @@
|
||||
module mcp
|
||||
|
||||
pub fn result_to_mcp_tool_contents[T](result T) []ToolContent {
|
||||
return [result_to_mcp_tool_content[T](result)]
|
||||
}
|
||||
|
||||
pub fn result_to_mcp_tool_content[T](result T) ToolContent {
|
||||
$if T is string {
|
||||
return ToolContent{
|
||||
typ: 'text'
|
||||
text: result.str()
|
||||
}
|
||||
} $else $if T is int {
|
||||
return ToolContent{
|
||||
typ: 'number'
|
||||
number: result.int()
|
||||
}
|
||||
} $else $if T is bool {
|
||||
return ToolContent{
|
||||
typ: 'boolean'
|
||||
boolean: result.bool()
|
||||
}
|
||||
} $else $if result is $array {
|
||||
mut items := []ToolContent{}
|
||||
for item in result {
|
||||
items << result_to_mcp_tool_content(item)
|
||||
}
|
||||
return ToolContent{
|
||||
typ: 'array'
|
||||
items: items
|
||||
}
|
||||
} $else $if T is $struct {
|
||||
mut properties := map[string]ToolContent{}
|
||||
$for field in T.fields {
|
||||
properties[field.name] = result_to_mcp_tool_content(result.$(field.name))
|
||||
}
|
||||
return ToolContent{
|
||||
typ: 'object'
|
||||
properties: properties
|
||||
}
|
||||
} $else {
|
||||
panic('Unsupported type: ${typeof(result)}')
|
||||
}
|
||||
}
|
||||
|
||||
pub fn array_to_mcp_tool_contents[U](array []U) []ToolContent {
|
||||
mut contents := []ToolContent{}
|
||||
for item in array {
|
||||
contents << result_to_mcp_tool_content(item)
|
||||
}
|
||||
return contents
|
||||
}
|
||||
27
lib/ai/mcp/handler_initialize.v
Normal file
27
lib/ai/mcp/handler_initialize.v
Normal file
@@ -0,0 +1,27 @@
|
||||
module mcp
|
||||
|
||||
import time
|
||||
import os
|
||||
import log
|
||||
import x.json2
|
||||
import freeflowuniverse.herolib.schemas.jsonrpc
|
||||
|
||||
// initialize_handler handles the initialize request according to the MCP specification
|
||||
fn (mut s Server) initialize_handler(data string) !string {
|
||||
// Decode the request with ClientConfiguration parameters
|
||||
request := jsonrpc.decode_request_generic[ClientConfiguration](data)!
|
||||
s.client_config = request.params
|
||||
|
||||
// Create a success response with the result
|
||||
response := jsonrpc.new_response_generic[ServerConfiguration](request.id, s.ServerConfiguration)
|
||||
return response.encode()
|
||||
}
|
||||
|
||||
// initialized_notification_handler handles the initialized notification
|
||||
// This notification is sent by the client after successful initialization
|
||||
fn initialized_notification_handler(data string) !string {
|
||||
// This is a notification, so no response is expected
|
||||
// Just log that we received the notification
|
||||
log.info('Received initialized notification')
|
||||
return ''
|
||||
}
|
||||
103
lib/ai/mcp/handler_initialize_test.v
Normal file
103
lib/ai/mcp/handler_initialize_test.v
Normal file
@@ -0,0 +1,103 @@
|
||||
module mcp
|
||||
|
||||
import freeflowuniverse.herolib.schemas.jsonrpc
|
||||
import json
|
||||
|
||||
// This file contains tests for the MCP initialize handler implementation.
|
||||
// It tests the handler's ability to process initialize requests according to the MCP specification.
|
||||
|
||||
// test_initialize_handler tests the initialize handler with a sample initialize request
|
||||
fn test_initialize_handler() {
|
||||
mut server := Server{}
|
||||
|
||||
// Sample initialize request from the MCP specification
|
||||
initialize_request := '{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{"sampling":{},"roots":{"listChanged":true}},"clientInfo":{"name":"mcp-inspector","version":"0.0.1"}}}'
|
||||
|
||||
// Call the initialize handler directly
|
||||
response := server.initialize_handler(initialize_request) or {
|
||||
assert false, 'Initialize handler failed: ${err}'
|
||||
return
|
||||
}
|
||||
|
||||
// Decode the response to verify its structure
|
||||
decoded_response := jsonrpc.decode_response(response) or {
|
||||
assert false, 'Failed to decode response: ${err}'
|
||||
return
|
||||
}
|
||||
|
||||
// Verify that the response is not an error
|
||||
assert !decoded_response.is_error(), 'Response should not be an error'
|
||||
|
||||
// Parse the result to verify its contents
|
||||
result_json := decoded_response.result() or {
|
||||
assert false, 'Failed to get result: ${err}'
|
||||
return
|
||||
}
|
||||
|
||||
// Decode the result into an ServerConfiguration struct
|
||||
result := json.decode(ServerConfiguration, result_json) or {
|
||||
assert false, 'Failed to decode result: ${err}'
|
||||
return
|
||||
}
|
||||
|
||||
// Verify the protocol version matches what was requested
|
||||
assert result.protocol_version == '2024-11-05', 'Protocol version should match the request'
|
||||
|
||||
// Verify server capabilities
|
||||
assert result.capabilities.prompts.list_changed == true, 'Prompts capability should have list_changed set to true'
|
||||
assert result.capabilities.resources.subscribe == true, 'Resources capability should have subscribe set to true'
|
||||
assert result.capabilities.resources.list_changed == true, 'Resources capability should have list_changed set to true'
|
||||
assert result.capabilities.tools.list_changed == true, 'Tools capability should have list_changed set to true'
|
||||
|
||||
// Verify server info
|
||||
assert result.server_info.name == 'HeroLibMCPServer', 'Server name should be HeroLibMCPServer'
|
||||
assert result.server_info.version == '1.0.0', 'Server version should be 1.0.0'
|
||||
}
|
||||
|
||||
// test_initialize_handler_with_handler tests the initialize handler through the JSONRPC handler
|
||||
fn test_initialize_handler_with_handler() {
|
||||
mut server := Server{}
|
||||
|
||||
// Create a handler with just the initialize procedure
|
||||
handler := jsonrpc.new_handler(jsonrpc.Handler{
|
||||
procedures: {
|
||||
'initialize': server.initialize_handler
|
||||
}
|
||||
}) or {
|
||||
assert false, 'Failed to create handler: ${err}'
|
||||
return
|
||||
}
|
||||
|
||||
// Sample initialize request from the MCP specification
|
||||
initialize_request := '{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{"sampling":{},"roots":{"listChanged":true}},"clientInfo":{"name":"mcp-inspector","version":"0.0.1"}}}'
|
||||
|
||||
// Process the request through the handler
|
||||
response := handler.handle(initialize_request) or {
|
||||
assert false, 'Handler failed to process request: ${err}'
|
||||
return
|
||||
}
|
||||
|
||||
// Decode the response to verify its structure
|
||||
decoded_response := jsonrpc.decode_response(response) or {
|
||||
assert false, 'Failed to decode response: ${err}'
|
||||
return
|
||||
}
|
||||
|
||||
// Verify that the response is not an error
|
||||
assert !decoded_response.is_error(), 'Response should not be an error'
|
||||
|
||||
// Parse the result to verify its contents
|
||||
result_json := decoded_response.result() or {
|
||||
assert false, 'Failed to get result: ${err}'
|
||||
return
|
||||
}
|
||||
|
||||
// Decode the result into an ServerConfiguration struct
|
||||
result := json.decode(ServerConfiguration, result_json) or {
|
||||
assert false, 'Failed to decode result: ${err}'
|
||||
return
|
||||
}
|
||||
|
||||
// Verify the protocol version matches what was requested
|
||||
assert result.protocol_version == '2024-11-05', 'Protocol version should match the request'
|
||||
}
|
||||
135
lib/ai/mcp/handler_prompts.v
Normal file
135
lib/ai/mcp/handler_prompts.v
Normal file
@@ -0,0 +1,135 @@
|
||||
module mcp
|
||||
|
||||
import time
|
||||
import os
|
||||
import log
|
||||
import x.json2
|
||||
import json
|
||||
import freeflowuniverse.herolib.schemas.jsonrpc
|
||||
|
||||
// Prompt related structs
|
||||
|
||||
pub struct Prompt {
|
||||
pub:
|
||||
name string
|
||||
description string
|
||||
arguments []PromptArgument
|
||||
}
|
||||
|
||||
pub struct PromptArgument {
|
||||
pub:
|
||||
name string
|
||||
description string
|
||||
required bool
|
||||
}
|
||||
|
||||
pub struct PromptMessage {
|
||||
pub:
|
||||
role string
|
||||
content PromptContent
|
||||
}
|
||||
|
||||
pub struct PromptContent {
|
||||
pub:
|
||||
typ string @[json: 'type']
|
||||
text string
|
||||
data string
|
||||
mimetype string @[json: 'mimeType']
|
||||
resource ResourceContent
|
||||
}
|
||||
|
||||
// Prompt List Handler
|
||||
|
||||
pub struct PromptListParams {
|
||||
pub:
|
||||
cursor string
|
||||
}
|
||||
|
||||
pub struct PromptListResult {
|
||||
pub:
|
||||
prompts []Prompt
|
||||
next_cursor string @[json: 'nextCursor']
|
||||
}
|
||||
|
||||
// prompts_list_handler handles the prompts/list request
|
||||
// This request is used to retrieve a list of available prompts
|
||||
fn (mut s Server) prompts_list_handler(data string) !string {
|
||||
// Decode the request with cursor parameter
|
||||
request := jsonrpc.decode_request_generic[PromptListParams](data)!
|
||||
cursor := request.params.cursor
|
||||
|
||||
// TODO: Implement pagination logic using the cursor
|
||||
// For now, return all prompts
|
||||
|
||||
// Create a success response with the result
|
||||
response := jsonrpc.new_response_generic[PromptListResult](request.id, PromptListResult{
|
||||
prompts: s.backend.prompt_list()!
|
||||
next_cursor: '' // Empty if no more pages
|
||||
})
|
||||
return response.encode()
|
||||
}
|
||||
|
||||
// Prompt Get Handler
|
||||
|
||||
pub struct PromptGetParams {
|
||||
pub:
|
||||
name string
|
||||
arguments map[string]string
|
||||
}
|
||||
|
||||
pub struct PromptGetResult {
|
||||
pub:
|
||||
description string
|
||||
messages []PromptMessage
|
||||
}
|
||||
|
||||
// prompts_get_handler handles the prompts/get request
|
||||
// This request is used to retrieve a specific prompt with arguments
|
||||
fn (mut s Server) prompts_get_handler(data string) !string {
|
||||
// Decode the request with name and arguments parameters
|
||||
request_map := json2.raw_decode(data)!.as_map()
|
||||
params_map := request_map['params'].as_map()
|
||||
|
||||
if !s.backend.prompt_exists(params_map['name'].str())! {
|
||||
return jsonrpc.new_error_response(request_map['id'].int(), prompt_not_found(params_map['name'].str())).encode()
|
||||
}
|
||||
|
||||
// Get the prompt by name
|
||||
prompt := s.backend.prompt_get(params_map['name'].str())!
|
||||
|
||||
// Validate required arguments
|
||||
for arg in prompt.arguments {
|
||||
if arg.required && params_map['arguments'].as_map()[arg.name].str() == '' {
|
||||
return jsonrpc.new_error_response(request_map['id'].int(), missing_required_argument(arg.name)).encode()
|
||||
}
|
||||
}
|
||||
|
||||
messages := s.backend.prompt_call(params_map['name'].str(), params_map['arguments'].as_map().values().map(it.str()))!
|
||||
|
||||
// // Get the prompt messages with arguments applied
|
||||
// messages := s.backend.prompt_messages_get(request.params.name, request.params.arguments)!
|
||||
|
||||
// Create a success response with the result
|
||||
response := jsonrpc.new_response_generic[PromptGetResult](request_map['id'].int(),
|
||||
PromptGetResult{
|
||||
description: prompt.description
|
||||
messages: messages
|
||||
})
|
||||
return response.encode()
|
||||
}
|
||||
|
||||
// Prompt Notification Handlers
|
||||
|
||||
// send_prompts_list_changed_notification sends a notification when the list of prompts changes
|
||||
pub fn (mut s Server) send_prompts_list_changed_notification() ! {
|
||||
// Check if the client supports this notification
|
||||
if !s.client_config.capabilities.roots.list_changed {
|
||||
return
|
||||
}
|
||||
|
||||
// Create a notification
|
||||
notification := jsonrpc.new_blank_notification('notifications/prompts/list_changed')
|
||||
s.send(json.encode(notification))
|
||||
// Send the notification to all connected clients
|
||||
log.info('Sending prompts list changed notification: ${json.encode(notification)}')
|
||||
}
|
||||
186
lib/ai/mcp/handler_resources.v
Normal file
186
lib/ai/mcp/handler_resources.v
Normal file
@@ -0,0 +1,186 @@
|
||||
module mcp
|
||||
|
||||
import time
|
||||
import os
|
||||
import log
|
||||
import x.json2
|
||||
import json
|
||||
import freeflowuniverse.herolib.schemas.jsonrpc
|
||||
|
||||
pub struct Resource {
|
||||
pub:
|
||||
uri string
|
||||
name string
|
||||
description string
|
||||
mimetype string @[json: 'mimeType']
|
||||
}
|
||||
|
||||
// Resource List Handler
|
||||
|
||||
pub struct ResourceListParams {
|
||||
pub:
|
||||
cursor string
|
||||
}
|
||||
|
||||
pub struct ResourceListResult {
|
||||
pub:
|
||||
resources []Resource
|
||||
next_cursor string @[json: 'nextCursor']
|
||||
}
|
||||
|
||||
// resources_list_handler handles the resources/list request
|
||||
// This request is used to retrieve a list of available resources
|
||||
fn (mut s Server) resources_list_handler(data string) !string {
|
||||
// Decode the request with cursor parameter
|
||||
request := jsonrpc.decode_request_generic[ResourceListParams](data)!
|
||||
cursor := request.params.cursor
|
||||
|
||||
// TODO: Implement pagination logic using the cursor
|
||||
// For now, return all resources
|
||||
|
||||
// Create a success response with the result
|
||||
response := jsonrpc.new_response_generic[ResourceListResult](request.id, ResourceListResult{
|
||||
resources: s.backend.resource_list()!
|
||||
next_cursor: '' // Empty if no more pages
|
||||
})
|
||||
return response.encode()
|
||||
}
|
||||
|
||||
// Resource Read Handler
|
||||
|
||||
pub struct ResourceReadParams {
|
||||
pub:
|
||||
uri string
|
||||
}
|
||||
|
||||
pub struct ResourceReadResult {
|
||||
pub:
|
||||
contents []ResourceContent
|
||||
}
|
||||
|
||||
pub struct ResourceContent {
|
||||
pub:
|
||||
uri string
|
||||
mimetype string @[json: 'mimeType']
|
||||
text string
|
||||
blob string // Base64-encoded binary data
|
||||
}
|
||||
|
||||
// resources_read_handler handles the resources/read request
|
||||
// This request is used to retrieve the contents of a resource
|
||||
fn (mut s Server) resources_read_handler(data string) !string {
|
||||
// Decode the request with uri parameter
|
||||
request := jsonrpc.decode_request_generic[ResourceReadParams](data)!
|
||||
|
||||
if !s.backend.resource_exists(request.params.uri)! {
|
||||
return jsonrpc.new_error_response(request.id, resource_not_found(request.params.uri)).encode()
|
||||
}
|
||||
|
||||
// Get the resource contents by URI
|
||||
resource_contents := s.backend.resource_contents_get(request.params.uri)!
|
||||
|
||||
// Create a success response with the result
|
||||
response := jsonrpc.new_response_generic[ResourceReadResult](request.id, ResourceReadResult{
|
||||
contents: resource_contents
|
||||
})
|
||||
return response.encode()
|
||||
}
|
||||
|
||||
// Resource Templates Handler
|
||||
|
||||
pub struct ResourceTemplatesListResult {
|
||||
pub:
|
||||
resource_templates []ResourceTemplate @[json: 'resourceTemplates']
|
||||
}
|
||||
|
||||
pub struct ResourceTemplate {
|
||||
pub:
|
||||
uri_template string @[json: 'uriTemplate']
|
||||
name string
|
||||
description string
|
||||
mimetype string @[json: 'mimeType']
|
||||
}
|
||||
|
||||
// resources_templates_list_handler handles the resources/templates/list request
|
||||
// This request is used to retrieve a list of available resource templates
|
||||
fn (mut s Server) resources_templates_list_handler(data string) !string {
|
||||
// Decode the request
|
||||
request := jsonrpc.decode_request(data)!
|
||||
|
||||
// Create a success response with the result
|
||||
response := jsonrpc.new_response_generic[ResourceTemplatesListResult](request.id,
|
||||
ResourceTemplatesListResult{
|
||||
resource_templates: s.backend.resource_templates_list()!
|
||||
})
|
||||
return response.encode()
|
||||
}
|
||||
|
||||
// Resource Subscription Handler
|
||||
|
||||
pub struct ResourceSubscribeParams {
|
||||
pub:
|
||||
uri string
|
||||
}
|
||||
|
||||
pub struct ResourceSubscribeResult {
|
||||
pub:
|
||||
subscribed bool
|
||||
}
|
||||
|
||||
// resources_subscribe_handler handles the resources/subscribe request
|
||||
// This request is used to subscribe to changes for a specific resource
|
||||
fn (mut s Server) resources_subscribe_handler(data string) !string {
|
||||
request := jsonrpc.decode_request_generic[ResourceSubscribeParams](data)!
|
||||
|
||||
if !s.backend.resource_exists(request.params.uri)! {
|
||||
return jsonrpc.new_error_response(request.id, resource_not_found(request.params.uri)).encode()
|
||||
}
|
||||
|
||||
s.backend.resource_subscribe(request.params.uri)!
|
||||
|
||||
response := jsonrpc.new_response_generic[ResourceSubscribeResult](request.id, ResourceSubscribeResult{
|
||||
subscribed: true
|
||||
})
|
||||
return response.encode()
|
||||
}
|
||||
|
||||
// Resource Notification Handlers
|
||||
|
||||
// send_resources_list_changed_notification sends a notification when the list of resources changes
|
||||
pub fn (mut s Server) send_resources_list_changed_notification() ! {
|
||||
// Check if the client supports this notification
|
||||
if !s.client_config.capabilities.roots.list_changed {
|
||||
return
|
||||
}
|
||||
|
||||
// Create a notification
|
||||
notification := jsonrpc.new_blank_notification('notifications/resources/list_changed')
|
||||
s.send(json.encode(notification))
|
||||
// Send the notification to all connected clients
|
||||
// In a real implementation, this would use a WebSocket or other transport
|
||||
log.info('Sending resources list changed notification: ${json.encode(notification)}')
|
||||
}
|
||||
|
||||
pub struct ResourceUpdatedParams {
|
||||
pub:
|
||||
uri string
|
||||
}
|
||||
|
||||
// send_resource_updated_notification sends a notification when a subscribed resource is updated
|
||||
pub fn (mut s Server) send_resource_updated_notification(uri string) ! {
|
||||
// Check if the client is subscribed to this resource
|
||||
if !s.backend.resource_subscribed(uri)! {
|
||||
return
|
||||
}
|
||||
|
||||
// Create a notification
|
||||
notification := jsonrpc.new_notification[ResourceUpdatedParams]('notifications/resources/updated',
|
||||
ResourceUpdatedParams{
|
||||
uri: uri
|
||||
})
|
||||
|
||||
s.send(json.encode(notification))
|
||||
// Send the notification to all connected clients
|
||||
// In a real implementation, this would use a WebSocket or other transport
|
||||
log.info('Sending resource updated notification: ${json.encode(notification)}')
|
||||
}
|
||||
145
lib/ai/mcp/handler_sampling.v
Normal file
145
lib/ai/mcp/handler_sampling.v
Normal file
@@ -0,0 +1,145 @@
|
||||
module mcp
|
||||
|
||||
import time
|
||||
import os
|
||||
import log
|
||||
import x.json2
|
||||
import json
|
||||
import freeflowuniverse.herolib.schemas.jsonrpc
|
||||
|
||||
// Sampling related structs
|
||||
|
||||
pub struct MessageContent {
|
||||
pub:
|
||||
typ string @[json: 'type']
|
||||
text string
|
||||
data string
|
||||
mimetype string @[json: 'mimeType']
|
||||
}
|
||||
|
||||
pub struct Message {
|
||||
pub:
|
||||
role string
|
||||
content MessageContent
|
||||
}
|
||||
|
||||
pub struct ModelHint {
|
||||
pub:
|
||||
name string
|
||||
}
|
||||
|
||||
pub struct ModelPreferences {
|
||||
pub:
|
||||
hints []ModelHint
|
||||
cost_priority f32 @[json: 'costPriority']
|
||||
speed_priority f32 @[json: 'speedPriority']
|
||||
intelligence_priority f32 @[json: 'intelligencePriority']
|
||||
}
|
||||
|
||||
pub struct SamplingCreateMessageParams {
|
||||
pub:
|
||||
messages []Message
|
||||
model_preferences ModelPreferences @[json: 'modelPreferences']
|
||||
system_prompt string @[json: 'systemPrompt']
|
||||
include_context string @[json: 'includeContext']
|
||||
temperature f32
|
||||
max_tokens int @[json: 'maxTokens']
|
||||
stop_sequences []string @[json: 'stopSequences']
|
||||
metadata map[string]json2.Any
|
||||
}
|
||||
|
||||
pub struct SamplingCreateMessageResult {
|
||||
pub:
|
||||
model string
|
||||
stop_reason string @[json: 'stopReason']
|
||||
role string
|
||||
content MessageContent
|
||||
}
|
||||
|
||||
// sampling_create_message_handler handles the sampling/createMessage request
|
||||
// This request is used to request LLM completions through the client
|
||||
fn (mut s Server) sampling_create_message_handler(data string) !string {
|
||||
// Decode the request
|
||||
request_map := json2.raw_decode(data)!.as_map()
|
||||
id := request_map['id'].int()
|
||||
params_map := request_map['params'].as_map()
|
||||
|
||||
// Validate required parameters
|
||||
if 'messages' !in params_map {
|
||||
return jsonrpc.new_error_response(id, missing_required_argument('messages')).encode()
|
||||
}
|
||||
|
||||
if 'maxTokens' !in params_map {
|
||||
return jsonrpc.new_error_response(id, missing_required_argument('maxTokens')).encode()
|
||||
}
|
||||
|
||||
// Call the backend to handle the sampling request
|
||||
result := s.backend.sampling_create_message(params_map) or {
|
||||
return jsonrpc.new_error_response(id, sampling_error(err.msg())).encode()
|
||||
}
|
||||
|
||||
// Create a success response with the result
|
||||
response := jsonrpc.new_response(id, json.encode(result))
|
||||
return response.encode()
|
||||
}
|
||||
|
||||
// Helper function to convert JSON messages to our Message struct format
|
||||
fn parse_messages(messages_json json2.Any) ![]Message {
|
||||
messages_arr := messages_json.arr()
|
||||
mut result := []Message{cap: messages_arr.len}
|
||||
|
||||
for msg_json in messages_arr {
|
||||
msg_map := msg_json.as_map()
|
||||
|
||||
if 'role' !in msg_map {
|
||||
return error('Missing role in message')
|
||||
}
|
||||
|
||||
if 'content' !in msg_map {
|
||||
return error('Missing content in message')
|
||||
}
|
||||
|
||||
role := msg_map['role'].str()
|
||||
content_map := msg_map['content'].as_map()
|
||||
|
||||
if 'type' !in content_map {
|
||||
return error('Missing type in message content')
|
||||
}
|
||||
|
||||
typ := content_map['type'].str()
|
||||
mut text := ''
|
||||
mut data := ''
|
||||
mut mimetype := ''
|
||||
|
||||
if typ == 'text' {
|
||||
if 'text' !in content_map {
|
||||
return error('Missing text in text content')
|
||||
}
|
||||
text = content_map['text'].str()
|
||||
} else if typ == 'image' {
|
||||
if 'data' !in content_map {
|
||||
return error('Missing data in image content')
|
||||
}
|
||||
data = content_map['data'].str()
|
||||
|
||||
if 'mimeType' !in content_map {
|
||||
return error('Missing mimeType in image content')
|
||||
}
|
||||
mimetype = content_map['mimeType'].str()
|
||||
} else {
|
||||
return error('Unsupported content type: ${typ}')
|
||||
}
|
||||
|
||||
result << Message{
|
||||
role: role
|
||||
content: MessageContent{
|
||||
typ: typ
|
||||
text: text
|
||||
data: data
|
||||
mimetype: mimetype
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
151
lib/ai/mcp/handler_tools.v
Normal file
151
lib/ai/mcp/handler_tools.v
Normal file
@@ -0,0 +1,151 @@
|
||||
module mcp
|
||||
|
||||
import time
|
||||
import os
|
||||
import log
|
||||
import x.json2
|
||||
import json
|
||||
import freeflowuniverse.herolib.schemas.jsonrpc
|
||||
import freeflowuniverse.herolib.schemas.jsonschema
|
||||
|
||||
// Tool related structs
|
||||
|
||||
pub struct Tool {
|
||||
pub:
|
||||
name string
|
||||
description string
|
||||
input_schema jsonschema.Schema @[json: 'inputSchema']
|
||||
}
|
||||
|
||||
pub struct ToolProperty {
|
||||
pub:
|
||||
typ string @[json: 'type']
|
||||
items ToolItems
|
||||
enum []string
|
||||
}
|
||||
|
||||
pub struct ToolItems {
|
||||
pub:
|
||||
typ string @[json: 'type']
|
||||
enum []string
|
||||
properties map[string]ToolProperty
|
||||
}
|
||||
|
||||
pub struct ToolContent {
|
||||
pub:
|
||||
typ string @[json: 'type']
|
||||
text string
|
||||
number int
|
||||
boolean bool
|
||||
properties map[string]ToolContent
|
||||
items []ToolContent
|
||||
}
|
||||
|
||||
// Tool List Handler
|
||||
|
||||
pub struct ToolListParams {
|
||||
pub:
|
||||
cursor string
|
||||
}
|
||||
|
||||
pub struct ToolListResult {
|
||||
pub:
|
||||
tools []Tool
|
||||
next_cursor string @[json: 'nextCursor']
|
||||
}
|
||||
|
||||
// tools_list_handler handles the tools/list request
|
||||
// This request is used to retrieve a list of available tools
|
||||
fn (mut s Server) tools_list_handler(data string) !string {
|
||||
// Decode the request with cursor parameter
|
||||
request := jsonrpc.decode_request_generic[ToolListParams](data)!
|
||||
cursor := request.params.cursor
|
||||
|
||||
// TODO: Implement pagination logic using the cursor
|
||||
// For now, return all tools
|
||||
encoded := json.encode(ToolListResult{
|
||||
tools: s.backend.tool_list()!
|
||||
next_cursor: '' // Empty if no more pages
|
||||
})
|
||||
// Create a success response with the result
|
||||
response := jsonrpc.new_response(request.id, json.encode(ToolListResult{
|
||||
tools: s.backend.tool_list()!
|
||||
next_cursor: '' // Empty if no more pages
|
||||
}))
|
||||
return response.encode()
|
||||
}
|
||||
|
||||
// Tool Call Handler
|
||||
|
||||
pub struct ToolCallParams {
|
||||
pub:
|
||||
name string
|
||||
arguments map[string]json2.Any
|
||||
meta map[string]json2.Any @[json: '_meta']
|
||||
}
|
||||
|
||||
pub struct ToolCallResult {
|
||||
pub:
|
||||
is_error bool @[json: 'isError']
|
||||
content []ToolContent
|
||||
}
|
||||
|
||||
// tools_call_handler handles the tools/call request
|
||||
// This request is used to call a specific tool with arguments
|
||||
fn (mut s Server) tools_call_handler(data string) !string {
|
||||
// Decode the request with name and arguments parameters
|
||||
request_map := json2.raw_decode(data)!.as_map()
|
||||
params_map := request_map['params'].as_map()
|
||||
tool_name := params_map['name'].str()
|
||||
if !s.backend.tool_exists(tool_name)! {
|
||||
return jsonrpc.new_error_response(request_map['id'].int(), tool_not_found(tool_name)).encode()
|
||||
}
|
||||
|
||||
arguments := params_map['arguments'].as_map()
|
||||
// Get the tool by name
|
||||
tool := s.backend.tool_get(tool_name)!
|
||||
|
||||
// Validate arguments against the input schema
|
||||
// TODO: Implement proper JSON Schema validation
|
||||
for req in tool.input_schema.required {
|
||||
if req !in arguments {
|
||||
return jsonrpc.new_error_response(request_map['id'].int(), missing_required_argument(req)).encode()
|
||||
}
|
||||
}
|
||||
|
||||
log.error('Calling tool: ${tool_name} with arguments: ${arguments}')
|
||||
// Call the tool with the provided arguments
|
||||
result := s.backend.tool_call(tool_name, arguments)!
|
||||
|
||||
log.error('Received result from tool: ${tool_name} with result: ${result}')
|
||||
// Create a success response with the result
|
||||
response := jsonrpc.new_response_generic[ToolCallResult](request_map['id'].int(),
|
||||
result)
|
||||
return response.encode()
|
||||
}
|
||||
|
||||
// Tool Notification Handlers
|
||||
|
||||
// send_tools_list_changed_notification sends a notification when the list of tools changes
|
||||
pub fn (mut s Server) send_tools_list_changed_notification() ! {
|
||||
// Check if the client supports this notification
|
||||
if !s.client_config.capabilities.roots.list_changed {
|
||||
return
|
||||
}
|
||||
|
||||
// Create a notification
|
||||
notification := jsonrpc.new_blank_notification('notifications/tools/list_changed')
|
||||
s.send(json.encode(notification))
|
||||
// Send the notification to all connected clients
|
||||
log.info('Sending tools list changed notification: ${json.encode(notification)}')
|
||||
}
|
||||
|
||||
pub fn error_tool_call_result(err IError) ToolCallResult {
|
||||
return ToolCallResult{
|
||||
is_error: true
|
||||
content: [ToolContent{
|
||||
typ: 'text'
|
||||
text: err.msg()
|
||||
}]
|
||||
}
|
||||
}
|
||||
92
lib/ai/mcp/mcpgen/README.md
Normal file
92
lib/ai/mcp/mcpgen/README.md
Normal file
@@ -0,0 +1,92 @@
|
||||
# MCP Generator
|
||||
|
||||
An implementation of the [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) server for V language operations. This server uses the Standard Input/Output (stdio) transport as described in the [MCP documentation](https://modelcontextprotocol.io/docs/concepts/transports).
|
||||
|
||||
## Features
|
||||
|
||||
The server supports the following operations:
|
||||
|
||||
1. **test** - Run V tests on a file or directory
|
||||
2. **run** - Execute V code from a file or directory
|
||||
3. **compile** - Compile V code from a file or directory
|
||||
4. **vet** - Run V vet on a file or directory
|
||||
|
||||
## Usage
|
||||
|
||||
### Building the Server
|
||||
|
||||
```bash
|
||||
v -gc none -stats -enable-globals -n -w -cg -g -cc tcc /Users/despiegk/code/github/freeflowuniverse/herolib/lib/mcp/v_do
|
||||
```
|
||||
|
||||
### Using the Server
|
||||
|
||||
The server communicates using the MCP protocol over stdio. To send a request, use the following format:
|
||||
|
||||
```
|
||||
Content-Length: <length>
|
||||
|
||||
{"jsonrpc":"2.0","id":"<request-id>","method":"<method-name>","params":{"fullpath":"<path-to-file-or-directory>"}}
|
||||
```
|
||||
|
||||
Where:
|
||||
- `<length>` is the length of the JSON message in bytes
|
||||
- `<request-id>` is a unique identifier for the request
|
||||
- `<method-name>` is one of: `test`, `run`, `compile`, or `vet`
|
||||
- `<path-to-file-or-directory>` is the absolute path to the V file or directory to process
|
||||
|
||||
### Example
|
||||
|
||||
Request:
|
||||
```
|
||||
Content-Length: 85
|
||||
|
||||
{"jsonrpc":"2.0","id":"1","method":"test","params":{"fullpath":"/path/to/file.v"}}
|
||||
```
|
||||
|
||||
Response:
|
||||
```
|
||||
Content-Length: 245
|
||||
|
||||
{"jsonrpc":"2.0","id":"1","result":{"output":"Command: v -gc none -stats -enable-globals -show-c-output -keepc -n -w -cg -o /tmp/tester.c -g -cc tcc test /path/to/file.v\nExit code: 0\nOutput:\nAll tests passed!"}}
|
||||
```
|
||||
|
||||
## Methods
|
||||
|
||||
### test
|
||||
|
||||
Runs V tests on the specified file or directory.
|
||||
|
||||
Command used:
|
||||
```
|
||||
v -gc none -stats -enable-globals -show-c-output -keepc -n -w -cg -o /tmp/tester.c -g -cc tcc test ${fullpath}
|
||||
```
|
||||
|
||||
If a directory is specified, it will run tests on all `.v` files in the directory (non-recursive).
|
||||
|
||||
### run
|
||||
|
||||
Executes the specified V file or all V files in a directory.
|
||||
|
||||
Command used:
|
||||
```
|
||||
v -gc none -stats -enable-globals -n -w -cg -g -cc tcc run ${fullpath}
|
||||
```
|
||||
|
||||
### compile
|
||||
|
||||
Compiles the specified V file or all V files in a directory.
|
||||
|
||||
Command used:
|
||||
```
|
||||
cd /tmp && v -gc none -enable-globals -show-c-output -keepc -n -w -cg -o /tmp/tester.c -g -cc tcc ${fullpath}
|
||||
```
|
||||
|
||||
### vet
|
||||
|
||||
Runs V vet on the specified file or directory.
|
||||
|
||||
Command used:
|
||||
```
|
||||
v vet -v -w ${fullpath}
|
||||
```
|
||||
22
lib/ai/mcp/mcpgen/command.v
Normal file
22
lib/ai/mcp/mcpgen/command.v
Normal file
@@ -0,0 +1,22 @@
|
||||
module mcpgen
|
||||
|
||||
import cli
|
||||
|
||||
pub const command = cli.Command{
|
||||
sort_flags: true
|
||||
name: 'mcpgen'
|
||||
// execute: cmd_mcpgen
|
||||
description: 'will list existing mdbooks'
|
||||
commands: [
|
||||
cli.Command{
|
||||
name: 'start'
|
||||
execute: cmd_start
|
||||
description: 'start the MCP server'
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
fn cmd_start(cmd cli.Command) ! {
|
||||
mut server := new_mcp_server(&MCPGen{})!
|
||||
server.start()!
|
||||
}
|
||||
281
lib/ai/mcp/mcpgen/mcpgen.v
Normal file
281
lib/ai/mcp/mcpgen/mcpgen.v
Normal file
@@ -0,0 +1,281 @@
|
||||
module mcpgen
|
||||
|
||||
import freeflowuniverse.herolib.core.code
|
||||
import freeflowuniverse.herolib.ai.mcp
|
||||
import freeflowuniverse.herolib.schemas.jsonschema
|
||||
import freeflowuniverse.herolib.schemas.jsonschema.codegen
|
||||
import os
|
||||
|
||||
pub struct FunctionPointer {
|
||||
name string // name of function
|
||||
module_path string // path to module
|
||||
}
|
||||
|
||||
// create_mcp_tool_code receives the name of a V language function string, and the path to the module in which it exists.
|
||||
// returns an MCP Tool code in v for attaching the function to the mcp server
|
||||
// function_pointers: A list of function pointers to generate tools for
|
||||
pub fn (d &MCPGen) create_mcp_tools_code(function_pointers []FunctionPointer) !string {
|
||||
mut str := ''
|
||||
|
||||
for function_pointer in function_pointers {
|
||||
str += d.create_mcp_tool_code(function_pointer.name, function_pointer.module_path)!
|
||||
}
|
||||
|
||||
return str
|
||||
}
|
||||
|
||||
// create_mcp_tool_code receives the name of a V language function string, and the path to the module in which it exists.
|
||||
// returns an MCP Tool code in v for attaching the function to the mcp server
|
||||
pub fn (d &MCPGen) create_mcp_tool_code(function_name string, module_path string) !string {
|
||||
if !os.exists(module_path) {
|
||||
return error('Module path does not exist: ${module_path}')
|
||||
}
|
||||
|
||||
function := code.get_function_from_module(module_path, function_name) or {
|
||||
return error('Failed to get function ${function_name} from module ${module_path}\n${err}')
|
||||
}
|
||||
|
||||
mut types := map[string]string{}
|
||||
for param in function.params {
|
||||
// Check if the type is an Object (struct)
|
||||
if param.typ is code.Object {
|
||||
types[param.typ.symbol()] = code.get_type_from_module(module_path, param.typ.symbol())!
|
||||
}
|
||||
}
|
||||
|
||||
// Get the result type if it's a struct
|
||||
mut result_ := ''
|
||||
if function.result.typ is code.Result {
|
||||
result_type := (function.result.typ as code.Result).typ
|
||||
if result_type is code.Object {
|
||||
result_ = code.get_type_from_module(module_path, result_type.symbol())!
|
||||
}
|
||||
} else if function.result.typ is code.Object {
|
||||
result_ = code.get_type_from_module(module_path, function.result.typ.symbol())!
|
||||
}
|
||||
|
||||
tool_name := function.name
|
||||
tool := d.create_mcp_tool(function, types)!
|
||||
handler := d.create_mcp_tool_handler(function, types, result_)!
|
||||
str := $tmpl('./templates/tool_code.v.template')
|
||||
return str
|
||||
}
|
||||
|
||||
// create_mcp_tool parses a V language function string and returns an MCP Tool struct
|
||||
// function: The V function string including preceding comments
|
||||
// types: A map of struct names to their definitions for complex parameter types
|
||||
// result: The type of result of the create_mcp_tool function. Could be simply string, or struct {...}
|
||||
pub fn (d &MCPGen) create_mcp_tool_handler(function code.Function, types map[string]string, result_ string) !string {
|
||||
decode_stmts := function.params.map(argument_decode_stmt(it)).join_lines()
|
||||
|
||||
function_call := 'd.${function.name}(${function.params.map(it.name).join(',')})'
|
||||
result := code.parse_type(result_)
|
||||
str := $tmpl('./templates/tool_handler.v.template')
|
||||
return str
|
||||
}
|
||||
|
||||
pub fn argument_decode_stmt(param code.Param) string {
|
||||
return if param.typ is code.Integer {
|
||||
'${param.name} := arguments["${param.name}"].int()'
|
||||
} else if param.typ is code.Boolean {
|
||||
'${param.name} := arguments["${param.name}"].bool()'
|
||||
} else if param.typ is code.String {
|
||||
'${param.name} := arguments["${param.name}"].str()'
|
||||
} else if param.typ is code.Object {
|
||||
'${param.name} := json.decode[${param.typ.symbol()}](arguments["${param.name}"].str())!'
|
||||
} else if param.typ is code.Array {
|
||||
'${param.name} := json.decode[${param.typ.symbol()}](arguments["${param.name}"].str())!'
|
||||
} else if param.typ is code.Map {
|
||||
'${param.name} := json.decode[${param.typ.symbol()}](arguments["${param.name}"].str())!'
|
||||
} else {
|
||||
panic('Unsupported type: ${param.typ}')
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
in @generate_mcp.v , implement a create_mpc_tool_handler function that given a vlang function string and the types that map to their corresponding type definitions (for instance struct some_type: SomeType{...}), generates a vlang function such as the following:
|
||||
|
||||
ou
|
||||
pub fn (d &MCPGen) create_mcp_tool_tool_handler(arguments map[string]Any) !mcp.Tool {
|
||||
function := arguments['function'].str()
|
||||
types := json.decode[map[string]string](arguments['types'].str())!
|
||||
return d.create_mcp_tool(function, types)
|
||||
}
|
||||
*/
|
||||
|
||||
// create_mcp_tool parses a V language function string and returns an MCP Tool struct
|
||||
// function: The V function string including preceding comments
|
||||
// types: A map of struct names to their definitions for complex parameter types
|
||||
pub fn (d MCPGen) create_mcp_tool(function code.Function, types map[string]string) !mcp.Tool {
|
||||
// Create input schema for parameters
|
||||
mut properties := map[string]jsonschema.SchemaRef{}
|
||||
mut required := []string{}
|
||||
|
||||
for param in function.params {
|
||||
// Add to required parameters
|
||||
required << param.name
|
||||
|
||||
// Create property for this parameter
|
||||
mut property := jsonschema.SchemaRef{}
|
||||
|
||||
// Check if this is a complex type defined in the types map
|
||||
if param.typ.symbol() in types {
|
||||
// Parse the struct definition to create a nested schema
|
||||
struct_def := types[param.typ.symbol()]
|
||||
struct_schema := codegen.struct_to_schema(code.parse_struct(struct_def)!)
|
||||
if struct_schema is jsonschema.Schema {
|
||||
property = struct_schema
|
||||
} else {
|
||||
return error('Unsupported type: ${param.typ}')
|
||||
}
|
||||
} else {
|
||||
// Handle primitive types
|
||||
property = codegen.typesymbol_to_schema(param.typ.symbol())
|
||||
}
|
||||
|
||||
properties[param.name] = property
|
||||
}
|
||||
|
||||
// Create the input schema
|
||||
input_schema := jsonschema.Schema{
|
||||
typ: 'object'
|
||||
properties: properties
|
||||
required: required
|
||||
}
|
||||
|
||||
// Create and return the Tool
|
||||
return mcp.Tool{
|
||||
name: function.name
|
||||
description: function.description
|
||||
input_schema: input_schema
|
||||
}
|
||||
}
|
||||
|
||||
// // create_mcp_tool_input_schema creates a jsonschema.Schema for a given input type
|
||||
// // input: The input type string
|
||||
// // returns: A jsonschema.Schema for the given input type
|
||||
// // errors: Returns an error if the input type is not supported
|
||||
// pub fn (d MCPGen) create_mcp_tool_input_schema(input string) !jsonschema.Schema {
|
||||
|
||||
// // if input is a primitive type, return a mcp jsonschema.Schema with that type
|
||||
// if input == 'string' {
|
||||
// return jsonschema.Schema{
|
||||
// typ: 'string'
|
||||
// }
|
||||
// } else if input == 'int' {
|
||||
// return jsonschema.Schema{
|
||||
// typ: 'integer'
|
||||
// }
|
||||
// } else if input == 'float' {
|
||||
// return jsonschema.Schema{
|
||||
// typ: 'number'
|
||||
// }
|
||||
// } else if input == 'bool' {
|
||||
// return jsonschema.Schema{
|
||||
// typ: 'boolean'
|
||||
// }
|
||||
// }
|
||||
|
||||
// // if input is a struct, return a mcp jsonschema.Schema with typ 'object' and properties for each field in the struct
|
||||
// if input.starts_with('pub struct ') {
|
||||
// struct_name := input[11..].split(' ')[0]
|
||||
// fields := parse_struct_fields(input)
|
||||
// mut properties := map[string]jsonschema.Schema{}
|
||||
|
||||
// for field_name, field_type in fields {
|
||||
// property := jsonschema.Schema{
|
||||
// typ: d.create_mcp_tool_input_schema(field_type)!.typ
|
||||
// }
|
||||
// properties[field_name] = property
|
||||
// }
|
||||
|
||||
// return jsonschema.Schema{
|
||||
// typ: 'object',
|
||||
// properties: properties
|
||||
// }
|
||||
// }
|
||||
|
||||
// // if input is an array, return a mcp jsonschema.Schema with typ 'array' and items of the item type
|
||||
// if input.starts_with('[]') {
|
||||
// item_type := input[2..]
|
||||
|
||||
// // For array types, we create a schema with type 'array'
|
||||
// // The actual item type is determined by the primitive type
|
||||
// mut item_type_str := 'string' // default
|
||||
// if item_type == 'int' {
|
||||
// item_type_str = 'integer'
|
||||
// } else if item_type == 'float' {
|
||||
// item_type_str = 'number'
|
||||
// } else if item_type == 'bool' {
|
||||
// item_type_str = 'boolean'
|
||||
// }
|
||||
|
||||
// // Create a property for the array items
|
||||
// mut property := jsonschema.Schema{
|
||||
// typ: 'array'
|
||||
// }
|
||||
|
||||
// // Add the property to the schema
|
||||
// mut properties := map[string]jsonschema.Schema{}
|
||||
// properties['items'] = property
|
||||
|
||||
// return jsonschema.Schema{
|
||||
// typ: 'array',
|
||||
// properties: properties
|
||||
// }
|
||||
// }
|
||||
|
||||
// // Default to string type for unknown types
|
||||
// return jsonschema.Schema{
|
||||
// typ: 'string'
|
||||
// }
|
||||
// }
|
||||
|
||||
// parse_struct_fields parses a V language struct definition string and returns a map of field names to their types
|
||||
fn parse_struct_fields(struct_def string) map[string]string {
|
||||
mut fields := map[string]string{}
|
||||
|
||||
// Find the opening and closing braces of the struct definition
|
||||
start_idx := struct_def.index('{') or { return fields }
|
||||
end_idx := struct_def.last_index('}') or { return fields }
|
||||
|
||||
// Extract the content between the braces
|
||||
struct_content := struct_def[start_idx + 1..end_idx].trim_space()
|
||||
|
||||
// Split the content by newlines to get individual field definitions
|
||||
field_lines := struct_content.split('
|
||||
')
|
||||
|
||||
for line in field_lines {
|
||||
trimmed_line := line.trim_space()
|
||||
|
||||
// Skip empty lines and comments
|
||||
if trimmed_line == '' || trimmed_line.starts_with('//') {
|
||||
continue
|
||||
}
|
||||
|
||||
// Handle pub: or mut: prefixes
|
||||
mut field_def := trimmed_line
|
||||
if field_def.starts_with('pub:') || field_def.starts_with('mut:') {
|
||||
field_def = field_def.all_after(':').trim_space()
|
||||
}
|
||||
|
||||
// Split by whitespace to separate field name and type
|
||||
parts := field_def.split_any(' ')
|
||||
if parts.len < 2 {
|
||||
continue
|
||||
}
|
||||
|
||||
field_name := parts[0]
|
||||
field_type := parts[1..].join(' ')
|
||||
|
||||
// Handle attributes like @[json: 'name']
|
||||
if field_name.contains('@[') {
|
||||
continue
|
||||
}
|
||||
|
||||
fields[field_name] = field_type
|
||||
}
|
||||
|
||||
return fields
|
||||
}
|
||||
@@ -1,8 +1,6 @@
|
||||
module developer
|
||||
|
||||
@[heap]
|
||||
pub struct Developer {}
|
||||
module mcpgen
|
||||
|
||||
import freeflowuniverse.herolib.ai.mcp
|
||||
|
||||
pub fn result_to_mcp_tool_contents[T](result T) []mcp.ToolContent {
|
||||
return [result_to_mcp_tool_content(result)]
|
||||
@@ -11,17 +9,17 @@ pub fn result_to_mcp_tool_contents[T](result T) []mcp.ToolContent {
|
||||
pub fn result_to_mcp_tool_content[T](result T) mcp.ToolContent {
|
||||
return $if T is string {
|
||||
mcp.ToolContent{
|
||||
typ: 'text'
|
||||
typ: 'text'
|
||||
text: result.str()
|
||||
}
|
||||
} $else $if T is int {
|
||||
mcp.ToolContent{
|
||||
typ: 'number'
|
||||
typ: 'number'
|
||||
number: result.int()
|
||||
}
|
||||
} $else $if T is bool {
|
||||
mcp.ToolContent{
|
||||
typ: 'boolean'
|
||||
typ: 'boolean'
|
||||
boolean: result.bool()
|
||||
}
|
||||
} $else $if result is $array {
|
||||
@@ -30,7 +28,7 @@ pub fn result_to_mcp_tool_content[T](result T) mcp.ToolContent {
|
||||
items << result_to_mcp_tool_content(item)
|
||||
}
|
||||
return mcp.ToolContent{
|
||||
typ: 'array'
|
||||
typ: 'array'
|
||||
items: items
|
||||
}
|
||||
} $else $if T is $struct {
|
||||
@@ -39,7 +37,7 @@ pub fn result_to_mcp_tool_content[T](result T) mcp.ToolContent {
|
||||
properties[field.name] = result_to_mcp_tool_content(result.$(field.name))
|
||||
}
|
||||
return mcp.ToolContent{
|
||||
typ: 'object'
|
||||
typ: 'object'
|
||||
properties: properties
|
||||
}
|
||||
} $else {
|
||||
144
lib/ai/mcp/mcpgen/mcpgen_tools.v
Normal file
144
lib/ai/mcp/mcpgen/mcpgen_tools.v
Normal file
@@ -0,0 +1,144 @@
|
||||
module mcpgen
|
||||
|
||||
import freeflowuniverse.herolib.ai.mcp
|
||||
import freeflowuniverse.herolib.core.code
|
||||
import freeflowuniverse.herolib.schemas.jsonschema
|
||||
import x.json2 as json { Any }
|
||||
// import json
|
||||
|
||||
// create_mcp_tools_code MCP Tool
|
||||
// create_mcp_tool_code receives the name of a V language function string, and the path to the module in which it exists.
|
||||
// returns an MCP Tool code in v for attaching the function to the mcp server
|
||||
// function_pointers: A list of function pointers to generate tools for
|
||||
|
||||
const create_mcp_tools_code_tool = mcp.Tool{
|
||||
name: 'create_mcp_tools_code'
|
||||
description: 'create_mcp_tool_code receives the name of a V language function string, and the path to the module in which it exists.
|
||||
returns an MCP Tool code in v for attaching the function to the mcp server
|
||||
function_pointers: A list of function pointers to generate tools for'
|
||||
input_schema: jsonschema.Schema{
|
||||
typ: 'object'
|
||||
properties: {
|
||||
'function_pointers': jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'array'
|
||||
items: jsonschema.Items(jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'object'
|
||||
properties: {
|
||||
'name': jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'string'
|
||||
})
|
||||
'module_path': jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'string'
|
||||
})
|
||||
}
|
||||
required: ['name', 'module_path']
|
||||
}))
|
||||
})
|
||||
}
|
||||
required: ['function_pointers']
|
||||
}
|
||||
}
|
||||
|
||||
pub fn (d &MCPGen) create_mcp_tools_code_tool_handler(arguments map[string]Any) !mcp.ToolCallResult {
|
||||
function_pointers := json.decode[[]FunctionPointer](arguments['function_pointers'].str())!
|
||||
result := d.create_mcp_tools_code(function_pointers) or {
|
||||
return mcp.error_tool_call_result(err)
|
||||
}
|
||||
return mcp.ToolCallResult{
|
||||
is_error: false
|
||||
content: mcp.result_to_mcp_tool_contents[string](result)
|
||||
}
|
||||
}
|
||||
|
||||
const create_mcp_tool_code_tool = mcp.Tool{
|
||||
name: 'create_mcp_tool_code'
|
||||
description: 'create_mcp_tool_code receives the name of a V language function string, and the path to the module in which it exists.
|
||||
returns an MCP Tool code in v for attaching the function to the mcp server'
|
||||
input_schema: jsonschema.Schema{
|
||||
typ: 'object'
|
||||
properties: {
|
||||
'function_name': jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'string'
|
||||
})
|
||||
'module_path': jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'string'
|
||||
})
|
||||
}
|
||||
required: ['function_name', 'module_path']
|
||||
}
|
||||
}
|
||||
|
||||
pub fn (d &MCPGen) create_mcp_tool_code_tool_handler(arguments map[string]Any) !mcp.ToolCallResult {
|
||||
function_name := arguments['function_name'].str()
|
||||
module_path := arguments['module_path'].str()
|
||||
result := d.create_mcp_tool_code(function_name, module_path) or {
|
||||
return mcp.error_tool_call_result(err)
|
||||
}
|
||||
return mcp.ToolCallResult{
|
||||
is_error: false
|
||||
content: result_to_mcp_tool_contents[string](result)
|
||||
}
|
||||
}
|
||||
|
||||
// Tool definition for the create_mcp_tool function
|
||||
const create_mcp_tool_const_tool = mcp.Tool{
|
||||
name: 'create_mcp_tool_const'
|
||||
description: 'Parses a V language function string and returns an MCP Tool struct. This tool analyzes function signatures, extracts parameters, and generates the appropriate MCP Tool representation.'
|
||||
input_schema: jsonschema.Schema{
|
||||
typ: 'object'
|
||||
properties: {
|
||||
'function': jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'string'
|
||||
})
|
||||
'types': jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'object'
|
||||
})
|
||||
}
|
||||
required: ['function']
|
||||
}
|
||||
}
|
||||
|
||||
pub fn (d &MCPGen) create_mcp_tool_const_tool_handler(arguments map[string]Any) !mcp.ToolCallResult {
|
||||
function := json.decode[code.Function](arguments['function'].str())!
|
||||
types := json.decode[map[string]string](arguments['types'].str())!
|
||||
result := d.create_mcp_tool(function, types) or { return mcp.error_tool_call_result(err) }
|
||||
return mcp.ToolCallResult{
|
||||
is_error: false
|
||||
content: result_to_mcp_tool_contents[string](result.str())
|
||||
}
|
||||
}
|
||||
|
||||
// Tool definition for the create_mcp_tool_handler function
|
||||
const create_mcp_tool_handler_tool = mcp.Tool{
|
||||
name: 'create_mcp_tool_handler'
|
||||
description: 'Generates a tool handler for the create_mcp_tool function. This tool handler accepts function string and types map and returns an MCP ToolCallResult.'
|
||||
input_schema: jsonschema.Schema{
|
||||
typ: 'object'
|
||||
properties: {
|
||||
'function': jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'string'
|
||||
})
|
||||
'types': jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'object'
|
||||
})
|
||||
'result': jsonschema.SchemaRef(jsonschema.Schema{
|
||||
typ: 'string'
|
||||
})
|
||||
}
|
||||
required: ['function', 'result']
|
||||
}
|
||||
}
|
||||
|
||||
// Tool handler for the create_mcp_tool_handler function
|
||||
pub fn (d &MCPGen) create_mcp_tool_handler_tool_handler(arguments map[string]Any) !mcp.ToolCallResult {
|
||||
function := json.decode[code.Function](arguments['function'].str())!
|
||||
types := json.decode[map[string]string](arguments['types'].str())!
|
||||
result_ := arguments['result'].str()
|
||||
result := d.create_mcp_tool_handler(function, types, result_) or {
|
||||
return mcp.error_tool_call_result(err)
|
||||
}
|
||||
return mcp.ToolCallResult{
|
||||
is_error: false
|
||||
content: result_to_mcp_tool_contents[string](result)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"function_pointers": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"module_path": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": ["name", "module_path"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": ["function_pointers"]
|
||||
}
|
||||
35
lib/ai/mcp/mcpgen/server.v
Normal file
35
lib/ai/mcp/mcpgen/server.v
Normal file
@@ -0,0 +1,35 @@
|
||||
module mcpgen
|
||||
|
||||
import freeflowuniverse.herolib.ai.mcp.logger
|
||||
import freeflowuniverse.herolib.ai.mcp
|
||||
|
||||
@[heap]
|
||||
pub struct MCPGen {}
|
||||
|
||||
pub fn new_mcp_server(v &MCPGen) !&mcp.Server {
|
||||
logger.info('Creating new Developer MCP server')
|
||||
|
||||
// Initialize the server with the empty handlers map
|
||||
mut server := mcp.new_server(mcp.MemoryBackend{
|
||||
tools: {
|
||||
'create_mcp_tool_code': create_mcp_tool_code_tool
|
||||
'create_mcp_tool_const': create_mcp_tool_const_tool
|
||||
'create_mcp_tool_handler': create_mcp_tool_handler_tool
|
||||
'create_mcp_tools_code': create_mcp_tools_code_tool
|
||||
}
|
||||
tool_handlers: {
|
||||
'create_mcp_tool_code': v.create_mcp_tool_code_tool_handler
|
||||
'create_mcp_tool_const': v.create_mcp_tool_const_tool_handler
|
||||
'create_mcp_tool_handler': v.create_mcp_tool_handler_tool_handler
|
||||
'create_mcp_tools_code': v.create_mcp_tools_code_tool_handler
|
||||
}
|
||||
}, mcp.ServerParams{
|
||||
config: mcp.ServerConfiguration{
|
||||
server_info: mcp.ServerInfo{
|
||||
name: 'mcpgen'
|
||||
version: '1.0.0'
|
||||
}
|
||||
}
|
||||
})!
|
||||
return server
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
// @{tool_name} MCP Tool
|
||||
// @{tool.description}
|
||||
|
||||
const @{tool_name}_tool = @{tool.str()}
|
||||
|
||||
11
lib/ai/mcp/mcpgen/templates/tool_handler.v.template
Normal file
11
lib/ai/mcp/mcpgen/templates/tool_handler.v.template
Normal file
@@ -0,0 +1,11 @@
|
||||
pub fn (d &MCPGen) @{function.name}_tool_handler(arguments map[string]Any) !mcp.ToolCallResult {
|
||||
@{decode_stmts}
|
||||
result := @{function_call}
|
||||
or {
|
||||
return mcp.error_tool_call_result(err)
|
||||
}
|
||||
return mcp.ToolCallResult{
|
||||
is_error: false
|
||||
content: mcp.result_to_mcp_tool_contents[@{result.symbol()}](result)
|
||||
}
|
||||
}
|
||||
1
lib/ai/mcp/mcpgen/templates/tools_file.v.template
Normal file
1
lib/ai/mcp/mcpgen/templates/tools_file.v.template
Normal file
@@ -0,0 +1 @@
|
||||
@for import in
|
||||
93
lib/ai/mcp/model_configuration.v
Normal file
93
lib/ai/mcp/model_configuration.v
Normal file
@@ -0,0 +1,93 @@
|
||||
module mcp
|
||||
|
||||
import time
|
||||
import os
|
||||
import log
|
||||
import x.json2
|
||||
import freeflowuniverse.herolib.schemas.jsonrpc
|
||||
|
||||
const protocol_version = '2024-11-05'
|
||||
// MCP server implementation using stdio transport
|
||||
// Based on https://modelcontextprotocol.io/docs/concepts/transports
|
||||
|
||||
// ClientConfiguration represents the parameters for the initialize request
|
||||
pub struct ClientConfiguration {
|
||||
pub:
|
||||
protocol_version string @[json: 'protocolVersion']
|
||||
capabilities ClientCapabilities
|
||||
client_info ClientInfo @[json: 'clientInfo']
|
||||
}
|
||||
|
||||
// ClientCapabilities represents the client capabilities
|
||||
pub struct ClientCapabilities {
|
||||
pub:
|
||||
roots RootsCapability // Ability to provide filesystem roots
|
||||
sampling SamplingCapability // Support for LLM sampling requests
|
||||
experimental ExperimentalCapability // Describes support for non-standard experimental features
|
||||
}
|
||||
|
||||
// RootsCapability represents the roots capability
|
||||
pub struct RootsCapability {
|
||||
pub:
|
||||
list_changed bool @[json: 'listChanged']
|
||||
}
|
||||
|
||||
// SamplingCapability represents the sampling capability
|
||||
pub struct SamplingCapability {}
|
||||
|
||||
// ExperimentalCapability represents the experimental capability
|
||||
pub struct ExperimentalCapability {}
|
||||
|
||||
// ClientInfo represents the client information
|
||||
pub struct ClientInfo {
|
||||
pub:
|
||||
name string
|
||||
version string
|
||||
}
|
||||
|
||||
// ServerConfiguration represents the server configuration
|
||||
pub struct ServerConfiguration {
|
||||
pub:
|
||||
protocol_version string = '2024-11-05' @[json: 'protocolVersion']
|
||||
capabilities ServerCapabilities
|
||||
server_info ServerInfo @[json: 'serverInfo']
|
||||
}
|
||||
|
||||
// ServerCapabilities represents the server capabilities
|
||||
pub struct ServerCapabilities {
|
||||
pub:
|
||||
logging LoggingCapability
|
||||
prompts PromptsCapability
|
||||
resources ResourcesCapability
|
||||
tools ToolsCapability
|
||||
}
|
||||
|
||||
// LoggingCapability represents the logging capability
|
||||
pub struct LoggingCapability {
|
||||
}
|
||||
|
||||
// PromptsCapability represents the prompts capability
|
||||
pub struct PromptsCapability {
|
||||
pub:
|
||||
list_changed bool = true @[json: 'listChanged']
|
||||
}
|
||||
|
||||
// ResourcesCapability represents the resources capability
|
||||
pub struct ResourcesCapability {
|
||||
pub:
|
||||
subscribe bool = true @[json: 'subscribe']
|
||||
list_changed bool = true @[json: 'listChanged']
|
||||
}
|
||||
|
||||
// ToolsCapability represents the tools capability
|
||||
pub struct ToolsCapability {
|
||||
pub:
|
||||
list_changed bool = true @[json: 'listChanged']
|
||||
}
|
||||
|
||||
// ServerInfo represents the server information
|
||||
pub struct ServerInfo {
|
||||
pub:
|
||||
name string = 'HeroLibMCPServer'
|
||||
version string = '1.0.0'
|
||||
}
|
||||
91
lib/ai/mcp/model_configuration_test.v
Normal file
91
lib/ai/mcp/model_configuration_test.v
Normal file
@@ -0,0 +1,91 @@
|
||||
module mcp
|
||||
|
||||
import freeflowuniverse.herolib.schemas.jsonrpc
|
||||
import json
|
||||
|
||||
// This file contains tests for the MCP initialize handler implementation.
|
||||
// It tests the handler's ability to process initialize requests according to the MCP specification.
|
||||
|
||||
// test_json_serialization_deserialization tests the JSON serialization and deserialization of initialize request and response
|
||||
fn test_json_serialization_deserialization() {
|
||||
// Create a sample initialize params object
|
||||
params := ClientConfiguration{
|
||||
protocol_version: '2024-11-05'
|
||||
capabilities: ClientCapabilities{
|
||||
roots: RootsCapability{
|
||||
list_changed: true
|
||||
}
|
||||
// sampling: SamplingCapability{}
|
||||
}
|
||||
client_info: ClientInfo{
|
||||
name: 'mcp-inspector'
|
||||
// version: '0.0.1'
|
||||
}
|
||||
}
|
||||
|
||||
// Serialize the params to JSON
|
||||
params_json := json.encode(params)
|
||||
|
||||
// Verify the JSON structure has the correct camelCase keys
|
||||
assert params_json.contains('"protocolVersion":"2024-11-05"'), 'JSON should have protocolVersion in camelCase'
|
||||
assert params_json.contains('"clientInfo":{'), 'JSON should have clientInfo in camelCase'
|
||||
assert params_json.contains('"listChanged":true'), 'JSON should have listChanged in camelCase'
|
||||
|
||||
// Deserialize the JSON back to a struct
|
||||
deserialized_params := json.decode(ClientConfiguration, params_json) or {
|
||||
assert false, 'Failed to deserialize params: ${err}'
|
||||
return
|
||||
}
|
||||
|
||||
// Verify the deserialized object matches the original
|
||||
assert deserialized_params.protocol_version == params.protocol_version, 'Deserialized protocol_version should match original'
|
||||
assert deserialized_params.client_info.name == params.client_info.name, 'Deserialized client_info.name should match original'
|
||||
assert deserialized_params.client_info.version == params.client_info.version, 'Deserialized client_info.version should match original'
|
||||
assert deserialized_params.capabilities.roots.list_changed == params.capabilities.roots.list_changed, 'Deserialized capabilities.roots.list_changed should match original'
|
||||
|
||||
// Now test the response serialization/deserialization
|
||||
response := ServerConfiguration{
|
||||
protocol_version: '2024-11-05'
|
||||
capabilities: ServerCapabilities{
|
||||
logging: LoggingCapability{}
|
||||
prompts: PromptsCapability{
|
||||
list_changed: true
|
||||
}
|
||||
resources: ResourcesCapability{
|
||||
subscribe: true
|
||||
list_changed: true
|
||||
}
|
||||
tools: ToolsCapability{
|
||||
list_changed: true
|
||||
}
|
||||
}
|
||||
server_info: ServerInfo{
|
||||
name: 'HeroLibMCPServer'
|
||||
version: '1.0.0'
|
||||
}
|
||||
}
|
||||
|
||||
// Serialize the response to JSON
|
||||
response_json := json.encode(response)
|
||||
|
||||
// Verify the JSON structure has the correct camelCase keys
|
||||
assert response_json.contains('"protocolVersion":"2024-11-05"'), 'JSON should have protocolVersion in camelCase'
|
||||
assert response_json.contains('"serverInfo":{'), 'JSON should have serverInfo in camelCase'
|
||||
assert response_json.contains('"listChanged":true'), 'JSON should have listChanged in camelCase'
|
||||
assert response_json.contains('"subscribe":true'), 'JSON should have subscribe field'
|
||||
|
||||
// Deserialize the JSON back to a struct
|
||||
deserialized_response := json.decode(ServerConfiguration, response_json) or {
|
||||
assert false, 'Failed to deserialize response: ${err}'
|
||||
return
|
||||
}
|
||||
|
||||
// Verify the deserialized object matches the original
|
||||
assert deserialized_response.protocol_version == response.protocol_version, 'Deserialized protocol_version should match original'
|
||||
assert deserialized_response.server_info.name == response.server_info.name, 'Deserialized server_info.name should match original'
|
||||
assert deserialized_response.server_info.version == response.server_info.version, 'Deserialized server_info.version should match original'
|
||||
assert deserialized_response.capabilities.prompts.list_changed == response.capabilities.prompts.list_changed, 'Deserialized capabilities.prompts.list_changed should match original'
|
||||
assert deserialized_response.capabilities.resources.subscribe == response.capabilities.resources.subscribe, 'Deserialized capabilities.resources.subscribe should match original'
|
||||
assert deserialized_response.capabilities.resources.list_changed == response.capabilities.resources.list_changed, 'Deserialized capabilities.resources.list_changed should match original'
|
||||
assert deserialized_response.capabilities.tools.list_changed == response.capabilities.tools.list_changed, 'Deserialized capabilities.tools.list_changed should match original'
|
||||
}
|
||||
42
lib/ai/mcp/model_error.v
Normal file
42
lib/ai/mcp/model_error.v
Normal file
@@ -0,0 +1,42 @@
|
||||
module mcp
|
||||
|
||||
import freeflowuniverse.herolib.schemas.jsonrpc
|
||||
|
||||
// resource_not_found indicates that the requested resource doesn't exist.
|
||||
// This error is returned when the resource specified in the request is not found.
|
||||
// Error code: -32002
|
||||
pub fn resource_not_found(uri string) jsonrpc.RPCError {
|
||||
return jsonrpc.RPCError{
|
||||
code: -32002
|
||||
message: 'Resource not found'
|
||||
data: 'The requested resource ${uri} was not found.'
|
||||
}
|
||||
}
|
||||
|
||||
fn prompt_not_found(name string) jsonrpc.RPCError {
|
||||
return jsonrpc.RPCError{
|
||||
code: -32602 // Invalid params
|
||||
message: 'Prompt not found: ${name}'
|
||||
}
|
||||
}
|
||||
|
||||
fn missing_required_argument(arg_name string) jsonrpc.RPCError {
|
||||
return jsonrpc.RPCError{
|
||||
code: -32602 // Invalid params
|
||||
message: 'Missing required argument: ${arg_name}'
|
||||
}
|
||||
}
|
||||
|
||||
fn tool_not_found(name string) jsonrpc.RPCError {
|
||||
return jsonrpc.RPCError{
|
||||
code: -32602 // Invalid params
|
||||
message: 'Tool not found: ${name}'
|
||||
}
|
||||
}
|
||||
|
||||
fn sampling_error(message string) jsonrpc.RPCError {
|
||||
return jsonrpc.RPCError{
|
||||
code: -32603 // Internal error
|
||||
message: 'Sampling error: ${message}'
|
||||
}
|
||||
}
|
||||
2
lib/ai/mcp/pugconvert/cmd/.gitignore
vendored
Normal file
2
lib/ai/mcp/pugconvert/cmd/.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
main
|
||||
|
||||
16
lib/ai/mcp/pugconvert/cmd/compile.sh
Executable file
16
lib/ai/mcp/pugconvert/cmd/compile.sh
Executable file
@@ -0,0 +1,16 @@
|
||||
#!/bin/bash
|
||||
set -ex
|
||||
|
||||
export name="mcp_pugconvert"
|
||||
|
||||
# Change to the directory containing this script
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
# Compile the V program
|
||||
v -n -w -gc none -cc tcc -d use_openssl -enable-globals main.v
|
||||
|
||||
# Ensure the binary is executable
|
||||
chmod +x main
|
||||
mv main ~/hero/bin/${name}
|
||||
|
||||
echo "Compilation successful. Binary '${name}' is ready."
|
||||
17
lib/ai/mcp/pugconvert/cmd/main.v
Normal file
17
lib/ai/mcp/pugconvert/cmd/main.v
Normal file
@@ -0,0 +1,17 @@
|
||||
module main
|
||||
|
||||
import freeflowuniverse.herolib.ai.mcp.servers.pugconvert.mcp
|
||||
|
||||
fn main() {
|
||||
// Create a new MCP server
|
||||
mut server := mcp.new_mcp_server() or {
|
||||
eprintln('Failed to create MCP server: ${err}')
|
||||
return
|
||||
}
|
||||
|
||||
// Start the server
|
||||
server.start() or {
|
||||
eprintln('Failed to start MCP server: ${err}')
|
||||
return
|
||||
}
|
||||
}
|
||||
203
lib/ai/mcp/pugconvert/logic/convertpug.v
Normal file
203
lib/ai/mcp/pugconvert/logic/convertpug.v
Normal file
@@ -0,0 +1,203 @@
|
||||
module pugconvert
|
||||
|
||||
import freeflowuniverse.herolib.clients.openai
|
||||
import freeflowuniverse.herolib.core.texttools
|
||||
import freeflowuniverse.herolib.core.pathlib
|
||||
import json
|
||||
|
||||
pub fn convert_pug(mydir string) ! {
|
||||
mut d := pathlib.get_dir(path: mydir, create: false)!
|
||||
list := d.list(regex: [r'.*\.pug$'], include_links: false, files_only: true)!
|
||||
for item in list.paths {
|
||||
convert_pug_file(item.path)!
|
||||
}
|
||||
}
|
||||
|
||||
// extract_template parses AI response content to extract just the template
|
||||
fn extract_template(raw_content string) string {
|
||||
mut content := raw_content
|
||||
|
||||
// First check for </think> tag
|
||||
if content.contains('</think>') {
|
||||
content = content.split('</think>')[1].trim_space()
|
||||
}
|
||||
|
||||
// Look for ```jet code block
|
||||
if content.contains('```jet') {
|
||||
parts := content.split('```jet')
|
||||
if parts.len > 1 {
|
||||
end_parts := parts[1].split('```')
|
||||
if end_parts.len > 0 {
|
||||
content = end_parts[0].trim_space()
|
||||
}
|
||||
}
|
||||
} else if content.contains('```') {
|
||||
// If no ```jet, look for regular ``` code block
|
||||
parts := content.split('```')
|
||||
if parts.len >= 2 {
|
||||
// Take the content between the first set of ```
|
||||
// This handles both ```content``` and cases where there's only an opening ```
|
||||
content = parts[1].trim_space()
|
||||
|
||||
// If we only see an opening ``` but no closing, cleanup any remaining backticks
|
||||
// to avoid incomplete formatting markers
|
||||
if !content.contains('```') {
|
||||
content = content.replace('`', '')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return content
|
||||
}
|
||||
|
||||
pub fn convert_pug_file(myfile string) ! {
|
||||
println(myfile)
|
||||
|
||||
// Create new file path by replacing .pug extension with .jet
|
||||
jet_file := myfile.replace('.pug', '.jet')
|
||||
|
||||
// Check if jet file already exists, if so skip processing
|
||||
mut jet_path_exist := pathlib.get_file(path: jet_file, create: false)!
|
||||
if jet_path_exist.exists() {
|
||||
println('Jet file already exists: ${jet_file}. Skipping conversion.')
|
||||
return
|
||||
}
|
||||
|
||||
mut content_path := pathlib.get_file(path: myfile, create: false)!
|
||||
content := content_path.read()!
|
||||
|
||||
mut l := loader()
|
||||
mut client := openai.get()!
|
||||
|
||||
base_instruction := '
|
||||
You are a template language converter. You convert Pug templates to Jet templates.
|
||||
|
||||
The target template language, Jet, is defined as follows:
|
||||
'
|
||||
|
||||
base_user_prompt := '
|
||||
Convert this following Pug template to Jet:
|
||||
|
||||
only output the resulting template, no explanation, no steps, just the jet template
|
||||
'
|
||||
|
||||
// We'll retry up to 5 times if validation fails
|
||||
max_attempts := 5
|
||||
mut attempts := 0
|
||||
mut is_valid := false
|
||||
mut error_message := ''
|
||||
mut template := ''
|
||||
|
||||
for attempts < max_attempts && !is_valid {
|
||||
attempts++
|
||||
|
||||
mut system_content := texttools.dedent(base_instruction) + '\n' + l.jet()
|
||||
mut user_prompt := ''
|
||||
|
||||
// Create different prompts for first attempt vs retries
|
||||
if attempts == 1 {
|
||||
// First attempt - convert from PUG
|
||||
user_prompt = texttools.dedent(base_user_prompt) + '\n' + content
|
||||
|
||||
// Print what we're sending to the AI service
|
||||
println('Sending to OpenAI for conversion:')
|
||||
println('--------------------------------')
|
||||
println(content)
|
||||
println('--------------------------------')
|
||||
} else {
|
||||
// Retries - focus on fixing the previous errors
|
||||
println('Attempt ${attempts}: Retrying with error feedback')
|
||||
user_prompt = '
|
||||
The previous Jet template conversion had the following error:
|
||||
ERROR: ${error_message}
|
||||
|
||||
Here was the template that had errors:
|
||||
```
|
||||
${template}
|
||||
```
|
||||
|
||||
The original pug input was was
|
||||
```
|
||||
${content}
|
||||
```
|
||||
|
||||
Please fix the template and try again. Learn from feedback and check which jet template was created.
|
||||
Return only the corrected Jet template.
|
||||
Dont send back more information than the fixed template, make sure its in jet format.
|
||||
|
||||
' // Print what we're sending for the retry
|
||||
|
||||
println('Sending to OpenAI for correction:')
|
||||
println('--------------------------------')
|
||||
println(user_prompt)
|
||||
println('--------------------------------')
|
||||
}
|
||||
|
||||
mut m := openai.Messages{
|
||||
messages: [
|
||||
openai.Message{
|
||||
role: .system
|
||||
content: system_content
|
||||
},
|
||||
openai.Message{
|
||||
role: .user
|
||||
content: user_prompt
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
// Create a chat completion request
|
||||
res := client.chat_completion(
|
||||
msgs: m
|
||||
model: 'deepseek-r1-distill-llama-70b'
|
||||
max_completion_tokens: 64000
|
||||
)!
|
||||
|
||||
println('-----')
|
||||
|
||||
// Print AI response before extraction
|
||||
println('Response received from AI:')
|
||||
println('--------------------------------')
|
||||
println(res.choices[0].message.content)
|
||||
println('--------------------------------')
|
||||
|
||||
// Extract the template from the AI response
|
||||
template = extract_template(res.choices[0].message.content)
|
||||
|
||||
println('Extracted template for ${myfile}:')
|
||||
println('--------------------------------')
|
||||
println(template)
|
||||
println('--------------------------------')
|
||||
|
||||
// Validate the template
|
||||
validation_result := jetvaliditycheck(template) or {
|
||||
// If validation service is unavailable, we'll just proceed with the template
|
||||
println('Warning: Template validation service unavailable: ${err}')
|
||||
break
|
||||
}
|
||||
|
||||
// Check if template is valid
|
||||
if validation_result.is_valid {
|
||||
is_valid = true
|
||||
println('Template validation successful!')
|
||||
} else {
|
||||
error_message = validation_result.error
|
||||
println('Template validation failed: ${error_message}')
|
||||
}
|
||||
}
|
||||
|
||||
// Report the validation outcome
|
||||
if is_valid {
|
||||
println('Successfully converted template after ${attempts} attempt(s)')
|
||||
// Create the file and write the processed content
|
||||
println('Converted to: ${jet_file}')
|
||||
mut jet_path := pathlib.get_file(path: jet_file, create: true)!
|
||||
jet_path.write(template)!
|
||||
} else if attempts >= max_attempts {
|
||||
println('Warning: Could not validate template after ${max_attempts} attempts')
|
||||
println('Using best attempt despite validation errors: ${error_message}')
|
||||
jet_file2 := jet_file.replace('.jet', '_error.jet')
|
||||
mut jet_path2 := pathlib.get_file(path: jet_file2, create: true)!
|
||||
jet_path2.write(template)!
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user