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
73 changes: 64 additions & 9 deletions examples/client.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,85 @@
"""Main module for the tests."""

import argparse
import asyncio
import logging
from collections.abc import AsyncGenerator

from connect.connect import UnaryRequest
from connect.connect import StreamRequest, UnaryRequest, ensure_single
from connect.connection_pool import AsyncConnectionPool

from proto.connectrpc.eliza.v1.eliza_pb2 import SayRequest
from proto.connectrpc.eliza.v1.eliza_pb2 import IntroduceRequest, ReflectRequest, SayRequest
from proto.connectrpc.eliza.v1.v1connect.eliza_connect_pb2 import ElizaServiceClient

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

async def run_unary(client: ElizaServiceClient) -> None:
"""Run unary RPC (Say)."""
request = UnaryRequest(SayRequest(sentence="Hi"))
response = await client.Say(request)

print(f"Response: {response.message.sentence}")


async def run_server_streaming(client: ElizaServiceClient) -> None:
"""Run server streaming RPC (Introduce)."""

async def request_generator() -> AsyncGenerator[IntroduceRequest]:
yield IntroduceRequest(name="Alice")

request = StreamRequest(request_generator())

message_count = 1
async with client.Introduce(request) as response:
async for message in response.messages:
print(f"Received message {message_count}: {message.sentence}")
message_count += 1


async def run_client_streaming(client: ElizaServiceClient) -> None:
"""Run client streaming RPC (Reflect)."""

async def request_generator() -> AsyncGenerator[ReflectRequest]:
for i in range(5):
yield ReflectRequest(sentence=f"Alice is thinking... {i}")

request = StreamRequest(request_generator())
async with client.Reflect(request) as response:
message = await ensure_single(response.messages)

print(f"Final response: {message.sentence}")


async def main() -> None:
"""Interact with the ElizaServiceClient asynchronously."""
parser = argparse.ArgumentParser(description="Eliza client with different RPC types")
parser.add_argument("-u", "--unary", action="store_true", help="Send unary RPC")
parser.add_argument("-ss", "--server-streaming", action="store_true", help="Send server streaming RPC")
parser.add_argument("-cs", "--client-streaming", action="store_true", help="Send client streaming RPC")

args = parser.parse_args()

if not any([args.unary, args.server_streaming, args.client_streaming]):
print("Please specify an RPC type: -u, -ss, or -cs")
return

if sum([args.unary, args.server_streaming, args.client_streaming]) > 1:
print("Please specify only one RPC type")
return

async with AsyncConnectionPool() as pool:
client = ElizaServiceClient(
pool=pool,
base_url="http://localhost:8080/",
)
response = await client.Say(UnaryRequest(SayRequest(sentence="I feel happy.")))

logger.debug(response.message.sentence)
for k, v in response.headers.items():
logger.debug(f"{k}: {v}")
try:
if args.unary:
await run_unary(client)
elif args.server_streaming:
await run_server_streaming(client)
elif args.client_streaming:
await run_client_streaming(client)
except Exception as e:
print(f"Error: {e}")


if __name__ == "__main__":
Expand Down
49 changes: 9 additions & 40 deletions examples/cmd/examples-go/client/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,6 @@ import (
"golang.org/x/net/http2"
)

type mode int

const (
modeClient mode = iota + 1
// for future use?
modeServer
)

type rpc int

Expand All @@ -34,37 +27,18 @@ const (
)

var (
runMode mode
rpcType rpc
)

