Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions dotnet/src/Skills/Skills.Grpc/GrpcOperationRunner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ private object GenerateOperationRequest(GrpcOperation operation, Type type, IDic
throw new GrpcOperationException($"No '{GrpcOperation.PayloadArgumentName}' argument representing gRPC request message is found for the '{operation.Name}' gRPC operation.");
}

//Deserializing JOSN payload to gRPC request message
//Deserializing JSON payload to gRPC request message
var instance = JsonSerializer.Deserialize(payload, type, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
if (instance == null)
{
Expand Down Expand Up @@ -212,7 +212,7 @@ private static Type BuildGrpcOperationDataContractType(GrpcOperationDataContract
setterIl.Emit(OpCodes.Stfld, fieldBuilder);
setterIl.Emit(OpCodes.Ret);

//Registering the property get and set methods.
//Registering the property get and set methods.
propertyBuilder.SetGetMethod(getterBuilder);
propertyBuilder.SetSetMethod(setterBuilder);

Expand Down
39 changes: 39 additions & 0 deletions samples/java/JavaReferenceSkill/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/

### IntelliJ IDEA ###
.idea
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr

### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache

### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/

### VS Code ###
.vscode/

### Mac OS ###
.DS_Store
23 changes: 23 additions & 0 deletions samples/java/JavaReferenceSkill/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Java Reference Skill gRPC Server
This is a sample Java gRPC server that can be invoked via SK's gRPC client as a Native Skill/Function. The purpose of this project is to demonstrate how Polyglot skills can be supported using either REST or gRPC.

## Prerequisites
* Java 17
* Maven

## Build
To build the project, run the following command:
```
mvn clean package
```
To generate the gRPC classes, run the following command:
```
mvn protobuf:compile
```

## Run
To run the project, run the following command:
```
java -jar ./target/JavaReferenceSkill-1.0-SNAPSHOT-jar-with-dependencies.jar
```

109 changes: 109 additions & 0 deletions samples/java/JavaReferenceSkill/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.microsoft.semantickernel.skills.random</groupId>
<artifactId>JavaReferenceSkill</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<grpc.version>1.54.0</grpc.version>
<javax.annotation-api.version>1.2</javax.annotation-api.version>
<os-maven-plugin.version>1.7.1</os-maven-plugin.version>
<protobuf-maven-plugin.version>0.6.1</protobuf-maven-plugin.version>
<protoc.version>3.22.2</protoc.version>
<mockito-core.version>5.2.0</mockito-core.version>
</properties>

<dependencies>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-stub</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-testing</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty-shaded</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito-core.version}</version>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>${javax.annotation-api.version}</version>
</dependency>
</dependencies>

<build>
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>${os-maven-plugin.version}</version>
</extension>
</extensions>
<plugins>
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>${protobuf-maven-plugin.version}</version>
<configuration>
<protocArtifact>com.google.protobuf:protoc:${protoc.version}:exe:${os.detected.classifier}</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>com.microsoft.semantickernel.skills.random.Main</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>

</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.microsoft.semantickernel.skills.random;

import io.grpc.Server;
import io.grpc.ServerBuilder;

import java.util.logging.Logger;

public class Main {

private static final int PORT = 50051;

public static void main(String[] args) {
Logger logger = java.util.logging.Logger.getLogger(Main.class.getName());

Server server = ServerBuilder.forPort(PORT)
.addService(new RandomActivitySkill()).build();

System.out.println("Starting server...");
try {
server.start();
System.out.println("gRPC Server for random activity started on port " + PORT);
server.awaitTermination();
} catch (Exception e) {
logger.severe("Error with request: " + e.getMessage());
throw new RuntimeException(e);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package com.microsoft.semantickernel.skills.random;

import io.grpc.stub.StreamObserver;
import reference_skill.ActivityOuterClass;
import reference_skill.RandomActivitySkillGrpc;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Logger;

public class RandomActivitySkill extends RandomActivitySkillGrpc.RandomActivitySkillImplBase {

public static final String API_ACTIVITY_URL = "https://www.boredapi.com/api/activity";

/**
* <pre>
* GetRandomActivity is an RPC method that retrieves a random activity from an API.
* </pre>
*
* @param request
* @param responseObserver
*/
@Override
public void getRandomActivity(ActivityOuterClass.GetRandomActivityRequest request, StreamObserver<ActivityOuterClass.GetRandomActivityResponse> responseObserver) {
Comment thread
thegovind marked this conversation as resolved.
Logger logger = java.util.logging.Logger.getLogger(this.getClass().getName());
HttpClient httpClient = HttpClient.newHttpClient();
HttpRequest httpRequest = HttpRequest.newBuilder()
.uri(URI.create(API_ACTIVITY_URL))
.build();
try {
CompletableFuture<HttpResponse<String>> response = httpClient.sendAsync(httpRequest, HttpResponse.BodyHandlers.ofString());
logger.info("Response: " + response.get().body());
responseObserver.onNext(ActivityOuterClass.GetRandomActivityResponse.newBuilder().setActivity(response.get().body()).build());
responseObserver.onCompleted();
} catch (Exception e) {
logger.severe("Error with request: " + e.getMessage());
}
}
}
30 changes: 30 additions & 0 deletions samples/java/JavaReferenceSkill/src/main/proto/activity.proto
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
syntax = "proto3";

package reference_skill;

// GetRandomActivityRequest is a message that contains input for the GetRandomActivity RPC method.
message GetRandomActivityRequest {
string input = 1; // Input is a hobby that is use to generate a random activity.
}

// GetRandomActivityResponse is a message that contains the activity returned by the GetRandomActivity RPC method.
message GetRandomActivityResponse {
string activity = 1; // Activity is a description of the random activity.
}

// RandomActivitySkill is a service that provides methods related to random activities.
service RandomActivitySkill {
// GetRandomActivity is an RPC method that retrieves a random activity from an API.
rpc GetRandomActivity (GetRandomActivityRequest) returns (GetRandomActivityResponse);
}

// Activity is a message that represents an activity with its various properties.
message Activity {
string activity = 1; // A description of the activity.
string type = 2; // The type or category of the activity.
int32 participants = 3; // The number of participants required for the activity.
double price = 4; // The cost associated with the activity, from 0 (free) to 1 (most expensive).
string link = 5; // A URL providing more information about the activity.
string key = 6; // A unique identifier for the activity.
float accessibility = 7; // The accessibility of the activity, from 0 (most accessible) to 1 (least accessible).
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package com.microsoft.semantickernel.skills.random;

import io.grpc.stub.StreamObserver;
import io.grpc.testing.GrpcServerRule;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import reference_skill.ActivityOuterClass;
import reference_skill.RandomActivitySkillGrpc;

import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.CompletableFuture;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;

public class RandomActivitySkillTest {

@Rule
public GrpcServerRule grpcServerRule = new GrpcServerRule().directExecutor();

private RandomActivitySkillGrpc.RandomActivitySkillBlockingStub blockingStub;

@Before
public void setUp() {
grpcServerRule.getServiceRegistry().addService(new RandomActivitySkill());
blockingStub = RandomActivitySkillGrpc.newBlockingStub(grpcServerRule.getChannel());
}

@Test
public void testGetRandomActivity() throws Exception {
HttpClient httpClient = mock(HttpClient.class);
HttpResponse<String> httpResponse = mock(HttpResponse.class);
CompletableFuture<HttpResponse<String>> responseFuture = CompletableFuture.completedFuture(httpResponse);

when(httpClient.sendAsync(any(HttpRequest.class), any(HttpResponse.BodyHandler.class))).thenReturn(responseFuture);
when(httpResponse.body()).thenReturn("{\"activity\":\"Test Activity\"}");

RandomActivitySkill randomActivitySkill = new RandomActivitySkill() {
};

ActivityOuterClass.GetRandomActivityRequest request = ActivityOuterClass.GetRandomActivityRequest.newBuilder().build();
StreamObserver<ActivityOuterClass.GetRandomActivityResponse> responseObserver = mock(StreamObserver.class);
randomActivitySkill.getRandomActivity(request, responseObserver);

verify(responseObserver).onNext(any(ActivityOuterClass.GetRandomActivityResponse.class));
verify(responseObserver).onCompleted();
}
}