func init() {
// mode
clientMode := flag.Bool("c", false, "run client mode")
serverMode := flag.Bool("s", false, "run server mode")
// rpc
unaryRPC := flag.Bool("u", false, "send unary RPC")
serverStreamingRPC := flag.Bool("ss", false, "send unary RPC")
clientStreamingRPC := flag.Bool("cs", false, "send unary RPC")
bidiRPC := flag.Bool("bidi", false, "send unary RPC")
serverStreamingRPC := flag.Bool("ss", false, "send server streaming RPC")
clientStreamingRPC := flag.Bool("cs", false, "send client streaming RPC")
bidiRPC := flag.Bool("bidi", false, "send bidirectional streaming RPC")

flag.Parse()

switch {
case *clientMode:
runMode = modeClient
case *serverMode:
runMode = modeServer
default: // throw
if !*clientMode && !*serverMode {
log.Fatal("either clientMode or serverMode must be enabled. [-c, -s]")
}
if *clientMode && *serverMode {
log.Fatal("neither clientMode nor serverMode can't be enabled")
}
panic("unreachable")
}

switch {
case *unaryRPC:
rpcType = unary
Expand All @@ -86,13 +60,8 @@ func asError(err error) (*connect.Error, bool) {
}

func main() {
switch runMode {
case modeClient:
if err := runClient(); err != nil {
log.Fatal(err)
}
case modeServer:
// TODO(tsubakiky): not implemented yet
if err := runClient(); err != nil {
log.Fatal(err)
}
}

Expand Down Expand Up @@ -129,10 +98,10 @@ func runClient() error {
fmt.Printf("res.Header(): %v\n", res.Header())

case clientStreaming:
stream := client.IntroduceClient(ctx)
stream := client.Reflect(ctx)
for range 5 {
err := stream.Send(&elizav1.IntroduceRequest{
Name: "Alice",
err := stream.Send(&elizav1.ReflectRequest{
Sentence: "Alice is thinking...",
})
if err != nil {
return err
Expand All @@ -154,7 +123,7 @@ func runClient() error {
request := connect.NewRequest(&elizav1.IntroduceRequest{
Name: "Alice",
})
stream, err := client.IntroduceServer(ctx, request)
stream, err := client.Introduce(ctx, request)
if err != nil {
return err
}
Expand Down
12 changes: 6 additions & 6 deletions examples/cmd/examples-go/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ func (e *elizaServer) Converse(
}
}

func (e *elizaServer) IntroduceServer(
func (e *elizaServer) Introduce(
ctx context.Context,
req *connect.Request[elizav1.IntroduceRequest],
stream *connect.ServerStream[elizav1.IntroduceResponse],
Expand Down Expand Up @@ -113,16 +113,16 @@ func (e *elizaServer) IntroduceServer(
return nil
}

func (e *elizaServer) IntroduceClient(ctx context.Context, stream *connect.ClientStream[elizav1.IntroduceRequest]) (*connect.Response[elizav1.IntroduceResponse], error) {
var messages string
func (e *elizaServer) Reflect(ctx context.Context, stream *connect.ClientStream[elizav1.ReflectRequest]) (*connect.Response[elizav1.ReflectResponse], error) {
var sentences string
for stream.Receive() {
messages += " " + stream.Msg().GetName()
sentences += stream.Msg().GetSentence()
}
if stream.Err() != nil {
return nil, stream.Err()
}
return connect.NewResponse(&elizav1.IntroduceResponse{
Sentence: messages,
return connect.NewResponse(&elizav1.ReflectResponse{
Sentence: sentences,
}), nil
}

Expand Down
139 changes: 139 additions & 0 deletions examples/eliza.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import random
import re
from re import Pattern

GOODBYE_INPUTS: set[str] = {"bye", "goodbye", "exit", "quit"}
GOODBYE_RESPONSES: list[str] = [
"Goodbye. It was nice talking to you.",
"Take care!",
"Farewell!",
]

INTRO_RESPONSES: list[str] = [
"Hello %s, I'm Eliza.",
"Nice to meet you, %s.",
]

ELIZA_FACTS: list[str] = [
"Did you know ELIZA was created in the 1960s?",
"I'm named after Eliza Doolittle from 'Pygmalion'.",
]

REFLECTED_WORDS: dict[str, str] = {
"am": "are",
"was": "were",
"i": "you",
"i'd": "you would",
"i've": "you have",
"i'll": "you will",
"my": "your",
"you": "me",
"are": "am",
"you're": "I am",
"you've": "I have",
"you'll": "I will",
"your": "my",
"yours": "mine",
"me": "you",
}

REQUEST_INPUT_REGEX_TO_RESPONSE_OPTIONS: dict[Pattern[str], list[str]] = {
re.compile(r"i need (.*)"): [
"Why do you need %s?",
"Would it really help you to get %s?",
"Are you sure you need %s?",
],
re.compile(r"why don'?t you ([^\?]*)\??"): [
"Do you really think I don't %s?",
"Perhaps eventually I will %s.",
"Do you really want me to %s?",
],
}

DEFAULT_RESPONSES: list[str] = [
"Please tell me more.",
"Let's change focus a bit… Tell me about your family.",
"Can you elaborate on that?",
]


def reply(user_input: str) -> tuple[str, bool]:
"""Respond to *user_input* in the style of a psychotherapist.

Parameters
----------
user_input :
The raw string entered by the user.

Returns
-------
tuple[str, bool]
- The response text.
- ``True`` if the conversation should end (i.e., user said goodbye);
otherwise ``False``.

"""
cleaned_input = _preprocess(user_input)
if cleaned_input in GOODBYE_INPUTS:
return _random_element(GOODBYE_RESPONSES), True

return _lookup_response(cleaned_input), False


def get_intro_responses(name: str) -> list[str]:
"""Generate introductory lines tailored to *name*.

Parameters
----------
name :
The conversation partner’s name.

Returns
-------
list[str]
A list of sentences Eliza might say at the start of a chat.

"""
intros = [template % name for template in INTRO_RESPONSES]
intros.append(_random_element(ELIZA_FACTS))
intros.append("How are you feeling today?")
return intros


def _lookup_response(cleaned_input: str) -> str:
for pattern, responses in REQUEST_INPUT_REGEX_TO_RESPONSE_OPTIONS.items():
match = pattern.search(cleaned_input)
if not match:
continue

response = _random_element(responses)
if "%s" not in response:
return response

fragment = _reflect(match.group(1))
return response % fragment

return _random_element(DEFAULT_RESPONSES)


def _preprocess(user_input: str) -> str:
"""Lower-case & trim punctuation/whitespace."""
return user_input.strip().lower().strip(".!?\"'")


def _reflect(fragment: str) -> str:
"""Swap first/second-person pronouns in *fragment*.

Example:
-------
"I am happy" -> "you are happy"

"""
words = fragment.split()
reflected = [REFLECTED_WORDS.get(word, word) for word in words]
return " ".join(reflected)


def _random_element(options: list[str]) -> str:
"""Return a random element from *options* (wrapper for :pyfunc:`random.choice`)."""
return random.choice(options)
Loading
Loading